Hi all! Today – a small post on the topic: PHP – working with cookies.
I’m sure you know what these same cookies are. Just in case, this is a small code that is used to:
- user authentication
- storing personal preferences and user settings
- tracking user access session state
- user statistics information
Cookies are generated on the server and stored on the user’s computer.
You can create these same cookies (cookies) in PHP as follows:
setcookie(cookie_name, value_cookie, time() + 3600);
where:
– cookie_name – cookie name
– value_cookie – cookie value
– time() – cookie lifetime in seconds, after which it will be automatically deleted
BUT! The fact that a cookie has an expiration date does not mean that it cannot be deleted. It is removed simply:
setcookie(cookie_name, value_cookie, time() - 3600);
those. the deletion code is completely similar to the code for creating cookies, with one difference – we put not a plus, but a minus in the cookie lifetime. As you can see, everything is simple!
Let’s take a look at the example code in practice. I created two pages here: https://lavrynenko.com/php_cookie/index_cookie.php – (responsible for the value of the cookie with the name “cookie_name” (yes, I’m original 🙂) and displaying this cookie itself) and https://lavrynenko. com/php_cookie/add_cookie.php – which, in fact, creates this very cookie.
The source code of the pages is below:
index_cookie.php
Let’s analyze the code in more detail: