Web Hosting Talk







View Full Version : PHP + setcookie()


latheesan
01-04-2008, 02:07 AM
My problem is quite simple. I set a cookie, once a user logins here, like this :

/members/Login_Handler.php
<?php

// Login validated...
setcookie("ch_username", $user, time()+604800);
setcookie("ch_password", $pass, time()+604800);

?>

To test that the cookie is successfully set, i wrote a debug code like this:

/members/cookie_test.php
<?php print_r($_COOKIE); ?>

When i ran www.domain.com/members/cookie_test.php i saw the values i set at the login handler.

Now here's the problem :(
When i try to use the values from cookie in my www.domain.com/index.php (outside of the "memebrs" folder), i get nothing. I tried to do cookie test and it there is no cookie.

How can i fix this problem? I want the cookie i set made available to me anywhere on site (regardless of how deep the folder structure is).

isurus
01-04-2008, 07:34 AM
You need to specify the path for your cookie.

http://www.php.net/setcookie
bool setcookie ( string $name [, string $value [, int $expire [, string $path [, string $domain [, bool $secure [, bool $httponly ]]]]]] )
...snip...
path 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.eg change your code to:
setcookie("ch_username", $user, time()+604800, '/');
setcookie("ch_password", $pass, time()+604800, '/'); Incidentally, why are you storing their username + password in cookies? This is insecure.

BlueHayes
01-04-2008, 07:58 AM
Have a look at PHP's session handling or create your own session handling mechanism. As isurus said, storing password with username in cookies is insecure and you certainly can't just identify by a username alone. Research session handling, PHP has its own functions to handle session setups. Sorry if you're learning and I've added confusion on top, just looking to expand on where to go based on isurus' comment about the cookies being insecure!

Good luck with your development, latheesan!

azizny
01-04-2008, 12:24 PM
setcookie("ch_username", $user, time()+604800, '.domain.com');
setcookie("ch_password", $pass, time()+604800, '.domain.com');


Will work on any subdomain within the domain.

Peace,