Reputation: 3539
I'm facing a strange problem.
I'm sending an AJAX to a PHP file which sets a $_COOKIE['cookieName']
Then I'm echoing that cookie in the main file.
Problem: If the PHP file which handles the AJAX is in the same folder as the view file, the $_COOKIE['cookieName']
will echo fine. If however I move it to a different directory, the Ajax response will come through successfully, but the '$_COOKIE' won't echo in the view file, as though it was never set, or doesn't exist.
File that handles AJAX:
$exp = time()+ 3600;
setcookie("cookieName", "tiger", $exp);
if(isset($_COOKIE['cookieName'])) {
echo "Ajax Response: " .$_COOKIE["cookieName"]. " cookie is set";
} else if(!isset($_COOKIE['cookieName'])) {
echo "Ajax Response: Session NOT SET";
}
The view file:
<script>
$(document).ready(function(){
var boxText = "test";
$.ajax({
type: "POST",
url: "login.php",
//login.php is in the same directory, so $_COOKIE will echo below.
// If I moved the file to folder/login.php AJAX will come back successfully, but $_COOKIE won't echo...
data: {sendValue: boxText, ajaxSent: true},
success: function(response){
console.log(response);
}
});
});
</script>
<div >
Cookie name is.....<?php echo $_COOKIE['cookieName'];?>
</div>
Upvotes: 7
Views: 4355
Reputation: 3694
The fourth param is 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("cookiekey", "value", $exp, '/');
so if you are not setting 4th param, then the default value which is the current directory is picked,
Upvotes: 2
Reputation: 26699
You have to set the $path parameter of the cookie, otherwise it's set only for the current path, as seen in the url.
setcookie("cookieName", "tiger", $exp, '/');
Upvotes: 8