PHP Scripts and Resources for Webmasters

PHP Redirect

This tutorial will demonstrate how to use PHP to perform a redirect. We will be using the PHP header function to send the HTTP headers required to perform the redirect. Note that the header function must must be called before any other output in your PHP script.

Location Header

The Location header is used to redirect the user agent (i.e. web browser, search engine spider, etc.) to some other URL. The following PHP code can be used to send the Location header:

<?php
header("Location: https://www.yourdomain.com/newpage.php");
exit;
?>

When the PHP header function sends this header, it will also send the temporary redirect (302) status code. The temporary redirect status code tells the user agent to continue to use the original URL.

Permanent Redirect

Often, you will want to send a permanent redirect (301) status code. A permanent redirect status code tells the user agent that the old URL should be discarded and the new URL should be used from now on. To send a permanent redirect status code, send the HTTP header before sending the Location header.

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.yourdomain.com/newpage.php");
exit;
?>

If you are using Apache HTTP server, these types of redirects can also be configured in a .htaccess file. Our .htaccess Tutorial describes how to configure a redirect in this manner.

Conditional Redirect

You can also use PHP code to send the redirect based on some desired condition. For example, the following code will only send the redirect if the user agent was referred from a specified domain:

<?php
$referer = $_SERVER['HTTP_REFERER'];
$domain_name = "somedomain.com";
if(strpos($referer, $domain_name)!== FALSE) {
	header("HTTP/1.1 301 Moved Permanently");
	header("Location: https://www.yourdomain.com/newpage.php");
	exit;
}
?>

Back to Tutorials