如何在 PHP 中进行重定向?

是否有可能通过使用 PHP 将用户重定向到不同的页面?
假设用户访问了 google www.example.com/page.php ,我想把他们重定向到 google www.example.com/index.php ,如果不使用元信息刷新,该怎么做呢? 这可能吗?

function Redirect($url, $permanent = false){
    if (headers_sent() === false)
    {
        header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
    }
    exit();}
Redirect('http://www.google.com/', false);

别把die()/exit()落下!

使用 header ()函数发送 HTTP Location header
:
header('Location: '.$newURL);
与一些人的想法相反,die ()与重定向没有任何关系。 只有当您想要重定向而不是正常执行时才使用它。
文件 example.php:

<?php
    header('Location: static.html');
    $fh = fopen('/tmp/track.txt', 'a');
    fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
    fclose($fh);?>

三次执行的结果:

bart@hal9k:~> cat /tmp/track.txt127.0.0.1 2009-04-21T09:50:02+02:00127.0.0.1 2009-04-21T09:50:05+02:00127.0.0.1 2009-04-21T09:50:08+02:00

1初步回答
您可以使用 header ()函数发送一个新的 HTTP header,但必须在任何 HTML 或文本之前发送到浏览器(例如在<!DOCTYPE ...> 之前)。
header('Location: '.$newURL);
2重要的细节
die() 或者exit()
header("Location: http://example.com/myOtherPage.php");die();
绝对或相对URL
自2014年6月以来,绝对和相对 url 都可以使用。 参见 RFC 7231,它取代了旧的 RFC 2616,旧的只允许绝对 url。
状态代码
Php 的“ Location”-header 仍然使用 HTTP 302-redirect 代码,但这不是您应该使用的代码。你应考虑301(永久重定向)或303(其他)。
注意: W3C 提到303表头与“许多pre-HTTP/1.1 用户代理不兼容。 目前使用的浏览器都是 http / 1.1用户代理。 对于机器人等许多其他用户代理来说,情况并非如此。
3. 替代品
您可以使用 http 重定向($url)的替代方法; 这需要安装PECL package pecl

4. 辅助函数
这个函数没有包含303状态码:

function Redirect($url, $permanent = false){
    header('Location: ' . $url, true, $permanent ? 301 : 302);

    exit();}
Redirect('http://example.com/', false);

这种方式更加灵活:

function redirect($url, $statusCode = 303){
   header('Location: ' . $url, true, $statusCode);
   die();}

用header函数跳转:
header("location:test.php")