是否可以通过使用PHP将用户重定向到不同的页面?

假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?

这甚至可以保护我的页面免受未授权用户的攻击。


当前回答

您可以使用以下JavaScript方法

self.location=“http://www.example.com/index.php";window.location.href=“http://www.example.com/index.php";文档位置href='http://www.example.com/index.php';window.location.replace(“http://www.example.com/index.php");

其他回答

我喜欢数秒后的重定向

<?php

header("Refresh: 3;url=https://theweek.com.br/índex.php");

这些答案中的许多都是正确的,但它们假设您有一个绝对的URL,而事实可能并非如此。如果您想使用相对URL并生成其余部分,那么可以执行以下操作。。。

$url = 'http://' . $_SERVER['HTTP_HOST'];            // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= '/your-relative/path-goes/here/';            // <-- Your relative path
header('Location: ' . $url, true, 302);              // Use either 301 or 302

Use:

<?php header('Location: another-php-file.php'); exit(); ?>

或者,如果您已经打开了PHP标记,请使用以下命令:

header('Location: another-php-file.php'); exit();

您还可以重定向到外部页面,例如:

header('Location: https://www.google.com'); exit();

确保包含exit()或includedie()。

使用header()函数发送HTTP位置标头:

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.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00

恢复-强制性die()/exit()是一些与实际PHP无关的都市传说。这与客户端“尊重”Location:标头无关。无论使用何种客户端,发送头都不会停止PHP执行。

header('位置:http://www.yoursite.com/new_page.html' );