To get and set cookie in PHP:
Code example
<?php
setcookie(name, value, expire, path, domain, secure, httponly);
setcookie("CookieName", "CookieValue", 2147483647, "/"); //SET COOKIE THAT EXPIRES IN 2038
print($_COOKIE["CookieName"]); //USER FOR GETTING COOKIE
?>
To set a cookie in PHP, you can use the setcookie() function. The syntax for this function is:
setcookie(name, value, expire, path, domain, secure, httponly);
Here's what each parameter does:
Here's an example that sets a cookie named "username" with a value of "John Doe" that will expire in 1 hour:
<?php
setcookie("username", "John Doe", time()+3600, "/", "", 0, 1);
?>
Note that the setcookie() function should be called before any output is sent to the browser, or it won't work.
To retrieve a cookie in PHP, you can use the $_COOKIE superglobal array. This array contains all the cookies that have been sent to the server from the client's browser. The syntax for accessing a cookie in this array is:
$_COOKIE['cookie_name'];
Here's an example that retrieves the value of a cookie named "username" and assigns it to a variable:
$username = $_COOKIE['username'];
Note that you should always check whether a cookie exists before trying to access it, to avoid errors. You can do this using the isset() function, like this:
if(isset($_COOKIE['username'])) {
$username = $_COOKIE['username'];
} else {
// the cookie does not exist
}
Once you have retrieved a cookie, you can use its value in your PHP code to perform various tasks, such as customizing the content of a web page or validating user credentials. However, you should be careful not to rely too heavily on cookies for sensitive data, as they can be manipulated by users and are not completely secure.
0 Comments