TechnoPHP

PHP header() function | Redirect

PHP header() function is used to send HTTP header to the client. If you are working on a project and want to use the PHP header function that redirects to another page then you can use the header function.

The header function helps to send HTTP Header. If you want to redirect on another page after the success process. You need to define the http_response_code under the header function.

PHP Header function syntax



header(string,replace,http_response_code)
string- Header string to send(Required)

replace - Allows multiple headers of the same type(optional)

string- HTTP response code.

The header function prevents more than one header to be sent at once. If header has already sent , then you will got a fetal error like "header allready sent "

A following example of header() function will show you how to work header() function in PHP .

Login Exmple using Header



<?php
session_start ();
include ("config.php"); 

if(isset($_REQUEST['sub']))
{
$a = $_REQUEST['uname'];
$b = $_REQUEST['upassword'];

$res = mysqli_query($mysqli,"select* from users where uname='$a'and upassword='$b'");
$result=mysqli_fetch_array($res);
if($result)
{
	
	$_SESSION["login"]="1";
	header("location:index.php");//header 

}

//if condition is wrong .
else	
{
	header("location:login.php?err=1");//header
	
}
}
?>
Try Demo

In above example we have used PHP login script and header function . If condition is true then user redirect to the another page (index.php page) if condtion is wrong it will show an error on same login page . like "invalid username and password " .
We can define http response code as =>


header("location:index.php");
or
 
header("location:https://technosmarter.com/index.php");//complete URL path . To 
redirect the page 
after login or success 
process  etc .