第一次访问时显示不同的页面

2021-12-21 00:00:00 cookies php

我发现了一段代码,如果它是第一次访问,它会重定向,但是当我尝试使用它时,它只是停留在那个代码上.我对cookies及其工作原理不太了解,所以也许你可以帮忙!这是 PHP 代码:

I found a snippet of code that redirects if it's the first visit, but when I tried to use it, it just stayed at that code. I don't really understand too much about the cookies and how it works, so maybe you can help! Here's the PHP code:

    <?php

    session_start();

    if (isset($_SESSION['FirstVisit'])) {

    $_SESSION['FirstVisit'] = 1;

    header("Location: http://example.com/index.php");

    // Don't forget to add http colon slash slash www dot before!

    }

?>

那么我该如何修复它,如果这是您第一次访问该网站,它会将您带到某个页面,如果不是,则是默认页面?

So how could I fix it so if it's your first visit to the site it brings you to a certain page, and if not, the default?

推荐答案

您可以使用以下代码:

<?php
if (!isset($_COOKIE['firsttime']))
{
    setcookie("firsttime", "no", /* EXPIRE */);
    header('Location: first-time.php');
    exit();
}
else
{
    header('Location: site.php');
    exit();
}
?>

它会检查您是否有名为firsttime"的 cookie如果没有,它会创建它并重定向到您的 FIRSTTIME 页面...如果是,它只会将您重定向到该网站...

It will check if you have a cookie named "firsttime" and if not, it will create it and redirect to your FIRSTTIME page... If yes, it will just redirect you to the website...

编辑 2021请不要使用这种旧方法,而是使用框架或更好的代码.现在 10 岁了.

EDIT 2021 Please don't use this old method and either use a framework or better code. This is 10 years old now.

相关文章