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

后端 未结 5 977
孤街浪徒
孤街浪徒 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: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.

提交回复
热议问题