Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - setcookie to an empty value not working

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']);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...