Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active March 7, 2024 06:02
Show Gist options
  • Save james2doyle/33794328675a6c88edd6 to your computer and use it in GitHub Desktop.
Save james2doyle/33794328675a6c88edd6 to your computer and use it in GitHub Desktop.
A simple JSON response function for PHP. Used in various PhileCMS plugins.
<?php
function json_response($code = 200, $message = null)
{
// 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',
422 => 'Unprocessable Entity',
500 => '500 Internal Server Error'
);
// ok, validation error, or failure
header('Status: '.$status[$code]);
// return the encoded json
return json_encode(array(
'status' => $code < 300, // success or not?
'message' => $message
));
}
// if you are doing ajax with application-json headers
if (empty($_POST)) {
$_POST = json_decode(file_get_contents("php://input"), true) ? : [];
}
// usage
echo json_response(200, 'working'); // {"status":true,"message":"working"}
// array usage
echo json_response(200, array(
'data' => array(1,2,3)
));
// {"status":true,"message":{"data":[1,2,3]}}
// usage with error
echo json_response(500, 'Server Error! Please Try Again!'); // {"status":false,"message":"Server Error! Please Try Again!"}
@Vanessa1906
Copy link

dfdf

@ogabrielguerra
Copy link

Thanks for sharing! Btw I think that @saurabhmdh is right. The parameters order were accidentally swapped.

@james2doyle
Copy link
Author

Updated the params. Can't believe they were swapped for so long... 🤕

@mathmul
Copy link

mathmul commented Oct 13, 2021

Only thing I added was ob_clean(); before header_remove();. Is it redundant?

@sherifnabil
Copy link

Dears for who gets 500 Server Error use exit after echo the json response
hope it helps

@mathmul
Copy link

mathmul commented Dec 13, 2021

Instead of

return json_encode([
    'status' => $code < 300,
    'message' => $message
]);

I prefer

die(json_encode([
    'status' => $code < 300,
    'message' => $message
]));

so there's no need for echo before calling json_response anymore, and the script is exited.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment