如果是第一次访问则显示不同的页面

时间:2012-01-06 01:38:39

标签: php cookies

我发现了一段代码重定向,如果它是第一次访问,但是当我尝试使用它时,它只停留在该代码上。我对饼干及其工作原理并不太了解,所以也许你可以提供帮助!这是PHP代码:

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

    }

?>

那么我怎么能修复它呢?如果你第一次访问该网站就会把它带到某个页面,如果不是,那就是默认页面?

6 个答案:

答案 0 :(得分:19)

您可以使用此代码:

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

它将检查你是否有一个名为“firsttime”的cookie,如果没有,它将创建它并重定向到你的FIRSTTIME页面...如果是,它只会将你重定向到网站......

答案 1 :(得分:3)

<?php

    session_start();

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

    //show site for the first time part
    $_SESSION['FirstVisit'] = 1;
    header("Location: http://example.com/index.php");

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

    } else { Show normal site }

?>

你只需要制作一个if语句来检查是否有会话集,如果没有,你知道它是第一次。虽然,因为它不是cookie,所以当你退出浏览器时,它会认为这是第一次,即使它从来不是第一次。

答案 2 :(得分:1)

如果难以进行会话/ cookie,您可以保存访问者的IP。当IP新存在时,当IP存在时显示第1页重定向到其他页面?

答案 3 :(得分:1)

有关详细信息,请参阅the docs

<?php

    if (!isset($_COOKIE['visited'])) { // no cookie, so probably the first time here
        setcookie ('visited', 'yes', time() + 3600); // set visited cookie

        header("Location: http://example.com/index.php");
        exit(); // always use exit after redirect to prevent further loading of the page
    }

?>

答案 4 :(得分:0)

  <?php

    @session_start();
    $url = 'http://blah.com/default/';

    if (!isset($_COOKIE['Visited'])) {
        $_COOKIE['Visited'] = 1;
        $url = 'http://blah.com/firstvisit/';
    }

    header("Location: {$url}");

  ?>

答案 5 :(得分:0)

  <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-
ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="/resources/demos/external/jquery.bgiframe-2.1.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script> 

<?php
if (!isset($_COOKIE['firsttime']))
{
setcookie("firsttime", "no", /* EXPIRE */);
header('Location: first-time.php');
exit();
}
else
{
?>
<div id="dialog" title="Basic dialog">
<p>text</p>
</div>
<?
}

?>

@ Frederick或PeeHaa上述脚本也可以在进入网站而不是页面之前调出窗口。