我正在构建一个 API 来存储注册用户数据。数据使用CURL with an api-key
. 我需要检查 api-key 是否有效。如果它无效,则返回带有 CURLINFO_HTTP_CODE 的错误消息。我回了消息。但是 CURLINFO_HTTP_CODE 是 200。我需要将其更改为 500。怎么做?我正在使用SLIM 框架
数据发布代码。
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";
}