Cookies in PHP are small text files that are stored on the client-side (web browser) by a website. Cookies can be used to store information such as user preferences, shopping cart information, and login credentials. PHP provides built-in functions to manage cookies, such as setcookie(), $_COOKIE, and unset().
To set a cookie in PHP, you can use the setcookie() function. The syntax for this function is as follows:
setcookie(name, value, expire, path, domain, secure, httponly);
name: The name of the cookie.value: The value to be stored in the cookie.expire: The expiration time of the cookie in Unix timestamp format. If omitted or set to 0, the cookie will expire when the browser is closed.path: The path on the server where the cookie will be available. If set to “/”, the cookie will be available across the entire domain.domain: The domain where the cookie is valid. If set to “.example.com”, the cookie will be valid for all subdomains of example.com.secure: If set to true, the cookie will only be transmitted over a secure HTTPS connection.httponly: If set to true, the cookie will only be accessible through HTTP requests and not through client-side scripting languages like JavaScript.
Here is an example of setting a cookie in PHP:
setcookie("username", "John Doe", time()+3600, "/");
This will set a cookie named “username” with the value “John Doe” that will expire in one hour and will be available across the entire domain.
To retrieve the value of a cookie in PHP, you can use the $_COOKIE superglobal variable. For execho $_COOKIE["username"];
This will output the value of the “username” cookie.
To delete a cookie in PHP, you can use the unset() function along with the setcookie() function with an expiration time in the past. For example:
unset($_COOKIE["username"]);
setcookie("username", "", time()-3600, "/");
This will delete the “username” cookie by setting its value to an empty string and setting its expiration time to the past.
