Last active
May 13, 2021 08:30
-
-
Save hax/75706bac6d89dfeb7195 to your computer and use it in GitHub Desktop.
PHP safe json encode
This file contains hidden or 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
<?php | |
function safe_json_encode($data) { | |
// We might have been tolerant to some common cases such as convert | |
// INF/NAN as 0 by using JSON_PARTIAL_OUTPUT_ON_ERROR option, but | |
// sadly `json_last_error()` only get the last error means it may | |
// override worse errors such as malfored utf-8 which we can't ignore! | |
// Poor H P !! | |
$result = @json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); | |
$err = json_last_error(); | |
// strictly no error | |
if ($err === JSON_ERROR_NONE && $result) { | |
// Escape </script> to prevent XSS | |
// Note: Commonly `str_replace()` is not safe for corrupted string | |
// But in our case, `json_encode()` already ensure `$result` as a | |
// valid utf-8 string. | |
return str_replace('</script>', '<\/script>', $result); | |
} | |
error_log( | |
'json encode error: ' . json_last_error_msg() . | |
', trace: ' . print_r(debug_backtrace(), true) | |
); | |
// When error, PHP 5.5 may return `false`, which output nothing. | |
// PHP 5.4 (or PHP 5.5 with JSON_PARTIAL_OUTPUT_ON_ERROR option on) | |
// may return "{null: ...}" if the key is a malfored utf-8 string, | |
// which is not valid JSON string. | |
// Instead of such meaningless and harmful result which may cause | |
// JavaScript error or potential XSS, we return 'null' to denote the | |
// failure. | |
return 'null'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what is this method doing as a final result? its returning null in the end.
is it testing that $data is valid to convert in json or not