Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a PHP cookie exists and if not set its value

I am working on a multilingual site so I tried this approach:

echo $_COOKIE["lg"]; if (!isset($_COOKIE["lg"]))     setcookie("lg", "ro"); echo $_COOKIE["lg"]; 

The idea is that if the client doesn't have an lg cookie (it is, therefore, the first time they've visited this site) then set a cookie lg = ro for that user.

Everything works fine except that if I enter this page for the first time, the first and second echo return nothing. Only if I refresh the page is the cookie set and then both echo print the "ro" string I am expecting.

How can I set this cookie in order to see its value from the second echo on the first visit/page load of the user? Should be without needing to refresh the page or create a redirect.

like image 551
Teodor Avatar asked May 24 '12 13:05

Teodor


People also ask

How do you check if cookies are set or not in laravel?

Forum Check if cookie exists and is not null Last updated 3 months ago. You can get cookies from request: $value = Request::cookie('name', $defaultValue); if (Request::hasCookie('phone')) { ... }

How can I see cookies in PHP?

Accessing Cookies with PHP Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example. You can use isset() function to check if a cookie is set or not.

How can I tell if PHP cookies are expired?

php function secToDays($sec){ return ($sec / 60 / 60 / 24); } if(isset($_COOKIE['cookie'])){ if(round(secToDays((intval($_COOKIE['cookie']) - time())),1) < 1){ echo "Cookie will expire today"; }else{ echo "Cookie will expire in " .


1 Answers

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {     setcookie('lg', 'ro');     $_COOKIE['lg'] = 'ro'; } echo $_COOKIE['lg']; 
like image 56
Treffynnon Avatar answered Oct 05 '22 02:10

Treffynnon