i need to run a java script only once when accessing the site for the first time..i want to save a cookie and check it every time site opening if cookie is saved dont need to run the script if cookie is not saved ( it mean first times that using the site ) need to create a new cookie and run the script.. Or we can do it from IP if that ip is on mysql database no to run if not add da ip and run the script.im new to php开发者_StackOverflow..still studying. need a help.
In its simplest form:
if (document.cookie != 'onetime=true') {
... do your one-time stuff here ...
document.cookie = 'onetime=true; expires:Fri, 8 Jul 2011 00:00:00 UTC; path=/';
} else {
... cookie is set, so don't do anyhing ...
}
This only allows a single cookie key=value pair, however. If your site requires other cookies beyond this one (e.g. a session token), you'll need a bit of infrastructure to set/get/read multiple cookies. Code samples for that are demoed here.
In PHP:
<?
if (!isset($HTTP_COOKIE_VARS["visited"]))
{
echo "<script ... your Javascript code goes here ... </script>";
setcookie ("visited","Yes",time()+3600 * 24 * 120,'/', ".yoursite.com"); // for 120 days
}
?>
It's impossible to really know whether someone hasn't already visited your site before. If they delete their cookies, how will you tell? And no you can't do it based on IP, what about universities, companies, libraries, schools and free wi-fi networks in coffee shops, hotels and airports that might have many hundreds or thousands of people behind them?
And of course, many home users are on dynamic IPs so they change all the time.
The best you can do is check for the existence of the cookie, if it doesn't exist run your script, if it does, then don't.
精彩评论