星期一, 12月 14, 2015

加強json_encode的xss 防禦

由於常把資料從db拉出來,再整個json_encode丟給前端
因此要一個個filter還挺累的
如果可以直接對encode過的string filter最好了~

幸好json_encode有好用的參數
完整參數如下
json_encode($value, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);
PHP官網有完整範例,以下截錄
$a = array('',"'bar'",'"baz"','&blong&', "\xc3\xa9");

echo "Normal: ",  json_encode($a), "\n";
echo "Tags: ",    json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n";
echo "Quot: ",    json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ",     json_encode($a, JSON_HEX_AMP), "\n";
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
echo "All: ",     json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";

Normal: ["","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["","'bar'","\"baz\"","&blong&","e"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","e"]
Reference
Example #2 A json_encode() example showing some options in use

沒有留言: