带有会话 ID 的 POST 请求卡住而不会出错


POST request with session id gets stuck without error

我正在尝试用php创建一个简单易用的API,但我遇到了多个问题。我正在开发一个执行基本 CRUD 工作的用户 API。

如果我使用 cURL 向我的用户 api(用户.php(发出 POST 请求,则在执行用户.php期间会使用新的会话 ID。

因此,为了解决这个问题,我尝试将带有 POST 请求的当前会话 ID 发送给用户.php。我现在遇到的问题是,在使用session_id($_POST['session'])设置id然后使用session_start()启动会话后,我的服务器将卡在执行该代码时,最终将抛出内部服务器错误500。

试图让我的服务器向我展示ini_set('display_errors', 1);和.htaccess文件(内容:php_flag display_errors 1(的错误是什么,但无济于事,服务器只是卡住了。

测试.php

<?php
    session_start();
    // Check for available session
    if (!isset($_SESSION['id'])) {
        header('location: index.php');
    } else {
        // Initialize cURL
        $curl = curl_init();
        // Set parameters for POST request
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => 'http://localhost/api/user.php',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => http_build_query([
                'session' => session_id(),
                'username' => 'testuser',
                'password' => 'testalot',
                'name' => 'testuser',
                'isAdmin' => 0
            ])
        ]);
        // Execute POST request
        $response = curl_exec($curl);
        /* <<< Doesn't get beyond this point. */
        // Dump JSON
        var_dump($response);
        // Close cURL session
        curl_close($curl);
    }
?>

用户.php

<?php
  // Declare integer checking function
  function isInteger($input) {
    return ctype_digit(strval($input));
  }
  // Declare result object
  $output = ['success' => false, 'data' => [], 'error' => ''];
  // Action on POST
  if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check if session id was sent
    if (!empty($_POST['session'])) {
      // Set session id
      session_id($_POST['session']);
      // Start session with received session id
      session_start();
      /* <<< Freezes at this point. */
      // Check session for available user id
      if (isset($_SESSION['id'])) {
        // Only admins are allowed to execute POST requests
        if ($_SESSION['isAdmin'] == 1) {
          // ... more code ...
当然,我

也会使用不同的方法来访问我的 API,该方法不需要我发送当前会话 ID(如果有的话(。有什么想法吗?

更新:

看看@Neok在我的问题下的评论。这就是解决办法。只是为可能有相同问题的其他人指出它。

确保 php.ini 设置为记录所有错误

error_reporting(E_ALL);

ini_set('error_reporting', E_ALL);
PHP 文档说session_id()返回当前会话的会话 ID,如果没有当前会话(

不存在当前会话 ID(,则返回空字符串 (""(。因此,与其服用$_SESSION['id'],不如尝试:

// Check for available session
if (session_id() == "") {
    header('location: index.php');
} else {
    ...
}

否则,代码将重定向到 index.php 在循环中导致错误 500。