Cookies not working on different pages

后端 未结 9 1642
长发绾君心
长发绾君心 2020-12-03 17:19

Ok I have a cookie set, and I can clearly see it if I go to private data in Firefox... ok so when I echo it on one page in a certain directory it works, (www.example.com/dir

相关标签:
9条回答
  • 2020-12-03 17:54

    You need to set the $path to / in setcookie(), if you want to access it in all directories

    0 讨论(0)
  • 2020-12-03 17:56

    Yes try this, I was also facing this problem but resolved by below code.

    setcookie("TestCookie", "Value", time()+3600 , '/' );
    
    0 讨论(0)
  • 2020-12-03 17:56
    setcookie('cookie_username', $cookie_username, time() + (86400 * 30), "/"); // 86400 = 1 day,  '/' denotes cookie available in entire directory.
    

    and in another page:

    $username = $_COOKIE['cookie_username'];
    

    also make sure that browser is not blocking cookies.

    If you want to use cookies in sub domain also:

    setcookie('cookie_username', $cookie_username, time() + (86400 * 30), "/", ".subdomain.com"); // 86400 = 1 day,  '/' denotes cookie available in entire directory.
    
    0 讨论(0)
  • 2020-12-03 17:57

    You need to check the path that the cookie is being set.

    If it's not '/', there's your answer!

    0 讨论(0)
  • 2020-12-03 17:58

    Set your path option; the default value is the current directory that the cookie is being set in. Because you're setting the cookie in the directory /dir , its only available within that directory or below it.

    You get around this by explicitly setting the path, ie.

    setcookie(name,value,expire,path,domain,secure) 
    

    Set the path to "/".

    0 讨论(0)
  • 2020-12-03 18:01

    Cookies can be bound to a specific domain, subdomain, path, and protocol (http/https). You need to specify the path when setting the cookie in PHP:

    setcookie("TestCookie", "Value", time()+3600 , '/' );
    

    The fourth parameter binds it to the root of the site and it will be available in any subdirectory of the main site.

    If you want it available on the main domain and any subdomain, supply the fifth parameter like this:

    setcookie("TestCookie", "Value", time()+3600 , '/', '.example.com' );
    

    Now it will be readable at:

    www.example.com
    example.com/newdir
    awesome.example.com/newdir

    0 讨论(0)
提交回复
热议问题