PHP - SPLessons

PHP Cookies

Chapter 20

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Cookies

PHP Cookies

Cookies

shape Description

Cookies are the ids which saves the user data into browser and identifies the user next time when the same webpage is opened. Cookies data will save on client-side, in the browser itself. It’s not secure compared with Sessions.

Cookie can be created and deleted after particular time automatically or deletion can also be done manually.

Creating Cookies

shape Syntax

Cookies can be created using setcookie() function.

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

In the above syntax only one parameter name is required and the remaining are optional.

shape Example

<!DOCTYPE html>
	<?php
	$cookie_name = "Student";
	$cookie_value = "Mike";
	setcookie($cookie_name, $cookie_value, time() + (5 * 30), "/"); 
	
	?>
	
	<html>
		<body>

			<?php
				if(!isset($_COOKIE[$cookie_name])) {
					 echo "Cookie named '" . $cookie_name . "' is not set!";
				} else {
					 echo "Cookie '" . $cookie_name . "' is set!<br>";
					 echo "Value is: " . $_COOKIE[$cookie_name];
				}
			?>

		<p><strong>Note:</strong> Please reload the page to see the cookie value.</p>

		</body>
	</html>

Output:

shape Example

setcookie() is the function to delete the cookie. Set the cookie expire time to post.

<!DOCTYPE html>
<?php 
// set the expiration date to one hour ago 
setcookie("Student", "", time() - 3600); 
?>
    <html>
        <body>
        <?php echo "Cookie 'Student' is deleted."; ?>
        </body>
    </html>

Output:

shape Example

Initially, test cookie need to be created with the function setcookie().Later count the array variable $_COOKIE.

<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
	<body>

		<?php
			if(count($_COOKIE) > 0) {
				echo "Cookies are enabled.";
			} else {
				echo "Cookies are disabled.";
			}
		?>

	</body>
</html>

Output:

Summary

shape Points

  • PHP Cookies can be created and deleted after particular time automatically.
  • Cookies can be created using setcookie() function.