Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a cookie in an AJAX request?

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?

like image 331
williamg Avatar asked Aug 07 '10 20:08

williamg


1 Answers

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.
like image 64
Sarfraz Avatar answered Sep 20 '22 08:09

Sarfraz