Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a cookie for a domain in PHP?

Tags:

php

cookies

I want to set a cookie via PHP. The scenario is like this:

Domain is: example.com

There is one web page on sub-domain (my.example.com). My code is:

$value="I am looged in";
setcookie("TestCookie", $value,'','',".example.com");
echo "hello".$_COOKIE["TestCookie"];

but the result is only "hello" - the cookie is not getting set.

like image 855
Yogesh Avatar asked Dec 27 '11 12:12

Yogesh


1 Answers

First two corrections to the actual call of setcookie: Parameter 3 (expired) should be an integer value (the default value is 0); parameter four should be set to '/' to make the cookie valid for all subdirectories; the setcookie call should therefore look like this:

setcookie("TestCookie", $value, 0, '/', ".example.com");

Then it should actually work the second time the script is called. To understand why it won't work the first time already, we have to dig in a little into how cookies work; basically, Cookies are data sent from the server to the client, where the server says "send me this data the next time you send me a request". That's basically what setcookie is for: When the request is done and the client has received and processed the page, the cookie as specified will have been created at the client; $_COOKIE, on the other hand, holds all values which are in cookies already, and which have been transmitted by the client along with the request - meaning that the first time the script is called, $_SESSION will actually still be empty, since the cookies will only be created once the client has received the scripts output.

like image 184
codeling Avatar answered Oct 06 '22 08:10

codeling