PHP Beginner's Guide to Cookies

1. What is a cookie? What role does it play?

A cookie is a small file that the server leaves on the user's computer. Each time the same computer requests a page through the browser, the cookie will be sent to the computer. Through PHP, you can create and retrieve the value of cookie

Function: Usually used to identify users

2. How to create cookies

setcookie() function is used to set cookies

Note: The setcookie() function must be located before the <html> tag

Syntax: setcookie(name, value, expire, path, domain);

<?php
	setcookie("user", "admin", time()+3600);
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>cookie</title>
</head>
<body>
	
</body>
</html>

Note: As shown in the above case, create a named user with a value of admin. It also stipulates that the value will disappear after one hour.

Let the cookie expire in another way, as shown in the following code

<?php
	$time = time() + 60*60*3600;
	setcookie("user", "admin",$time);
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>cookie</title>
</head>
<body>

</body>
</html>

How to get the value of the cookie

<?php
	setcookie("user", "admin", time()+3600);
?>

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>cookie</title>
</head>
<body>
	<?php
		echo $_COOKIE['user'];
	?>
</body>
</html>

Note: When we write a user at the beginning with the value admin and run this code, the browser does not refresh and the value is not stored in the cookie.

After running, refresh the page to output the user value in the cookie

4. How to delete the cookie

When deleting the cookie, you should set the expiration date Change to the past time

<?php

//Set cookie expiration time to the past 1 hour

setcookie("user", "", time() -3600);

?>

General cookies are normally used when submitting forms to store the data in the form into cookies

Continuing Learning
||
<?php setcookie("user", "admin", time()+3600); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>cookie</title> </head> <body> </body> </html>
submitReset Code