Php 如何设置CURLINFO\u HTTP\u代码

Php 如何设置CURLINFO\u HTTP\u代码,php,curl,httpresponse,slim,Php,Curl,Httpresponse,Slim,我正在构建一个API来存储注册用户数据。使用带有api键的CURL传递数据。我需要检查api密钥是否有效。如果无效,则返回一条带有CURLINFO\u HTTP\u代码的错误消息。我回信了但是CURLINFO\u HTTP\u代码是200。我需要将其更改为500。怎么做?我正在使用超薄框架 数据过帐代码 private static function postJSON($url, $data) { $jsonData = array ( 'json' => json

我正在构建一个API来存储注册用户数据。使用带有api键的
CURL传递数据。我需要检查api密钥是否有效。如果无效,则返回一条带有CURLINFO\u HTTP\u代码的错误消息。我回信了但是CURLINFO\u HTTP\u代码是200。我需要将其更改为500。怎么做?我正在使用超薄框架

数据过帐代码

private static function postJSON($url, $data) { 

    $jsonData = array (
      'json' => json_encode($data)
    ); // data array contains some data and api-key

    $jsonString = http_build_query($jsonData);
    $http = curl_init($url);

    curl_setopt($http, CURLOPT_HEADER, false);
    curl_setopt($http, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($http, CURLOPT_POST, true);
    curl_setopt($http, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($http, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/x-www-form-urlencoded',
      'Content-Length: '.strlen($jsonString)
    ));
    curl_setopt($http, CURLOPT_POSTFIELDS, $jsonString);

    $responseBody = curl_exec($http); 
    $statusCode = curl_getinfo($http, CURLINFO_HTTP_CODE);
    echo $statusCode; // need to get 500 if the api key is not registerd

    if($statusCode > 200) {
        error_log('BugTracker Warning: Couldn\'t notify ('.$responseBody.')');
    } 
    curl_close($http); 

    return $statusCode;
}
下面是响应CURL操作的代码

$apiKey = $event->apiKey;
    // Check if the project for the given api key exists. if not do not insert the bugs
    $projectDetails = $bt->getProjectDetails($apiKey);
    if(count($projectDetails)>0){
        print_r($projectDetails);
        foreach($event->exceptions as $bug){
            $errorClass = $bug->errorClass;
            $message    = $bug->message;
            $lineNo     = $bug->lineNo;
            $file       = $bug->File;
            $createdAt  = $bug->CreatedAt;

            //saving to db
            $bt->saveData($releaseStage,$context,$errorClass,$message,$lineNo,$file,$createdAt,$apiKey);
        }
    }
    else{
        // show error with 500 error code
        http_response_code(500);
        echo "Invalid project";
    }

您可以将标题设置为500

header("HTTP/1.1 500 Internal Server Error");
或者尝试使用try-catch并抛出错误

throw new Exception("This is not working", 500);

你要找的是
$app->halt()
。您可以在Slim文档的一节中找到更多信息

Slim应用程序的
halt()
方法将立即返回带有给定状态代码和正文的HTTP响应。此方法接受两个参数:HTTP状态代码和可选消息


将使返回一个500和一个消息非常简单,但是您可能会考虑,因为您试图发送未找到请求的项目的消息(404),而不是服务器错误(5xx)。

您可以在这里查看:@ jjdouser,我改变了这样的代码<代码>标题($yServer [ ServelProtog')]“500内部服务器错误”,为真,500)但得到的是相同的200响应。但是我在一个没有curl的直接http调用中尝试了这个,得到了500。问题在于使用CURL。我尝试了header方法。它不起作用。我使用的是Slim框架。你知道如何在纤细的框架中做到这一点吗?