2011-04-19 34 views
3

对于我的网站,我想在第一次访问时在页面中间创建一个链接,用第一次点击“使用PHP首次点击此处”。首次访客Cookie

+1

如果用户没有“不是第一次”cookie,请显示该消息,然后设置cookie。 – 2011-04-19 21:46:01

回答

5

理论上你可以做到这一点与饼干,但没有万无一失的方法来检测“第一次参观”除了要求他们注册一个帐户,并告诉他们的消息他们登录第一次

原因是,cookies可能会从浏览器中清除,人们可能会更换计算机/浏览器,cookies最终会过期,并且取决于您的目标是什么,最终可能会让现有用户感到烦恼,假设他们是新手。

无论如何,够了。你的代码可能看起来像这样:

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

干杯!

+0

出于某种原因,它总是说我是第一次访问者,即使我已经多次刷新页面。 – Ryan 2011-04-20 19:12:08

+0

嗨@Ryan,在setcookie()的参数顺序中有一个错字。我修复了这个帖子并测试了代码...给它一个试试:) – SuitedSloth 2011-04-21 00:15:16

+0

完美,正是我所需要的。非常感谢! :-) – Ryan 2011-04-21 22:13:20

0
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!'; 
} 
+0

当我尝试这种方式时,即使在刷新我的浏览器之后,它始终显示我为第一次使用用户。 – Ryan 2011-04-20 21:00:23

0
<?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 ... 
+0

这怎么改变,所以我可以在页面中间的某个地方有链接? – Ryan 2011-04-20 20:59:49

+0

只是将两个分段分成不同的文件;把'setcookie'语句放在你希望他们访问的页面的顶部,并把'if(isset())'部分放在你想要链接的地方。 – Dereleased 2011-04-20 21:32:12