PHP Tutorial: Cookies 🎯

beginner
24 min

PHP Tutorial: Cookies 🎯

Welcome to our PHP Cookies tutorial! In this lesson, we'll explore the fascinating world of HTTP cookies, learn how to create, read, and manage them in PHP. Let's dive in! 🐳

What are Cookies? πŸ“

Cookies are small text files stored on a user's computer by a web browser. They are used to maintain user sessions, personalize content, and remember user preferences between visits.

Why Use Cookies? πŸ’‘

Cookies help websites remember user preferences, such as login status, language preference, or theme settings, without the need for users to re-enter data on each visit. This enhances user experience and makes websites more functional and engaging.

Creating Cookies in PHP 🎯

To create a cookie in PHP, we use the setcookie() function. Here's a simple example:

php
<?php // Set a cookie with name "user" and value "John Doe" setcookie("user", "John Doe", time() + (86400 * 30), "/"); // Expires in 30 days ?>

πŸ“ Note: The setcookie() function should be called before any output is sent to the browser, usually at the beginning of the PHP script.

Reading Cookies in PHP 🎯

To read a cookie in PHP, we access the $_COOKIE superglobal array. Here's how you can retrieve the "user" cookie we created earlier:

php
<?php // Read the "user" cookie $user = $_COOKIE["user"]; echo "Hello, " . $user; ?>

Deleting Cookies in PHP 🎯

To delete a cookie in PHP, we set its expiration to the past:

php
<?php // Delete the "user" cookie setcookie("user", "", time() - 3600); // Expires 1 hour ago ?>

Advanced Cookies: Secure and HTTP-only Cookies 🎯

For improved security, you can set cookies as secure (transmitted only over HTTPS) and HTTP-only (inaccessible to JavaScript). Here's how:

php
<?php // Set a secure and HTTP-only cookie setcookie("admin", "admin_password", time() + (86400 * 30), "/", "", true, true); // Expires in 30 days ?>

πŸ’‘ Pro Tip: Always use secure and HTTP-only cookies for sensitive data like login credentials.

Quiz 🎯

Quick Quiz
Question 1 of 1

What does the `setcookie()` function do?

That's it for our PHP Cookies tutorial! We hope you found it helpful and informative. Keep practicing, and happy coding! πŸ€–πŸ’»πŸŽ‰