通过 post php posting 数据后卷曲响应为空

Curl Response is Empty after posting data via post php

我有一个表单,用户可以在其中输入他的 apiKey,然后在检查错误后如果一切正常,处理脚本 post 通过 curl 将密钥发送到我的服务器进行验证。那么我的服务器应该 return success true | false 和错误代码(如果为 false)。但是当我发送文件时,curl 响应为空。

$post['apiKey'] = $apiKey;    
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL,"https://www.pawnhost.com/phevapi/verify_api.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$res = curl_exec($ch);
if ($res === FALSE) {
    echo "Curl Error:" . curl_error($ch);
}

curl_close($ch);

print_r($res);

我们要提交给的脚本:

<?php 

define("ERROR_HEADER_URL", "Location: " . $_SERVER['HTTP_REFERER'] . "?error=");

require("includes/initialize.php");

if ($_SERVER['REQUEST_METHOD'] != 'POST') header(ERROR_HEADER_URL . "invalidRequest");

if (!isset($_POST['apiKey'])) header(ERROR_HEADER_URL . "verficationFailed");

$apiKey = escape($_POST['apiKey']);

if (isInputEmpty($apiKey)) {
    header(ERROR_HEADER_URL . "emptyFields");

} elseif (!$apiKey == 25) {
    header(ERROR_HEADER_URL . urlencode("invalidKey"));

} else {

    $response = [];

    if (getApiKeyUserDetails($apiKey, $connection)) {

        if (getApiKeyUserDetails($apiKey, $connection)['apiKeyUsed'] > 0) {
            $response['success'] = false;
            $response['error'] = 'apiKeyUsed';
        } else {
            makeApiKeyUsed($apiKey, $connection);
            $response['success'] = true;
        }

    } else {
        $response['success'] = false;
        $response['error'] = 'invalidApiKey';
    }

    return json_encode($response);

}

您必须发送 $response 而不是 return 作为输出:

而不是

return json_encode($response);

使用

echo json_encode($response);

另请注意,如果 isInputEmpty($apiKey)!$apiKey == 25 评估 true 则执行不会插入最后一个条件块,您将不会有任何输出在响应的 body 中。

脚本逻辑是,对于某种错误,设置了特定的 header 来通知错误。

发送请求的 curl 脚本也应该检查 headers。

为此,您可以使用以下代码放在 curl_exec

之前
$response_headers = [];

curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
    function( $curl, $header ) use ( &$response_headers )
    {
        $len = strlen( $header );
        $header = explode(':', $header, 2);
        if( count( $header ) < 2 ) { return $len; } // ignore invalid headers
        $response_headers[ strtolower( trim( $header[0] ) ) ] = trim( $header[1] );
        return $len;
    }
);