Cookie – PHP

Cookie is used to enhance browsing experience by storing less sensitive data on user’s browser. It is used for many purposes. You can use cookies to know the person who requested some resource from your server, so you can identify him later. Or you can use cookies to reduce the number of requests on server.

For example you can store most of the data in your user’s browser so that when the user try to access it, it will not be fetched from your server but it will be fetched from user’s browser cookies. Cookies also play an important role in serving the cache mechanism which means the static data which is served to user once will not be fetched again from the server again. This mostly used for static data which does not change frequently, for example images, css and js files etc.

We are going to create a script that will allow you to add, view, edit and delete your browser’s cookies. We will be getting 3 inputs from user, cookie name, value and expiry time.

Save cookie – PHP

For layout and design, we will be using bootstrap as the most popular web design tool at the time of writing this. You can download bootstrap from it’s official site or you can get it from the source files which are attached at the end of this tutorial. Create a new file named index.php and paste the following code in it:

<!-- Include bootstrap -->
<link rel="stylesheet" href="bootstrap.min.css">

<!-- Create container -->
<div class="container" style="margin-top: 100px;">

	<div class="row">
		<div class="col-md-3">
			<!-- Create form -->
			<form method="POST" action="create-cookie.php">
				<!-- Create fields -->
				<div class="form-group">
					<label>Cookie name</label>
					<input name="cookie_name" class="form-control">
				</div>

				<div class="form-group">
					<label>Cookie value</label>
					<input name="cookie_value" class="form-control">
				</div>

				<!-- Create field to select cookie expiry time -->
				<div class="form-group">
					<label>Expire</label>
					<select name="sec" class="form-control">
						<option value="0">Sec</option>
						<?php for ($a = 1; $a <= 60; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="min" class="form-control">
						<option value="0">Min</option>
						<?php for ($a = 1; $a <= 60; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="hrs" class="form-control">
						<option value="0">Hrs</option>
						<?php for ($a = 1; $a <= 24; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="days" class="form-control">
						<option value="0">Days</option>
						<?php for ($a = 1; $a <= 90; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<input type="submit" class="btn btn-primary" value="Add Cookie">
			</form>
		</div>
	</div>
</div>

This will create a form with a input fields for selecting cookie name and cookie value. The form will also have 4 dropdown menus for selecting seconds, minutes, hours and days for expiring the cookie. You can select the time that after how many seconds or minutes or hours will this cookie be expired. If you do not select this time then depends on browser it will expire after a long time, typically after 90 days.

But you can change the expiry time of each cookie as per your requirements. We are setting the default value of expiry seconds, minutes, hours and days to zero so that if the user does not select any of the field then the default value will be zero. Now we need to process the form to create a cookie in your browser. So create a new file named create-cookie.php and paste the following code in it:

Processing the form

<?php

$cookie_name = $_POST["cookie_name"];
$cookie_value = $_POST["cookie_value"];

// Get expiry time
$sec = $_POST["sec"];
$min = $_POST["min"] * 60; // Convert minutes to seconds
$hrs = $_POST["hrs"] * 60 * 60; // Convert hours to seconds
$days = $_POST["days"] * 60 * 60 * 24; // Convert days into seconds

// Add all seconds
$expiry_time = $sec + $min + $hrs + $days;

// Add in current timestamp
$expire = time() + $expiry_time;

// Create an object
$data = array(
	"value" => $cookie_value,
	"expire" => $expire
);

// Save data in cookie in JSON format
setcookie($cookie_name, json_encode($data), $expire);

// Redirect back to home page
header("Location: index.php");

Get cookie – PHP

To read the cookies we need to first check if the browser has any cookies. Then we will loop through all cookies and it will return cookie’s key and value in each iteration. We will be displaying cookies in bootstrap table so go ahead and paste the following code below col-md-3 div in index.php file:

<div class="col-md-9">
	<!-- Check browser has any cookie -->
	<?php

		if (isset($_COOKIE)) {
	?>
	<!-- Create table -->

	<table class="table table-responsive">
		<!-- Heading of table -->
		<tr>
			<th>Name</th>
			<th>Value</th>
			<th>Expire</th>
			<th>Actions</th>
		</tr>

		<!-- Loop through all cookies -->
		<?php foreach ($_COOKIE as $key => $value) { ?>
			<?php
				// Decode cookie from json back to object
				$cookie = json_decode($_COOKIE[$key]);
			?>

			<tr>
				<td><?php echo $key; ?></td>

				<!-- Set td width -->
				<td style="max-width: 300px; overflow-x: scroll;">
					<!-- Show cookie value -->
					<?php
						echo isset($cookie->value) ? $cookie->value : $value;
					?>
				</td>

				<!-- Show expiry -->
				<td>
					<?php
						// Show expiry date in readable format
						echo isset($cookie->expire) ? date("Y-m-d H:i:s", $cookie->expire) : "";
					?>
				</td>

				<!-- Creating edit and delete button -->

				<td>
					<a class="btn btn-warning" href="edit-cookie.php?name=<?php echo $key; ?>">Edit</a>

					<a class="btn btn-danger" href="delete-cookie.php?name=<?php echo $key; ?>">Delete</a>
				</td>
			</tr>

		<?php } ?>
	</table>

	<?php } ?>
</div>

This will display the expiry date in readable format date() function is used to display the 2nd parameter timestamp in the format specified in 1st parameter. There are many formats available to display the date, the one used in this function are explained below:

YDisplay the year in 2009 this format.
mDisplay the month number, for example January as 1 and December as 12.
dDisplay the day number in month.
HThis will show the hour in 24 hour format, for example 1 PM will be displayed as 13:00.
iThe minute in the hour.
sThe second of minute.

Update cookies – PHP

Updating the cookies will require a simple form to be created with auto-populated values of selected cookie. We will be using same create-cookie.php page to update the cookies. Because the key of cookie will remains same. Create a new page named edit-cookie.php and paste the following code in it:

<!-- Include bootstrap -->
<link rel="stylesheet" href="bootstrap.min.css">

<?php

// Get cookie data
$key = $_GET["name"];
$cookie = json_decode($_COOKIE[$key]);

// Show value and name in form

?>

<!-- Create container -->
<div class="container" style="margin-top: 100px;">
	<div class="row">
		<div class="col-md-6 offset-md-3">
			<!-- Create form -->

			<!-- Form will submit on same page -->

			<form method="POST" action="create-cookie.php">
				<!-- Create fields -->
				<div class="form-group">
					<label>Cookie name</label>
					<input name="cookie_name" class="form-control" value="<?php echo $key; ?>">
				</div>

				<div class="form-group">
					<label>Cookie value</label>
					<input name="cookie_value" class="form-control" value="<?php echo $cookie->value; ?>">
				</div>

				<!-- Create field to select cookie expiry time -->
				<div class="form-group">
					<label>Expire</label>
					<select name="sec" class="form-control">
						<option value="0">Sec</option>
						<?php for ($a = 1; $a <= 60; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="min" class="form-control">
						<option value="0">Min</option>
						<?php for ($a = 1; $a <= 60; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="hrs" class="form-control">
						<option value="0">Hrs</option>
						<?php for ($a = 1; $a <= 24; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="days" class="form-control">
						<option value="0">Days</option>
						<?php for ($a = 1; $a <= 90; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<input type="submit" class="btn btn-warning" value="Edit Cookie">
			</form>
		</div>
	</div>
</div>

The code is mostly same as index.php page, only change is first we are getting the selected cookie from URL and populating it’s data in “cookie_value” field. The form will be redirected to create-cookie.php and it will execute the same code to update the cookie name, value and expiry date.

Remove cookie – PHP

Deleting the cookies is the most simplest part in this script. We need to get the cookie’s key from URL and will set the value to empty string. To delete the cookie, we need to set the expiry time in the past.

<?php

// Getting cookie name
$name = $_GET["name"];

// Setting cookie expire time in past will remove that cookie
setcookie($name, "", time() - 3600);

// Redirect back
header("Location: index.php");

We are setting the expiry time before 1 hour which will be enough. It will redirect you back to main page and now you will see that selected cookie will be removed. Removing it may logged you out from some sites which uses cookies. Cookies can also be accessed from Javascript so you must not save sensitive data like passwords in cookies. In javascript, cookies can be accessed by document.cookie you can write that in your browser’s console window and it will display all the cookies that has been stored in your browser.

That’s all for now. I have also attached all the source files below, make sure you download them and let us know if you face any issue.

Learn how to create a shopping cart using cookies in PHP.

[wpdm_package id=’164′]