Cookies in PHP without reloading

Some beginner web developers looking to solve the problem when they want to use the cookie created in php immediately after it is created, face a problem: it is available for a php script only after you refresh the page. Sample code:

if(!isset($_COOKIE['cookie']))
{
setcookie('cookie','hello, i am cookie',time()+3600);
}
echo $_COOKIE['cookie'];

This code first checks whether we have created a cookie called ‘cookie’. When first entering the site we do not have it, so it will be created. Then we immediately want to take advantage of this cookie – for example, by displaying its value on the screen. Unfortunately, after first run of this script we get an error about a nonexistent cookie. Only after the second page refresh the cookie will be available for us.

How we fix this? After setcookie() function we add: $_COOKIE['cookie'] = 'hello, i am cookie';

Become a Professionalist in Web Application Development! Enroll In The Course Of Laravel You will also learn how to create hybrid applications for smartphones

if(!isset($_COOKIE['cookie']))
{
setcookie('cookie','hello, i am cookie',time()+3600);
$_COOKIE['cookie'] = 'hello, i am cookie';
}
echo $_COOKIE['cookie'];

Since then, the cookie is immediately at our disposal.

 

 

enroll in the course of Laravel framework >>>> or affiliate program
Share

Leave a Reply

Your email address will not be published. Required fields are marked *