How to receive data sent via the POST method in PHP
In PHP, $_POST is an array that stores data sent via the HTTP POST method, which can be sent in various ways.
When we talk about HTTP, we’re discussing the HTTP protocol, upon which the entire web is based. When you search using a browser, you’re actually using an HTTP client that accesses a page hosted on an HTTP Server like Apache, Nginx or IIS.
When we use HTTP POST, it allows us to securely send data. It’s very different from HTTP GET, as GET exposes the sent data in the URL.
HTTP POST also enables us to send files; in PHP, these files will be handled with the $_FILES
variable.
HTTP POST can be used for logging in, registering, managing carts, sending comments, etc. It doesn’t make sense to use GET for these purposes.
There are many ways to send a POST request to our PHP from HTML. When using a form, we use method="post"
, but we can also send posts with JavaScript.
<form action="enviar.php" method="post"> <label for="nombre">Nombre:</label> <input type="text" id="nombre" name="nombre" required> <br> <label for="email">Correo electrónico:</label> <input type="email" id="email" name="email" required> <br> <label for="mensaje">Mensaje:</label> <textarea id="mensaje" name="mensaje" required></textarea> <br> <input type="submit" value="Enviar"> </form>
In PHP, $_POST
is an array, so we need to specify what we want to retrieve.
In the HTML above, we see that in the inputs we have an attribute called “nombre”; this is used by the server to identify the fields in form submits
So, to know the value sent by the user in the first input in our PHP file, we use $_POST['nombre']
.
Below, you’ll see a way to send an HTTP POST request to our enviar.php file using the Fetch API. Keep in mind that we can’t cover all the ways to send an HTTP POST request, as it would be too extensive, so we’ll focus on this one for now.
const datos = { nombre: "Juan Pérez", correo: "juan.perez@ejemplo.com", mensaje: "Este es un mensaje de prueba.", }; fetch("enviar.php", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(datos), }) .then((response) => { if (response.ok) { console.log("Datos enviados correctamente"); } else { console.log("Error al enviar los datos"); } }) .catch((error) => { console.log("Error:", error); });