Reputation: 53
For my site, I want to create a link in the middle of the page for first time visitors that says something like "First time, click here" using PHP.
Upvotes: 5
Views: 9451
Reputation: 4716
You could in theory do it with cookies, but there's no guaranteed way to detect "first time visitors" other than asking them to register for an account and show them the message the first time they log in.
The reason is that cookies may get cleaned from the browser, people may change computers / browsers, cookies will eventually expire and depending on what your goal is you may end up annoying existing users assuming they're new.
Anyway, enough of that. Your code could look something like this:
<?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; ?>
Cheers!
Upvotes: 7
Reputation: 10087
<?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 ...
Upvotes: 0
Reputation: 28124
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!';
}
Upvotes: 0
Reputation: 38503
Have a function that creates the cookie on the "click", and prompt everyone that does not have a cookie.
Setting a cookie is pretty trivial in PHP.
Upvotes: 0