How to make a forwarding in PHP

Learn how to create a PHP redirect with examples & code snippets - quickly & easily redirect users to a different page.

Forwarding with PHP

In PHP, you can redirect a user from one page to another using the header() function. This function can be used to redirect a user from one page to another page or to a specified URL.

The simplest way to redirect a user by using the header() function is to use the following syntax:

header("Location: http://www.example.com/");
exit;

This code will redirect the user to the location specified in the Location header. The exit; statement is optional, but it is often included to ensure that the code after the header() function is not executed.

You can also pass additional parameters to the header() function to control the behavior of the redirect. One of the most useful parameters is the HTTP_REFERER parameter, which allows you to specify the URL of the page that the user was on before they were redirected. This can be useful if you want to redirect the user to a specific page based on where they came from.

The syntax for passing the HTTP_REFERER parameter to the header() function is as follows:

header("Location: http://www.example.com/", true, 307);
header("HTTP_REFERER: http://www.example.com/sourcepage.php");
exit;

This code will redirect the user to the location specified in the Location header and will set the HTTP_REFERER parameter to the specified URL. Again, the exit; statement is optional.

The header() function can also be used to set additional headers, such as the Content-Type header. This can be useful if you need to send a specific type of content to the user, such as an image or a PDF document.

The syntax for setting the Content-Type header is as follows:

header("Content-Type: application/pdf");
exit;

This code will set the Content-Type header to application/pdf. Again, the exit; statement is optional.

The header() function can also be used to send additional headers, such as the Cache-Control header, which can be used to control how a page is cached by the browser. The syntax for setting the Cache-Control header is as follows:

header("Cache-Control: no-cache, no-store, must-revalidate");
exit;

This code will set the Cache-Control header to no-cache, no-store, must-revalidate, which will instruct the browser not to cache the page. Again, the exit; statement is optional.

In summary, the header() function can be used to redirect a user from one page to another page or to a specified URL, as well as to set additional headers such as the Content-Type header or the Cache-Control header.

Answers (0)