13

I face some problem on my script that I use PHP and jquery to create login system.

First I have PHP page contain form for login. when user click submit I use jquery to send data to server

$.post('server_login.php', {username:username.val(), password:password.val()}, function(data){
    alert(data);
}); 

in server_login.php I have function to doing login user.

if($_POST['username']=='username' && $_POST['password']=='1234'){
    $expire = time() + 60*60*24*30; //1 month expired.
    setcookie("user_id", $_POST['username'], $expire);
    echo true;
}

and jquery alert "1" on my login page.

the problem is when i refresh my website and retieve cookie, it not show me.

print_r($_COOKIE);

anything wrong?

Giffary
  • 3,060
  • 12
  • 50
  • 71
  • 1
    You might find [`new Cookie($name)`](https://github.com/delight-im/PHP-Cookie/blob/004cde69ec840e65c15275e09b92ecb1da06f357/src/Cookie.php#L51) and [`$cookie->setPath($path)`](https://github.com/delight-im/PHP-Cookie/blob/004cde69ec840e65c15275e09b92ecb1da06f357/src/Cookie.php#L104) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Cookie). – caw Sep 21 '16 at 03:23

2 Answers2

20

If the script you are calling is located in another folder on the server (or via url rewrite it appears as if it is under another path), make sure to set the path parameter of the cookie.

By default, setcookie() sets the cookie only for the current path.

If your page is www.domain.com and you make ajax call to www.domain.com/auth/login.php the cookie will be set to /auth and will not be available outside /auth.

So try changing to this:

setcookie("user_id", $_POST['username'], $expire, '/');
Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
0

I try below code in my script. Please once try this code if you get cookie value than something wrong with your code but if this code also not work than check your browser cookie option enabled or not. if cookie disabled by browser than also you can't get any cookie value.

For enabling browser cookie follow below link http://www.blogpatrol.com/enable-cookies.php.

Test Code 1:

$expire = time() + 60*60*24*30; //1 month expired.

setcookie("TestCookie", "shashank patel here", $expire);

print_r($_COOKIE);

Test code 2:

Also check this code with your script this code told you your browser cookie enabled or not.

error_reporting (E_ALL ^ E_WARNING ^ E_NOTICE);

// Check if cookie has been set or not

if ($_GET['set'] != 'yes')
{
  // Set cookie
  setcookie ('test', 'test', time() + 60);

  // Reload page
  header ("Location: test.php?set=yes");
} 
else
{
  // Check if cookie exists
  if (!empty($_COOKIE['test']))
  {
     echo "Cookies are enabled on your browser";
  } 
  else 
  {
    echo "Cookies are NOT enabled on your browser";
  }
}
Shashank Patel
  • 459
  • 3
  • 6