PHP Cookies

Cookies are small pieces of data that are stored on the client's browser and sent back to the server with subsequent requests. In PHP, you can use cookies to store user-specific information or to maintain state between different page visits. Here's how you can work with cookies in PHP:


1. Setting Cookies:

To set a cookie, you can use the `setcookie` function. The basic syntax is:

php
setcookie(name, value, expire, path, domain, secure, httponly);

- `name`: The name of the cookie.
- `value`: The value of the cookie.
- `expire`: The expiration time in Unix timestamp format (optional). If omitted, the cookie will expire at the end of the session.
- `path`: The path on the server where the cookie will be available (optional). Default is "/".
- `domain`: The domain where the cookie will be available (optional).
- `secure`: Indicates if the cookie should only be transmitted over a secure HTTPS connection (optional).
- `httponly`: Makes the cookie accessible only through the HTTP protocol, preventing JavaScript access (optional).


Example:

php
$cookie_name = "user";
$cookie_value = "John";
setcookie($cookie_name, $cookie_value, time() + 3600, "/");

2. Accessing Cookies:

You can access cookies using the `$_COOKIE` superglobal array. For example:

php
$user = $_COOKIE["user"];
echo "Welcome back, $user!";

3. Checking if a Cookie is Set:

You can use the `isset` function to check if a cookie is set before accessing it:

php
if (isset($_COOKIE["user"])) {
    echo "Welcome back, " . $_COOKIE["user"] . "!";
} else {
    echo "Welcome, guest!";
}

4. Deleting Cookies:

To delete a cookie, you can set its expiration time to a value in the past:

php
$cookie_name = "user";
setcookie($cookie_name, "", time() - 3600, "/");

This removes the cookie by expiring it immediately.


Remember that cookies are stored on the client's browser, and they have limitations in terms of size and security. Sensitive information should not be stored in cookies. For more secure storage of user data, consider using PHP sessions or other server-side techniques.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext