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

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

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


当前回答

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()。

其他回答

要在PHP中重定向,请使用:

<?php头('Location:URL');退出;?>

我喜欢数秒后的重定向

<?php

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

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
?>

您可以使用以下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");

以下是我的想法:

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

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

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

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

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