Cookies are often used to identify users.
Cookies are often used to identify users. A cookie is a small file that a server leaves on a user's computer. Each time the same computer requests a page through the browser, this computer will send the cookie. With PHP, you can create and retrieve cookie values.
The setcookie() function is used to set cookies.
Note: The setcookie() function must be placed before the <html> tag.
setcookie(name, value, expire, path, domain);
In the following example, we will create a cookie named "user" and assign it the value "codercto". We also specify that this cookie expires after one hour:
<?phpsetcookie("user", "codercto", time()+3600);?><html>.....Note: When sending a cookie, the cookie value is automatically URL-encoded and automatically decoded when retrieved. (To prevent URL encoding, use setrawcookie() instead.)
There is another way you can set the cookie expiration time. This may be simpler than using seconds.
<?php$expire=time()+60*60*24*30;setcookie("user", "codercto", $expire);?><html>.....In the above example, the expiration time is set to one month ( 60 seconds * 60 minutes * 24 hours * 30 days ).
PHP's $_COOKIE variable is used to retrieve the value of the cookie.
In the following example, we retrieve the value of the cookie named "user" and display it on the page:
<?php// Output cookie value echo $_COOKIE["user"];// View all cookies print_r($_COOKIE);?>
In the following example, we use the isset() function to confirm whether the cookie has been set:
<html><head><meta charset="utf-8"><title>Coder Tutorial (codercto.com)</title></head><body><?phpif (isset($_COOKIE["user" ])) echo "Welcome" . $_COOKIE["user"] . "!<br>";else echo "Normal visitor!<br>";?></body></html>
When deleting a cookie, you should change the expiration date to a point in time in the past.
Deleted instance:
<?php//Set the cookie expiration time to the past 1 hour setcookie("user", "", time()-3600);?>If your application needs to deal with browsers that do not support cookies, then you will have to use other methods to pass information between pages in your application. One way is to pass data through a form (forms and user input are covered in the previous chapters of this tutorial).
The following form submits user input to "welcome.php" when the user clicks the "Submit" button:
<html><head><meta charset="utf-8"><title>Coder Tutorial (codercto.com)</title></head><body><form action="welcome.php" method=" post">Name: <input type="text" name="name">Age: <input type="text" name="age"><input type="submit"></form></body>< /html>
Retrieve the value from the "welcome.php" file as follows:
<html><head><meta charset="utf-8"><title>Coder Tutorial (codercto.com)</title></head><body>Welcome<?php echo $_POST["name"] ; ?>.<br>You are <?php echo $_POST["age"]; ?> years old. </body></html>