【问题标题】:function not reevaluated on each call每次调用都没有重新评估函数
【发布时间】:2016-02-16 20:57:13
【问题描述】:

好的,我有一个函数:newCSRF($formID);生成一个我在表单中调用的 CSRF 令牌。像这样

if(){
    echo "<some html form>". newCSRF("login-form")."<rest of html>";
}

在同一个 index.php 页面上还有另一个表单

if(){
    echo "<some html form>". newCSRF("register-form")."<rest of html>";
}

那些 csrf 令牌应该是不同的(我已经检查过 newCSRF() 没有任何问题。但它们不是...... 为了证明如果我把它们写成它应该可以工作:

echo "<some html form>"; echo newCSRF("register-form"); echo "<rest of html>";

效果很好。我的第一个拼写有什么问题??我不喜欢第二个,我觉得这很奇怪。

EDIT 添加了 newCSRF():

function newCSRF($formId)
{
    $c_ip = $_SERVER['REMOTE_ADDR']; //gets the client IPv4 address

    //generates a unique security token, randString has been added beacuse of dupes when refresh spamming.
    //$csrf = dechex(crc32($c_ip."".$formId."".time()."".randString(16)));
    $csrf = hash("crc32", $c_ip + $formId + time() + randString(16));

    try
    {
        $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;

        //connecting to the sql server
        $bdd = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD, $pdo_options);

        $a = $bdd->prepare('INSERT INTO csrf (form_id, client_ip, token, expire) VALUES(:form, :ip, :csrf, :expi)');

        $a->execute(array(
                'form'  => ichar($formId),
                'ip'    => $c_ip,
                'csrf'  => $csrf,
                'expi'  => time() + 1800)); //CSRF token remains valid for 15 min.
        $bdd = null;
        log_write("New CSRF token successfuly created", 0, false);
    }
    catch (PDOException $e)
    {
        log_write("Error occured when creating new CSRF token", 3, false);
        log_write("in File: " . __FILE__ . " on line: " . __LINE__ . " : " . $e->getMessage(), 3, false);
        $bdd = null;
        exit(1);
    }
    return $csrf;
}

【问题讨论】:

  • 您的if 语句检查真实-ness 是什么?在您的代码中,评估为空。在你的实际代码中是这样的吗?
  • 请提供 newCSRF() 函数的代码。
  • 任何时候有人说“我已经检查过,我确定...没有问题”,这几乎总是问题所在。
  • 不,这只是因为我希望它简短,他们正在检查是否存在 $_SESSION['connected'] 和他的值 == 1 但两种形式同时显示在页面上反正时间。当用户连接时隐藏它们。
  • @nakashu 我已经更新了我的问题

标签: php function echo call


【解决方案1】:

就您获得相同价值的原因而言,这里有几个因素在起作用。首先,您对newCSRF() 的两次调用可能非常接近,以至于当您在每个调用中调用time() 时,您将获得相同的值。其次,虽然这里没有显示它的内容,但我猜randString() 返回(顾名思义)一个文本字符串。由于您正在进行数学加法而不是连接,因此来自 $formIdrandString(16) 的文本字符串对于从每次调用中获得不同的值确实没有帮助。由于time() 在两次调用中都相同,因此每次调用中的整个计算在数学上都是等效的。

通过切换到串联,$formIdrandString(16) 都将真正发挥作用,time() 相同的事实不会成为问题。每次调用 newCSRF() 都会得到不同的结果(假设 $formId 不同)。

简而言之,解决方法是将$c_ip + $formId + time() + randString(16)改为$c_ip . $formId . time() . randString(16)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-15
    • 2021-06-20
    • 2015-03-29
    • 1970-01-01
    • 2011-08-05
    • 2012-12-23
    • 1970-01-01
    相关资源
    最近更新 更多