4

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) --> (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

SYNCRo
  • 450
  • 5
  • 21

2 Answers2

2
  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.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 2. $_GET will never transform my JS encoded string "don%27t_use_%23_and_%25_in_URL_params" into "don't_use_#_and_%_in_URL_params" what i expect to receive in $_GET["data"] – SYNCRo Feb 28 '11 at 10:07
  • Yes it will. PHP does The Right Thing for URL Encoded data when populating `$_GET`. – Quentin Feb 28 '11 at 11:50
1
  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?
Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345