开发者

best way to escape data JS->PHP->MySQL and vice versa

what functions i have to use to encode/decode/escape/stripslash data for following purposes?

  1. when calling a PHP script from JS like: page.php?data=don't_use_#_and_%_in_URL_params
  2. when a PHP script receive a parameter from JS like: don%27t_use_%23_and_%25_in_URL_params
  3. when running a MySQL query from PHP with data previously received from JS to prevent MySQL injections (lets say i need to insert in database the following sequence of characters: "``')
  4. when i need to compare in a MySQL statement a field value which contains "``' sequence with an expression
  5. when i need to retrieve a field value from a MySQL table and the field contains "``' and i want to use it in a PHP eval() macrosubstitution
  6. when i have to send data from PHP to JS in an AJAX response and it contains "``' characters
  7. and finally i have to eval() previous respond in JS

something like this diagram:

JS(encode) --开发者_C百科> (decode)PHP(encode) --> (decode?)MySQL(encode?) --> (decode)MySQL(encode) --> (decode)JS

if anyone have the time and pleasure to answer, or to correct me if i made any mistakes here, thanks in advance


  1. encodeURIComponent
  2. $_GET
  3. PDO bound parameters
  4. PDO bound parameters in a database. Otherwise it is just a string in PHP
  5. No idea. You really should have asked a Question for each question you have. eval smells bad though.
  6. Pick a data format and use appropriate encoding for that. JSON is common.
  7. The only time you should go near eval() is JS is when you are implementing a support for json in browsers without a native version (and you can use Crockford's json2.js for that). So don't.


  1. escape()
  2. No action required. 3-4. Data source doesn't matter here. there are common rules for building the query, I am sure you know it all already. If not - refer to this complete explanation.
  3. NEVER do it. It's a hole of a skyscraper size in your application. Don't you see it?
  4. json_encode()
  5. eval? are you sure? why not to send data only while all codes already present in JS?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜