Welcome to our PHP Cookies tutorial! In this lesson, we'll dive into the world of HTTP cookies, a powerful tool in web development that helps us store small pieces of data on a client's browser. Let's get started!
Cookies are small text files saved by a web browser on your computer when you visit a website. They are used to store information about your visit, such as your preferred language, login information, and other preferences.
Cookies play a crucial role in web development, helping us to:
When a user visits a PHP-powered website, the server can send cookies to the browser. The browser saves the cookies and sends them back to the server whenever a request is made to the same domain.
Let's write our first PHP cookie!
// Set a cookie named "myCookie" with value "Hello, World!" and expiry in 1 hour
setcookie("myCookie", "Hello, World!", time() + 3600);In this example, we're creating a cookie named myCookie with the value "Hello, World!" and setting its expiry time to 1 hour after it's created.
To retrieve a cookie, we can use the $_COOKIE superglobal array.
// Check if the "myCookie" cookie exists
if (isset($_COOKIE["myCookie"])) {
echo $_COOKIE["myCookie"]; // Outputs: Hello, World!
}In this example, we're checking if the myCookie cookie exists and, if so, we're displaying its value.
Cookies can be set with various attributes such as expiry date, path, domain, and secure flag. Let's create an example using these attributes:
// Set a secure, encrypted, and persistent cookie named "mySecureCookie"
// The cookie expires in 30 days and is available only on the example.com domain
setcookie("mySecureCookie", "Secret Data", time() + (60 * 60 * 24 * 30), "/", "example.com", true, true);In this example, we're creating a secure, encrypted, and persistent cookie named mySecureCookie that expires in 30 days and is available only on the example.com domain.
Which attribute makes a cookie secure?
Stay tuned for more PHP tutorials on CodeYourCraft! Happy learning! π