Set and Get Cookies in PHP

In this article, you will learn how to use or set and get cookies in a web page.

Cookies are pieces of content that stores in a user's web browser. Cookies can enable you to make shopping cart, client groups, and customized destinations. It's not prescribed that you store sensitive data in a cookie, but you can store a unique identification string that will coordinate a user with information held safely in a database.

To set a cookie, the setcookie function is called before sending any other content to the browser, because a cookie is actually part of the header information and $_COOKIE superglobal variable is used to get the previously set cookie values.

Here, we are taking a login system and implementing cookies to allow persistent logins between single browser sessions.
For this, we are going to create two web pages - set_cookie.php and get_cookie.php.





In set_cookie.php, we have set cookies for the username and password using the setcookie() function.


set_cookie.php
<html>
	<head>
		<title>Set Cookies in PHP</title>
	</head>
	<body>
	<?php
	$username = "test user";
	setcookie('username', $username, time() + 60 * 60 * 24 * 30); // Cookie sets for 30 days
	$password = "test password";
	setcookie('password', $password, time() + 60 * 60 * 24 * 30); // Cookie sets for 30 days
	?>
	<a href="/get_cookie.php">Click here</a> to get cookie values.
	</body>
</html>	

In get cookie.php, we have first check the valid cookie values. If they are not, it says "No cookies were set", else it prints success message.

get_cookie.php
<html>
	<head>
	<title>Get Cookies in PHP</title>
	</head>
	<body>
	<h1>Get Cookies</h1>
	<?php
	if ($_COOKIE['username'] == "" || $_COOKIE['password'] == "")
	{
	?>
	No cookies were set.<br>
	<?php
	}
	else
	{
	?>
	Your cookies were set:<br>
	Username cookie value: <b><?php echo $_COOKIE['username']; ?></b><br>
	Password cookie value: <b><?php echo $_COOKIE['password']; ?></b><br>
	<?php
	}
	?>
	</body>
</html>




Related Articles

Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL


Read more articles


General Knowledge



Learn Popular Language