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

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

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


当前回答

我们可以通过两种方式实现:

当用户启动时https://bskud.com/PINCODE/BIHAR/index.php然后重定向到https://bskud.com/PINCODE/BIHAR.php通过以下PHP代码<?php文件header(“位置:https://bskud.com/PINCODE/BIHAR.php");出口?>将上述代码保存在https://bskud.com/PINCODE/BIHAR/index.php如果任何条件为真,则重定向到另一页:<?php文件$myVar=“bskud”;如果($myVar==“bskud”){?><script>window.location.href=“https://bskud.com“;</script><?php文件}其他{echo“<b>再次检查网站名称</b>”;}?>

其他回答

您可以尝试使用PHP头函数进行重定向。您需要设置输出缓冲区,以便浏览器不会向屏幕发出重定向警告。

ob_start();
header("Location: " . $website);
ob_end_flush();

这些答案中的许多都是正确的,但它们假设您有一个绝对的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

1.不带收割台

在这里你不会遇到任何问题

 <?php echo "<script>location.href='target-page.php';</script>"; ?>

2.使用带有exit()的头函数

<?php 
     header('Location: target-page.php');
     exit();
?>

但是如果你使用header函数,有时你会得到“警告”likeheader already send”来解析在发送头之前不回显或打印的问题,或者您可以在头函数之后简单地使用die()或exit()。

3.将头函数与ob_start()和ob_end_flush()一起使用

<?php
ob_start(); //this should be first line of your page
header('Location: target-page.php');
ob_end_flush(); //this should be last line of your page
?>

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

以下是我的想法:

IMHO,重定向传入请求的最佳方法是使用位置标头

<?php
    header("Location: /index.php");
?>

一旦执行了该语句并发出输出,浏览器将开始重新引导用户。但是,请确保在发送头之前没有任何输出(任何echo/var_dump),否则会导致错误。

虽然这是一种快速而肮脏的方式来实现最初的要求,但最终会成为一场SEO灾难,因为这种重定向总是被解释为301/302重定向,因此搜索引擎将始终将您的索引页视为重定向页,而不是登录页/主页。

因此,它会影响网站的SEO设置。