PHP Tutorials

PHP Cookies Tutorial: Store and Track User Data

PHP cookies let you remember user preferences between visits. Learn how to set, read, and secure cookies with setcookie() in this friendly tutorial.

Serhat ALPASLAN3 min read

PHP

PHP cookies are small text files used on websites to store user information or track user behavior. Cookies are sent by the browser to the server and stored by the server. Creating, reading, and deleting cookies with PHP is quite easy.

As an example, you can create a cookie that you can use to store a user’s name or email address. First, you need to read the information the user enters from the $_POST array and create the cookie with the setcookie() function.

<?php
if (isset($_POST['submit'])) {
  $name = $_POST['name'];
  $email = $_POST['email'];
  setcookie('name', $name, time() + (86400 * 30), "/");
  setcookie('email', $email, time() + (86400 * 30), "/");
}
?>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

In this example, a cookie was created to store the name and email address entered by the user for 30 days. Later, to read the user’s information, you can read from the $_COOKIE array. For example;

 

<?php
if(isset($_COOKIE['name'])) {
  echo "Welcome " . $_COOKIE['name'];
} else {
  echo "Welcome Guest!";
}
?>

In this example, we read the user’s name from the cookie and print it to the screen. If the cookie has not been set, we print “Welcome Guest” to the user.

Finally, to delete a cookie, you pass an empty value or zero as the first parameter of the setcookie() function. For example;

 

setcookie("name", "", time() - 3600);

In this example, the expiration time of the cookie named “name” was moved back by 1 hour, and the cookie was deleted this way.

Cookies are an important tool for optimizing the user experience on websites. For example, they can be used to remember the items in a user’s shopping cart, track the pages a user visits on the site, or remember the searches a user makes on the site. It is also possible to store a user’s session or login information with cookies.

However, along with using cookies, you also need to consider security and privacy issues. For example, storing user information with cookies is not secure because cookies are stored by the browser and can be easily modified. In addition, cookies can track information in the user’s browser and interfere with the user’s privacy. Therefore, it is important to be careful when using cookies and to take encryption or other security measures when necessary.

In conclusion, PHP cookies are an important tool you can use on websites to store user information or track user behavior. However, along with using cookies, you also need to consider security and privacy issues.

Share it if it helped

Write a comment