How to Set a Cookie and Then Redirect in PHP

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

If you have human-readable 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.

Set cookie and redirect if cookie set based on url

To retrieve the Order ID

$order_id = wc_get_order_id_by_order_key( $_GET['key'] );

I would suggest to use a session instead of cookie so you can do something like

if(isset($_SESSION['order_'.$order_id])) {
header("Location: /where-you-want");
die;
} else {
$_SESSION['order_'.$order_id] = 1;
}

Please note that both Session and Cookies need to be set before any other output on the page, so be sure that the code you're running is executed before any HTML is printed.

Cookie dynamic redirect

Well, you could use a query parameter, eg. index.php?noredirect=1, and in your script:

if(isset($_COOKIE['landing']) && $_GET['noredirect'] != 1) {
header('Location: home.php');
} else if(!isset($_COOKIE['landing'])) {
setcookie('landing', true, $time);
}

Now if you append ?noredirect=1 to the url, the user will not be redirected, but by default they will (if the cookie is set).

PHP cookies and redirection

Try:

if( !isset($_COOKIE["first_time"]) ){

$browser_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

setcookie("first_time", "1", time()+3600, "/", "", 0);
if( !isset($_COOKIE["first_time"]) ){
header("Reload:0");
}
if ($browser_lang == "fr") {
header("Location: /fr");
}
}


Related Topics



Leave a reply



Submit