By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

HTTP Requests and Redirects in PHP

PHP Tutorial on how to change the auto-follow redirects behavior of HTTP requests in PHP.

Edited: 2016-01-03 01:58

Last: Using Proxies with PHP Next: Cookie Handling

When you are performing HTTP requests with PHP, redirects will automatically be followed. To change this behavior, you would simply set the follow_location context option to 0.

By default PHP will automatically follow redirects, sometimes you may not want this to happen. The redirect.php file was intended for testing cookie deliverance with another scripting language, but it can also be used in this php tutorial.

$sURL = "http://brugbart.com/Examples/redirect.php"; // The Request URL

$aHTTP['http']['method']          = 'GET';
$aHTTP['http']['header']          = "User-Agent: MS DOS 6.0 Firefox Browser\r\n";
$aHTTP['http']['header']         .= "Referer: http://brugbart.com/\r\n";

$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);

echo $contents;

What happens when you run the above script, is that PHP visits the provided URL first, and then tries to follow the http location header redirect URL automatically. This can be a useless extra step under certain circumstances, and you may therefor want to disable it.

Disable auto-following of redirects

When you disable automatic redirects, extra data may sometimes become available. With php functions such as file_get_contents and fread, this will be in the form body content on the redirecting page. Some scripting languages won't remember response headers on the redirecting page, which may sometimes result in missing cookies – this does not seem to be the case with PHP however.

To disable these automatic redirects, simply set the follow_location context option to 0, then proceed with the request as you would normally:

$sURL = "http://brugbart.com/Examples/redirect.php"; // The Request URL

$aHTTP['http']['method']          = 'GET';
$aHTTP['http']['follow_location'] = 0;
$aHTTP['http']['header']          = "User-Agent: MS DOS 6.0 Firefox Browser\r\n";
$aHTTP['http']['header']         .= "Referer: http://brugbart.com/\r\n";

$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);

echo $contents;

The resulting body content should show up as:

You are being redirected to <a href="http://brugbart.com/Examples/redirect-destination.php">http://brugbart.com/Examples/redirect-destination.php</a>