(PHP 4 >= 4.0.7, PHP 5)
Effectue une redirection HTTP et termine le script courant.
header_redirect() effectue une redirection HTTP vers l'URL fournie.
Pour rester conforme à la RFC, "The document has moved <a href="URL">here</a>." sera affiché si le client ne redirige pas immédiatement.
Cette fonction utilise header(). Par conséquent, header_redirect() doit être appelée avant que le moindre contenu ne soit envoyé, soit par des lignes HTML habituelles dans le fichier, soit par des affichages PHP.
<?php
function header_redirect( $url, $permanent = false )
{
$url_infos = parse_url($url);
if( !array_key_exists('scheme', $url_infos) )
{
$url = (empty($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS'])=='off') ? 'http' : 'https';
$url .= '://';
$url .= $_SERVER['HTTP_HOST'];
if( $_SERVER['SERVER_PORT'] != '80' )
$url .= ':'. $_SERVER['SERVER_PORT'];
if( preg_match('`^\/`', $url_infos['path']) )
$url .= $url_infos['path'];
else
{
$url .= '/';
$c_dirs = pathinfo($_SERVER['REQUEST_URI'].'x', PATHINFO_DIRNAME);
$c_dirs = explode('/', trim($c_dirs,'/'));
$t_dirs = explode('/', $url_infos['path']);
foreach($t_dirs as $d)
{
switch($d)
{
case '':
case '.': break;
case '..': array_pop($c_dirs); break;
default: array_push($c_dirs, $d);
}
}
if( array_pop($t_dirs)==='' )
array_push($c_dirs,'');
$url .= implode('/', $c_dirs);
}
if( isset($url_infos['query']) )
$url .= '?'. $url_infos['query'];
if( isset($url_infos['fragment']) )
$url .= '#'. $url_infos['fragment'];
}
if( $permanent )
header("Status: 301 Moved Permanently", true, 301);
else
header("Status: 302 Found", true, 302);
header("Location: {$url}");
echo "The document has moved <a href=\"{$url}\">here</a>.";
exit;
}
?>
void header_redirect ( string $url [, bool $permanent = false ] )
Aucune valeur n'est retournée.
Exemple #1 Exemple avec header_redirect()
<?php
// Effectue une redirection temporaire vers la racine du site
header_redirect('/');
?>
Exemple #2 Exemple avec header_redirect()
<?php
// Effectue une redirection permanente vers www.example.com
header_redirect('http://www.example.com/', true);
?>
Commentaire(s)
Poster un commentaire