The header() function and redirection in PHP
The header() function in PHP allows us to send HTTP headers without formatting.
Before using this function, we have to clarify something. This function must be called before displaying anything on the screen, there must be no whitespace before this function, and no comments either.
Sintaxis
The header()
function in PHP has 3 parameters, of which 2 are optional ($replace
and $http_response_code
).
header(string $string[,bool $replace=true[,int $http_response_code]])
$string
Must contain the header string in string format.
$replace:
The $replace
parameter is an optional value within the header
function, which indicates whether a previous header should be replaced or a second header should be added. Its default value is TRUE
, which means it will replace the header.
$http_response_code:
This optional value forces the response code value. For example, the following values (404, 405, 403, 500). To learn more about these values, you can check the following documentation (EN | ES).
The most commonly used content types in $string are:
atomheader('Content-Type: application/atom+xml');CSS
header('Content-Type: text/css');Javascript
header('Content-Type: text/javascript');jpeg image
header('Content-Type: image/jpeg');json
header('Content-Type: application/json');
There is a very good example about header('Content-Type: application/json');
in PDO queries with PHP extension if you want to see how to use it.
header('Content-Type: application/pdf');rss
header('Content-Type: application/rss+xml; charset=ISO-8859-1');text
header('Content-Type: text/plain');xml
header('Content-Type: text/xml');
¿Cuándo usaría header()?
These are some examples of when we might use the header()
function in PHP:
- When processing a form and we need to redirect the user to another page.
- After a successful login, we might want to redirect the user to their profile page.
- When a page is no longer available at a certain URL and has permanently moved to a different URL.
- When we want to ensure that the user receives the correct error message.
header()
function is used in PHP to send any type of HTTP header that is necessary to control the response that is sent to the client.
404 Not Found
Page does not exist example:
<?php header("HTTP/1.0 404 Not Found"); ?>
header("HTTP/1.1 301 Moved Permanently"); header("Location: https://www.ejemplo.com/pagenotfound"); exit();
Redireccionamiento
When we want to redirect and use “Location:” in PHP
Redirect to index.phpheader('Location: /index.php');
This will redirect us to our index.php.
The Location response header instructs the browser to navigate to the specified page, and is only meaningful when accompanied by a 3xx (redirection) or 201 (created) status response.
Ejemplo de redireccionamientoheader("HTTP/1.1 301 Moved Permanently"); header("Location: {$x}"); exit();
In this case, $x
would be the new path of our page.
Ejemplos
Here’s an example of redirecting after entering a username and password.
This example is a simulation of a login. Keep in mind that for a real login, you would need to use databases. In this example, we will simply check if the entered username and password match the ones we want the user to use.
- (folder)
- index.php
- logged_in.php
Username: marcos
Password: elmarquitos3674
index.php<!doctype html> <html lang="es"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Ejemplo de función header()</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/main.css"> </head> <body> <style> .form_item{ width:100%; margin-bottom:10px; } .form_item label{ display:inline-block; width:100%; } .form_item input{ display:inline-block; width:100%; } .login{ width:400px; } </style> <h2>LOGIN</h2> <form class="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div class= "form_item"> <label for="fusername">UserName: </label> <input type="text" id="fusername" name="username"/> </div> <div class="form_item"> <label for="fpassword">Password: </label> <input type="password" id="fpassword" name="password"/> </div> <input type="submit" value="confirm"> </form> <?php if(isset($_POST['username'],$_POST['password'])): if($_POST['username']=="" || $_POST['password']==""){ echo "el password o el nombre de usuario no ha sido ingresado."; }else if($_POST['username'] == "marcos" && $_POST["password"] =="elmarquitos3674"){ session_start(); $_SESSION['user'] = "marcos"; header("Location:logged_in.php"); }else{ echo "No se encontro el usuario o el password"; } endif; ?> </body> </html>
The following file is where the user will be redirected to:
logged_in.php<?php session_start(); echo "Wellcome ".$_SESSION['user']; ?>