setcookie到一个空值不工作 [英] setcookie to an empty value not working

查看:404
本文介绍了setcookie到一个空值不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码我试图做一种类型的缓存系统,所以它记住用户选择的城市。如果用户选择了城市,则会将其存储在会话和Cookie中,如果他们之前已选择城市,则会自动将其重定向到城市页面。



会话工作良好,但是如果$ _GET ['city']变量为空,它似乎没有将cookie设置为空值...



我的代码:

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

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

return $ url;
}

函数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']);
p $ p>

解决方案

您不能设置一个带有空字符串的cookie,因为它会删除该cookie。



文档


如果value参数是空字符串或FALSE,而所有其他
参数匹配以前对setcookie的调用,那么cookie的
指定的名称将从远程客户端中删除。



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']);

解决方案

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.

这篇关于setcookie到一个空值不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆