【问题标题】:PHP sessions not showing up properly in terminalPHP 会话未在终端中正确显示
【发布时间】:2018-09-16 11:28:46
【问题描述】:

我目前正在为 cron 作业构建一个小脚本,我正在终端 (Linux) 中测试所有内容,但我无法弄清楚为什么会话无法正常工作。

session_start()
$_SESSION['cron'] = 'test';
echo $_SESSION['cron'];

【问题讨论】:

  • 您已经开始会话了吗? (session_start())
  • 您是否启动了会话,该数组是否包含使用会话的所有其他页面中的值?
  • 我只是不明白使用 cron 会话。这真的有效吗?
  • 我在所有事情之前都有 session_start,我需要会话来为每个作业设置旧时间戳
  • 会话不能在终端上工作,它可以在浏览器上工作。但是你可以像this solution

标签: php linux session terminal cron


【解决方案1】:

这是我的解决方案

private function get($key){
    $content = @file_get_contents( __DIR__ . '/../../cron/data.json' );
    if ($content) {
        $content = json_decode($content, true);
        if ( is_array($content)) {
            return $content[$key];
        }else{
            return false;
        }           
    }else{
        return false;
    }
}

private function request($key){
    $content = @file_get_contents( __DIR__ . '/../../cron/data.json' );
    if ($content) {

        $content = json_decode($content, true);
        if ( is_array($content)) {
            $content[$key] = time();
            file_put_contents( __DIR__ . '/../../cron/data.json' , json_encode($content) );
        }else{
            return false;
        }

    }else{
        file_put_contents( __DIR__ . '/../../cron/data.json' , json_encode(['demo' => time()]) );
    }
}

【讨论】:

  • 请记住这是演示代码,请自行修复
  • 这与问题中的脚本有何关系?我在那里没有看到任何课程
【解决方案2】:

如果我没记错 PHP,你需要先初始化会话:

session_start();

请参阅doc。

【讨论】:

  • 深思熟虑:在发布答案并查看帖子下方留下的 cmets 之前,请务必等待几分钟。
  • @Funk Forty Niner:你们在我写答案的时候发表评论。 :)
猜你喜欢
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多