Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setcookie to an empty value not working

Tags:

php

cookies

i have this code im trying to do for a type of cache system so it remembers the city the user has selected. if the user has selected a city it stores it in sessions and cookies, and will automatically redirect them to the city page if they've selected it before.

sessions work fine, but it doesn't seem to be setting the cookie to an empty value if the $_GET['city'] variable is empty...

heres my code:

function gen_url ($city)
{
    $url = 'http://www.mysite.com';

    if (!empty($city)) $url .= "/c-$city";

    return $url;
}

function set_cache ($variable, $value)
{
    $_SESSION[$variable] = $value;
    setcookie($variable, $value, time() + 31536000);
}

$redirect = false;
$redirect_array['city'] = '';

if (!empty($_GET['city']))
{
    $sql = mysql_query("select * from `cities` where `slug`='".mysql_real_escape_string($_GET['city'])."'");

    if (mysql_num_rows($sql) != 0)
    {
        while ($row = mysql_fetch_assoc($sql))
        {
            foreach ($row as $k => $v)
                $city[$k] = $v;
        }

        $redirect_array['city'] = $city['slug'];
    }
    else
    {
        $redirect = true;
    }
}   

if ($redirect)
{
    header('Location: '.gen_url($redirect_array['city']);
    die();
}

set_cache('city', $redirect_array['city']);
like image 663
scarhand Avatar asked Sep 01 '26 08:09

scarhand


2 Answers

You can't set a cookie with an empty string as it will delete the cookie.

From the docs:

If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.

like image 101
Rich Adams Avatar answered Sep 03 '26 22:09

Rich Adams


You can't set a cookie to most falsy values to indicate falseness of a trit cookie. Only '0' will work. Use that.

like image 29
Explosion Pills Avatar answered Sep 03 '26 21:09

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!