PHP怎么用header()函数跳转到另一个页面

后端开发   发布日期:2023年09月25日   浏览次数:425

这篇文章主要介绍“PHP怎么用header()函数跳转到另一个页面”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“PHP怎么用header()函数跳转到另一个页面”文章能帮助大家解决问题。

步骤1:创建源页面

首先,我们需要创建我们要重定向的源页面。在我们的示例中,我们将创建一个名为“ source.php”的文件。

要创建一个简单的HTML页面,请按照以下步骤操作。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Source Page</title>
  6. </head>
  7. <body>
  8. <h2>Welcome to the Source Page!</h2>
  9. <p>Click the following button to go to the destination page.</p>
  10. <button onclick="redirect()">Go to Destination Page</button>
  11. <script>
  12. function redirect() {
  13. window.location = "destination.php";
  14. }
  15. </script>
  16. </body>
  17. </html>

这是一个非常简单的HTML页面,它包含一个标题和一个按钮。单击该按钮时,将调用JavaScript函数`redirect()`将用户重定向到“ destination.php”。

步骤2:创建目标页面

接下来,我们需要创建我们要将用户重定向的目标页面。在我们的示例中,我们将创建一个名为“ destination.php”的文件。

在此页面中,我们将简单地显示一条消息,以说明用户已成功重定向。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Destination Page</title>
  6. </head>
  7. <body>
  8. <h2>Welcome to the Destination Page!</h2>
  9. <p>You have been successfully redirected from the Source Page.</p>
  10. </body>
  11. </html>

这是另一个非常简单的HTML页面,它仅包含一个标题和一条消息。

步骤3:编写PHP代码

现在,我们需要将PHP代码添加到源页面中,以示在单击源页面上的按钮时将用户重定向到目标页面。 在我们的示例中,我们将使用header()函数来实现此目的。

  1. <?php
  2. header('Location: destination.php');
  3. exit;
  4. ?>

其中,‘ Location: ’表示我们要重定向到的位置。在这种情况下,我们要将用户重定向到“ destination.php”页面。

注意:您必须在header()函数之前使用exit语句。否则,重定向到目标页面之前将输出当前页面的所有内容,导致问题。

步骤4:测试代码

现在,您可以在浏览器中访问源页面,然后单击“ Go to Destination Page”按钮,以将用户重定向到目标页面。

请注意,您还可以将header()函数的第二个参数设置为true,以确保准确的重定向。

  1. <?php
  2. header('Location: destination.php', true, 301);
  3. exit;
  4. ?>

这样,您将重定向到目标页面,并附带一个301状态代码。

以上就是PHP怎么用header()函数跳转到另一个页面的详细内容,更多关于PHP怎么用header()函数跳转到另一个页面的资料请关注九品源码其它相关文章!