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?
Here are few suggestions:
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With