给用户200响应后执行php代码

时间:2019-03-28 09:46:03

标签: php laravel-5

我正在构建一个API。其中有一些不需要执行的代码即可为用户提供响应。因此,我想在执行强制代码后给出响应,并在后台运行其余代码。

这是运行apache和PHP7.2的Linux服务器

        ignore_user_abort(true);
        set_time_limit(0);

        ob_start();

        $api_key = $request->get('api_key');
        $clientToken = ClientToken::where('token', $api_key)->where('is_blocked', 0)->get();
        if (count($clientToken) > 0) {
            $dateTime = date_create_from_format('d-m-Y H:i:s a', $request->get('date_time'));
            $missCallRequest = new MissCallRequest();
            $missCallRequest->client_token_id = $clientToken[0]->id;
            $missCallRequest->called_number = "+" . $request->get('called_number');
            $missCallRequest->caller_number = $request->get('caller_number');
            $missCallRequest->datetime = date_format($dateTime, 'Y-m-d H:i:s');
            $missCallRequest->operator = $request->get('operator');
            $missCallRequest->circle = $request->get('circle');
            $missCallRequest->request_url = urldecode($request->fullUrl());
            $missCallRequest->save();

        }

        $response = [
            "status" => 200,
            "message" => "Request Received",
        ];

        echo json_encode($response); // send the response

        // Get the size of the output.
        $size = ob_get_length();

        // Disable compression (in case content length is compressed).
        header("Content-Encoding: none");

        // Set the content length of the response.
        header("Content-Length: {$size}");

        // Close the connection.
        header("Connection: close");

        // Flush all output.
        ob_end_flush();
        ob_flush();
        flush();

        echo "hello";

这是在强制性代码之后做出的响应,但是在响应后没有执行其余代码。

1 个答案:

答案 0 :(得分:0)

使用此命令可确保立即发送200

ignore_user_abort(true);
ob_start();
header("HTTP/1.1 200 OK");
header('Connection: close');
header('Content-Length: '.ob_get_length());
ob_end_flush();
ob_flush();
flush();