Cookie不能用于php会话文件:

时间:2010-02-28 12:56:53

标签: php session cookies

我尝试了以下内容:

基本上,它应该说:如果没有cookie,请从网络浏览器获取lang(这部分有用,这是lang.php的工作)。如果有cookie,会话将从cookie中获取其值。如果没有,请将其保留为英语。

session.php文件

/* Class constructor */
function Session(){
    $this->time = time();
    $this->startSession();
}

function cf($filename){//function to clean a filename string so it is a valid filename
    $fp = explode('/',$filename);
    $num = count($fp);
    return $fp[$num-1];
}

/**
 * startSession - Performs all the actions necessary to
 * initialize this session object. Tries to determine if the
 * the user has logged in already, and sets the variables
 * accordingly. Also takes advantage of this page load to
 * update the active visitors tables.
 */
function startSession(){
    session_start();   //Tell PHP to start the session

    /* Set referrer page */
    if(isset($_SESSION['url'])){
        $this->referrer = $search = $this->cf($_SESSION['url']);
    }else{
        $this->referrer = "/";
    }

    /* Set current url */
    $this->url = $_SESSION['url'] = $this->cf($_SERVER['PHP_SELF']);

    /* Set user-determined language: */
    //set up languages array:
    $langs = array('en','es','zh');
    //
    if(isset($_GET['lang'])){
        if(in_array($_GET['lang'],$langs)){
            $this->lang =  $_SESSION['lang'] = $_GET['lang'];
            setcookie($_SESSION['lang'], time() + (3600 * 24 * 30));
        }
    }
    else if(isSet($_COOKIE['lang'])) {
        $_SESSION['lang'] = $_COOKIE['lang'];
    }
    else {
        $_SESSION['lang'] = 'en';
    }
}

};

2 个答案:

答案 0 :(得分:1)

setcookie的第一个参数是cookie名称,第二个参数是cookie值。因此,在这种情况下,$_SESSION['lang']是Cookie名称,time() + (3600 * 24 * 30)是值:

setcookie($_SESSION['lang'], time() + (3600 * 24 * 30));

答案 1 :(得分:1)

setcookie的参数如下:

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

因此,你使用它的方式似乎有点奇怪。 (这说的并不是错误的。)我想到了像...这样的东西。

setcookie('lang', $_SESSION['lang'], time() + (3600 * 24 * 30));

......会更明显一点,也许就是你所追求的。 (这就是$ _COOKIE ['lang']所要求的。)