Set cookie by clicking on a link

I need to do a php set cookie when someone clicks on a link (before they arrive where the link will send them). What is the best way to do this?

You can’t. PHP runs on the server, not in the browser. You need to use JavaScript for this.

Hi

You can use this code to set a cookie via a link:


function SetCookie(c_name,value,expiredays)
	{
		var exdate=new Date()
		exdate.setDate(exdate.getDate()+expiredays)
		document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
	}

And call it in your link like


<a href="#" onClick="SetCookie('COOKIENAME','COOKIEVALUE','1')">

This is useless if the user doesnt have JS. Do it on your server side script.

<a href="index.php?lang=0"> Spanish</a>::<a href="index.php?lang=1"> English</a>::<a href="index.php?lang=2"> Basque</a>
$lang = $_GET['lang'];

if($lang !='')
{
 //set some cookie here.
 setcookie(COOKIE_PREFIX . "language",    " ", time() - 3600);
 setcookie(COOKIE_PREFIX . "language", $lang);
 header("Location: index.php?categoryid=$categoryid");
}

Perhaps this will help you.