-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-response.php
More file actions
36 lines (35 loc) · 972 Bytes
/
json-response.php
File metadata and controls
36 lines (35 loc) · 972 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?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 = [
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([
'status' => $code < 300, // success or not?
'message' => utf8ize($message),
]);
}
function utf8ize( $mixed ) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} elseif (is_string($mixed)) {
return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
}
return $mixed;
}