首次访问者Cookie



对于我的网站,我想在页面中间为第一次访问的访问者创建一个链接,使用PHP表示"第一次点击这里"。

理论上你可以用cookie来做,但是除了要求他们注册一个帐户并在他们第一次登录时向他们显示消息外,没有保证的方法来检测"首次访问者"。

原因是cookie可能会从浏览器中被清除,人们可能会更换计算机/浏览器,cookie最终会过期,这取决于你的目标是什么,你可能最终会惹恼现有用户,以为他们是新用户。

不管怎样,够了。您的代码可能看起来像这样:

<?php
    // Top of the page, before sending out ANY output to the page.
        $user_is_first_timer = !isset( $_COOKIE["FirstTimer"] );
    // Set the cookie so that the message doesn't show again
        setcookie( "FirstTimer", 1, strtotime( '+1 year' ) );
?>


<H1>hi!</h1><br>

<!-- Put this anywhere on your page. -->
<?php if( $user_is_first_timer ): ?>
    Hello there! you're a first time user!.
<?php endif; ?>

干杯!

创建一个在"click"时生成cookie的函数,并提示所有没有cookie的人

在PHP中设置cookie非常简单。

if(isset($_GET['firsttimer'])){
    // ok, lets set the cookie
    setcookie('firsttimer','something',strtotime('+1 year'),'/');
    $_COOKIE['firsttimer']='something'; // cookie is delayed, so we do this fix
}
if(!isset($_COOKIE['firsttimer']){
    // if cookie ain't set, show link
    echo '<a href="?firsttimer">First time, click here</a>';
}else{
    // not firsttimer
    echo 'Welcome back!';
}
<?php
// this might go best in the new visitor file
setcookie('visited','yes', 0x7FFFFFFF); // expires at the 2038 problem point
// ... snip ...
if (isset($_COOKIE['visited'])):
?>
<a href="foo.php">New Visitor?  Click here!</a>
<?php
endif;
// ... snip ...

最新更新