Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing $_COOKIE immediately after setcookie()

Tags:

php

cookies

I'm trying to access a cookie's value (using $_COOKIE) immediately after calling the setcookie() function in PHP. When I do so, $_COOKIE['uname'] isn't set. Why?

Note, however, that $_COOKIE['uname'] is set as expected upon the next execution of the script, such as after a page refresh.

setcookie('uname', $uname, time() + 60 * 30); echo "Cookie value: " . $_COOKIE['uname']; 
like image 661
heapzero Avatar asked Jul 12 '10 16:07

heapzero


People also ask

What is the use of Setcookie () function?

The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.

What is the default expire time of a cookie if not specified in the Setcookie () function?

For instance, time()+60*60*24*30 will set the cookie to expire in 30 days. Another option is to use the mktime() function. If set to 0 , or omitted, the cookie will expire at the end of the session (when the browser closes).

What does $_ cookie mean?

PHP Create/Retrieve a Cookie The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer). We then retrieve the value of the cookie "user" (using the global variable $_COOKIE).

How many arguments we can pass in Setcookie () in PHP?

PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag.


1 Answers

The cookie isn't set until the response is sent back to the client, and isn't available in your PHP until the next request from the client after that.

However, when you set the cookie in your script, you can do:

setcookie('uname', $uname, time()+60*30); $_COOKIE['uname'] = $uname; 
like image 117
Mark Baker Avatar answered Oct 11 '22 04:10

Mark Baker