Cookies

Small text file held on local machine.

 

Stores user information.

 

setcookie(name, value, expire, path, domain, secure) ;

//last 3 parameters offer more control, but aren't used that often.

 

<?php
	$expiry = time()+(60*60*24*30) ;

	setcookie("whoIsThis", "Julia", $expiry );

	echo $_COOKIE["whoIsThis"] ;

	echo "<br><br>" ;

	echo "<pre>" ; //just for nice formatting (of data below) on the screen
	print_r($_COOKIE) ;
	echo "<pre>" ;
?>

*note: setcookie(); must be before the opening <html> tag, due to HTTP headers (e.g. cookies) being sent before body (HTML code).

 

Displays a welcome message depending upon the status of the cookie.

 

<?php
	if( isset($_COOKIE["whoIsThis"])) {

		echo "Hi " . $_COOKIE["whoIsThis"] . ", Good to see you again!<br />";

	} else {

		echo "Hi Guest. Welcome to our site!<br />";
	}
?>

 

To delete a cookie, simply set its expiry date in the past.

<?php
	setcookie("whoIsThis", "" ,time()-3600 ) ;

	echo $_COOKIE["whoIsThis"] ;
?>

Leave a Reply