500 Internal Server Error in POSTMAN for PHP API
What to expect. A 500 Internal Server Error is an HTTP status code that indicates that the server encountered an unexpected error while processing the request. Note: Reach out to the API service and check the status page of the API Service and see if their systems are operational.
My code is throwing a 500 Internal Server Error because of this line:
phpheader($_SERVER['SERVER_PROTOCOL']. '500 Internal Server Error')It should be:
phpheader($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');There needs to be a space after the protocol version (e.g., "HTTP/1.1 500 Internal Server Error"), otherwise, it can cause issues.
Other Potential Issues:
- Incorrect Content-Type Check
- Some clients send
Content-Type: application/json; charset=utf-8, which doesn't strictly match"application/json". Usestripos()instead: if (stripos($incommingContentType, 'application/json') === false) { header($_SERVER['SERVER_PROTOCOL'] . ' 415 Unsupported Media Type'); echo json_encode(["error" => "Content-Type must be application/json"]); exit(); }
- Error Handling for
json_decode()
- If
json_decode()fails (e.g., malformed JSON), it returnsnull. Add error checking: - php
if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) { header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request'); echo json_encode(["error" => "Invalid JSON input"]); exit(); }
Fixed Code
error_reporting(E_ALL ^ E_NOTICE);/*-------- Start Code to Accept JSON post content --------------*/
header('Content-Type: application/json');$incomingContentType = $_SERVER['CONTENT_TYPE'] ?? '';if (stripos($incomingContentType, 'application/json') === false) {
header($_SERVER['SERVER_PROTOCOL'] . ' 415 Unsupported Media Type');
echo json_encode(["error" => "Content-Type must be application/json"]);
exit();
}$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
echo json_encode(["error" => "Invalid JSON input"]);
exit();
}// Process JSON normally
echo json_encode(["success" => "JSON received successfully"]);
Improvements:
✔ Fixed 500 error formatting
✔ Used stripos() to handle Content-Type variations
✔ Added JSON validation
✔ Provided descriptive error messages
Get www.jyotishgher.in’s stories in your inbox
Join Medium for free to get updates from this writer.
Try this version and let me know if you still face issues! 🚀










