2011-04-19 31 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