I am building an API to store registered users data. Data is passed using CURL with an api-key
. I need to check the api-key is valid or not. If it is not valid return an error message with an CURLINFO_HTTP_CODE. I returned the message. But the CURLINFO_HTTP_CODE is 200. I need to change it to 500. How to do that? I am using SLIM framework
Data Posting code.
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;
}
Following is the code which will respond to the CURL operation
$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";
}
What you're looking for is $app->halt()
. You can find more info in the Route Helpers section of the Slim documentation.
The Slim application’s
halt()
method will immediately return an HTTP response with a given status code and body. This method accepts two arguments: the HTTP status code and an optional message.
That'll make is super easy to return a 500 and a message, but you might consider using $app->notFound()
instead, since you're trying to send the message that the requested project is not found (404), rather than a server error (5xx).
You could set the header to 500
header("HTTP/1.1 500 Internal Server Error");
or try using a try catch and throw the error
throw new Exception("This is not working", 500);