Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP $_COOKIE is only available in one directory

Tags:

php

cookies

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>
like image 391
Allen S Avatar asked Aug 14 '13 11:08

Allen S


2 Answers

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, '/');

like image 177
Maxim Krizhanovsky Avatar answered Oct 27 '22 09:10

Maxim Krizhanovsky


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,

like image 2
Nishant Avatar answered Oct 27 '22 08:10

Nishant