13

I'm validating a login form with jQuery AJAX call to PHP. In php, I create a session and if they checked the 'remember me' checkbox, I want to create a cookie. Here's the php code:

<?php

include '../includes/connection.php';
date_default_timezone_set('GMT');

$name = $_POST['username'];
$pass = $_POST['password'];


$query = mysql_query("SELECT id, username, password FROM users WHERE username = '$name' LIMIT 1");

if(mysql_num_rows($query) == 0) {
 echo 'error';
 exit;
}

while($row = mysql_fetch_array($query)) {

 if($row['username'] == $name && $row['password'] == $pass) {

  session_start();
  $_SESSION['username'] = $row['username'];
  $_SESSION['usrID'] = $row['id'];
  echo 'success';


  if($_POST['remember']) {
   setcookie('username', $row['username'], $exp);
   setcookie('password', $row['password'], $exp);
   setcookie('usrID', $row['id'], $exp);
  }

 } else {
  echo 'error';
  exit;
 }



}


?>

The session is set successfully, however the cookie is not set at all. I've tried setting all the values (domain, path, etc.) but that didn't change anything. Is there anything obvious I'm missing?

williamg
  • 2,738
  • 6
  • 34
  • 48
  • Where is the variable `$exp` coming from? – Sarfraz Aug 07 '10 at 20:30
  • sorry, that was just a typo, $exp is defined earlier as the expiration date (2 months) – williamg Aug 07 '10 at 20:32
  • 4
    oooooh, i don't think you want to be setting the password in the cookie, even if its md5'ed. Session ID is much better – CpILL Jun 20 '12 at 07:06
  • You might find [`new Cookie('some-name')`](https://github.com/delight-im/PHP-Cookie/blob/004cde69ec840e65c15275e09b92ecb1da06f357/src/Cookie.php#L51) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Cookie). – caw Sep 21 '16 at 02:08

2 Answers2

20

Here are few suggestions:

  • Make sure that you are specifying the correct expiration format of date
  • When setting a cookie on a page that redirects, the cookie must be set after the call to header('Location: ....'); eg:

    header('Location: http://www.example.com/'); setcookie('asite', $site, time()+60*60, '/', 'site.com');

  • If you have human urls like www.domain.com/path1/path2/, then you must set cookie path to / to work for all paths, not just current one.

    setcookie('type_id', $new_type_id, time() + 60*60*24*30, '/');

Notice the last / in the arguments.

From PHP 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.

  • setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script meaning there should be no html/code echo statements before that.
random_user_name
  • 25,694
  • 7
  • 76
  • 115
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Awesome! I was making an echo statement before, changed that, and everything worked, except that when I try to make the path to the root ('/') it doesn't set the cookies...am I doing something wrong? – williamg Aug 07 '10 at 22:38
  • Try removing the last argument that is `'/'` – Sarfraz Aug 07 '10 at 22:48
  • If I do that, it works, but only with the current directory, which is not the root. – williamg Aug 07 '10 at 22:50
  • I understand that setting the path to '/' allows access from all directories, which is what I want. However, when I do that and add in the path, the cookie isn't set. It is only set when I leave out the path. – williamg Aug 07 '10 at 23:12
  • 1
    Specifying the domain fixed the problem. – williamg Aug 08 '10 at 19:29
-17

You won't be able to set the cookie server-side when using an AJAX call. Instead, wait until you get a successful response and set the cookie client side. To make it easier, you could use a jQuery plugin.

David Kaneda
  • 5,320
  • 1
  • 21
  • 14
  • 16
    I'm sorry, but why it's impossible to set cookie using Ajax call? Ajax call is a regular http request with it's own request and response headers. We're able to put any information into respose header, including cookies. Am I not right? – Kirzilla Aug 07 '10 at 20:55
  • 1
    Why in the world did 5 people upvote this? It's simply outright wrong to say that you can't return a set-cookie header from an AJAX call or that browsers won't honour them, and the talking of 'setting the cookie server-side' seems to indicate some basic confusion about how HTTP works. – Mark Amery Apr 05 '13 at 15:24
  • 1
    Echoing everyone else's sentiments. This answer should be removed, as it is completely and utterly incorrect. – maiorano84 Aug 19 '16 at 17:40
  • You can set a cookie in ajax and you don't need a jQuery plugin neither jQuery to set a cookie, you can do that with document.cookie : https://www.w3schools.com/js/js_cookies.asp – Benjamin Seche Apr 01 '20 at 06:50