How can I set a cookie and then redirect in PHP?

后端 未结 5 966
孤街浪徒
孤街浪徒 2020-11-29 06:19

After doing a bit of processing, I want to set a cookie value to user input and then redirect them to a new page. However, the cookie is not getting set. If I comment out

相关标签:
5条回答
  • 2020-11-29 07:05

    I'm assuming you are running IIS? There is a know bug with IIS versions less than 7 when attempting to both set a cookie and a location header in the same request.

    http://support.microsoft.com/kb/q176113/

    0 讨论(0)
  • 2020-11-29 07:07

    If you have human urls or subfolders (like www.domain.com/path1/path2/), then you must set cookie path to / to work for all paths, not just current one.

    if($form_submitted) {
        ...
        setcookie('type_id', $new_type_id, time() + 60*60*24*30, '/');
        header("Location: $url");
        exit;
    }
    

    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.

    0 讨论(0)
  • 2020-11-29 07:08

    How are you testing if the cookie is set? Cookies are available on the next page after they are set.

    Common Pitfalls:

    Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

    0 讨论(0)
  • 2020-11-29 07:08

    Use a relative URL in the header:

    @Header("Location: orders_9090_1.php");
    
    0 讨论(0)
  • 2020-11-29 07:09

    I was able to solve this problem by using a slight delay in the refresh header. We set the header (which must be done before any methods which might output, like setcookie), and then set the cookies. I added a message so that the user doesn't see a blank screen for those couple seconds.

        header("refresh: 2; url=$url");
        setcookie('type_id', $new_type_id, time() + 60*60*24*30, '/');
        echo "Processing, please wait...";
    
    0 讨论(0)
提交回复
热议问题