The most common way to execute redirects with PHP is to send headers to the client. This can be easily done with the header-Method of PHP.
<?php
header('location: http://www.example.org/foo/bar');
To avoid protocol collisions ( e.g. sending headers after a response body ) you may check the current state of your response and send only header informations if the protocol allows them:
<?php
if ( ! headers_sent($file, $line) ) {
header('location: http://www.example.org/foo/bar');
}
else {
echo 'Could not redirect you, headers are allready send in ['.$file.'] on line #'.$line.'.';
}
Protocol Standard: To send headers is the only method to ensure the execution of an redirect. HTTP/1.1 is an world wide implemented standardized protocol.
Another way to redirect safetly without taking care about any HTT-Protocol-Issue is to emulate an http-response refresh-header-field with meta-tags inside of your (x)HTML-Document ( respect the syntax difference of xHTML and HTML, the following source is HTML5 ):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Redirecting</title>
<meta http-equiv="refresh" content="5; http://www.example.org/foo/bar">
</head>
<body>
<p>Redirecting you to the next page, please wait...
If nothing happens please click <a href="http://example.org/foo/bar">here</a>.</p>
</body>
</html>
The meta
-tag serves an http-equiv
-property that defines the http-protocol header-field equivalent of the contained string:refresh
( instead of location
). The content
-property defines the time in seconds after the redirect should appear and the url to redirect to seperated by a single ;
.
Be careful: meta-tag behaviour depends completely on the web browser inplementation of web document standards. There is no warranty that the browser executes your http-equiv meta-definition.
The last and lesser recommend method to redirect an webpage to another is to use javascript:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Redirecting</title>
<script type="text/javascript">
function domready() {
window.location.href = 'http://www.example.org/foo/bar';
}
</script>
</head>
<body onLoad="domready();">
</body>
</html>
Dependency Behaviour: Javascript is an optional mechanic at the client. There is in no case a warranty that javascript is enabled at the client. Redirecting with javascript is only recommend if your entire application bases on javascript ( your application won't work without javascript ). For webpages that only have comfort benefits, javascript-redirects are the worst way to redirect and should be avoided.
So, a good redirect function could be like that :)