在不同的环境中的PHP会话变量将无法正常工作

时间:2013-06-11 12:44:21

标签: php session session-variables

以下脚本适用于windows xampp,php 5.3.8

session_start();
    if (empty($_SESSION['myvar']) && empty($_GET['myvar'])) {
        $myvar = "some_value";
    } elseif (!empty($_GET['myvar'])) {
        $_SESSION['myvar'] = $_GET['myvar'];
    }
    $_SESSION['myvar'] = $myvar;

但在ubuntu服务器上,如果我var_dump($myvar)值为null

,则为php 5.3.10

3 个答案:

答案 0 :(得分:1)

您是否认为您可能会定义两次会话变量,覆盖if语句中定义的第一个?此外,如果您在!($ _ GET ['myvar'])为真时运行以下代码:

session_start();
if (empty($_SESSION['myvar']) && empty($_GET['myvar'])) {
    $myvar = "some_value";
} elseif (!empty($_GET['myvar'])) {
    $_SESSION['myvar'] = $_GET['myvar'];
}
$_SESSION['myvar'] = $myvar;

你最喜欢得到一个未定义的变量警告,因为你没有设置$ myvar。试试这个:

session_start();
if (empty($_SESSION['myvar']) && empty($_GET['myvar'])) {
    $myvar = "some_value";
    $_SESSION['myvar'] = $myvar;
} elseif (!empty($_GET['myvar'])) {
    $_SESSION['myvar'] = $_GET['myvar'];
}

答案 1 :(得分:0)

如果session或get参数为空,则只向$myvar添加值。否则为空。 怎么样:

session_start();
$my_var = isset($_SESSION['my_var'] ? $_SESSION['my_var'] : 'default_value';
if(empty($_SESSION['myvar']) && empty($_GET['myvar'])){
    $myvar = 'some_value';
} elseif(!empty($_GET['my_var'))) {
    $myvar = $_GET['myvar'];
}
$_SESSION['my_var'] = $myvar;

或者简单地说:

session_start();
$_SESSION['my_var'] = isset($_GET['my_var']) ? $_GET['my_var'] : (isset($_SESSION['my_var']) ? $_SESSION['my_var'] : 'default_value');

答案 2 :(得分:0)

empty($_SESSION['myvar']) && empty($_GET['myvar'])

这一直是假的。 因为第一次$ _SESSION ['myvar']是空的,$ _GET ['myvar']不是空的:

$_SESSION['myvar'] = $myvar; // now $myvar is empty



 if (empty($_SESSION['myvar']) && empty($_GET['myvar'])) {
        $_SESSION['myvar'] = "some_value";
    } elseif (!empty($_GET['myvar'])) {
        $_SESSION['myvar'] = $_GET['myvar'];
    }