PHP函数无法正常工作

时间:2014-10-22 12:48:46

标签: php function session if-statement

我创建简单的功能,如果条件对用户进行大访问:

以下代码正常运行。

$_SESSION['role'] = 3

if($_SESSION['role'] == 1 || $_SESSION['role'] == 2){
    echo "Access Granted";
}
else
{
    echo "Access Denied";
}

上面的代码对我有用,但是当我将其转换为如下代码的函数时,它不适用:

function access($allowed_users) {

    foreach ($allowed_users as $key => $value) {
            $user .= $_SESSION['role'] ." == ".$value." || ";  // Here I'm generating statement to use in If condition
    }

    $user = substr(trim($user), 0, -3);

    if($user){
        echo "Access Granted";
    }
    else
    {
        echo "Access Denied";
    }
}

access(array('1', '2'));

这不起作用,并且在显示Access Granted时始终显示Access Denied,因为$_SESSION['role']值为3。

4 个答案:

答案 0 :(得分:3)

除非您使用eval,否则无法像在运行时那样生成条件。

foreach ($allowed_users as $key => $value) {
        $user .= $_SESSION['role'] ." == ".$value." || ";  // Here I'm generating statement to use in If condition
}

$user = substr(trim($user), 0, -3);

您需要的是功能in_array

function access($allowed_users)
{
    // in_array needs always an array as second parameter
    // handle a non array argument: (e.g. access(2))
    if (!is_array($allowed_users)) $allowed_users = array($allowed_users);

    // Check if $_SESSION['role'] is in $allowed_users
    if (in_array($_SESSION['role'], $allowed_users)) {
        echo 'Access granted';
    } else {
        echo 'Access denied';
    }
}

答案 1 :(得分:3)

你无法评估这样的字符串 - 由于php类型比较,你的代码只返回true:

http://php.net/manual/en/types.comparisons.php

你可以(但肯定不应该)使用if(eval($user))。重构会更好:

function access($allowed_users) {

    if(in_array($_SESSION['role'], $allowed_users)) // There was syntax error here because bracket was not closed
    {
        echo "Access Granted";
    }
    else
    {
        echo "Access Denied";
    }
}

答案 2 :(得分:1)

除非$user var为0false,否则条件将始终评估为true,并且将执行并回显Access Granted。您需要提出一个更加可靠的条件语句,只有在授予访问权限时才会计算为true。提示,检查值==

答案 3 :(得分:0)

注意不同的

S_SESSION['userrole']

$_SESSION['user']

在你的函数和它上面的代码中。你有没有改变会话var?

相关问题