Created
November 8, 2019 20:02
-
-
Save lepfsd/bddc47417df4ea682e71d974ff99c981 to your computer and use it in GitHub Desktop.
generate json response php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function json_response($message = null, $code = 200) | |
{ | |
// clear the old headers | |
header_remove(); | |
// set the actual code | |
http_response_code($code); | |
// set the header to make sure cache is forced | |
header("Cache-Control: no-transform,public,max-age=300,s-maxage=900"); | |
// treat this as json | |
header('Content-Type: application/json'); | |
$status = array( | |
200 => '200 OK', | |
400 => '400 Bad Request', | |
404 => '404 Not Found', | |
409 => 'CLIENT ERROR', | |
500 => '500 Internal Server Error' | |
); | |
// ok, validation error, or failure | |
header('Status: '.$status[$code]); | |
// return the encoded json | |
return json_encode(array( | |
'status' => $code, // success or not? | |
'message' => $message | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment