omerjerk
omerjerk

Reputation: 4259

Unable to read cookie in php

I am creating cookies in a loginform.php file like this :

$time = time();
setcookie('myusername', $myusername, $time +60*60*24*200); // Sets the cookie username
setcookie('myuserid', $rows['userid'], $time +60*60*24*200); // Sets the cookie password
setcookie('myname', $rows['name'], $time +60*60*24*200);

this file is located in a folder named login which is located in the root directory of my website.

I am able to retrieve the cookies in loginform.php but not at anyother file in the root directory ..

What may be the problem ?

Upvotes: 0

Views: 724

Answers (2)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57640

From manual,

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

You need to set the cookie path to / to access it from anywhere. So it'll be like,

setcookie('myusername', $myusername, $time +60*60*24*200, '/'); 

Its not a good idea to set sensitive information like username or user id in cookie. Any one can change the value and become someone else.

Its better to use Session. Even the session id will be saved in cookie but its hard to guess another session id.

Upvotes: 2

Jye Lewis
Jye Lewis

Reputation: 688

when a cookie is created its root path is set to the path of the script that created, in this case /login - everything below that cannot access the cookie, add '/' as another parmeter in your setcookie

$time = time();
setcookie('myusername', $myusername, $time +60*60*24*200, '/'); // Sets the cookie username
setcookie('myuserid', $rows['userid'], $time +60*60*24*200, '/'); // Sets the cookie password
setcookie('myname', $rows['name'], $time +60*60*24*200, '/');

Upvotes: 3

Related Questions