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

What functions should I use to encode / decode / escape / stripslash data for the following purposes?

  • when calling a PHP script from JS like: page.php?data=don't_use_#_and_%_in_URL_params
  • when a PHP script receives a parameter from JS like: don%27t_use_%23_and_%25_in_URL_params
  • when starting a MySQL query from PHP with data previously received from JS to prevent MySQL injections (let's say I need to insert the following sequence of characters into the database: "``' )
  • when I need to compare the value of the field containing the sequence "``' with the expression in the MySQL statement
  • when I need to get the value of a field from a MySQL table and the field contains a "``' and I want to use it in a PHP macro cable eval ()
  • when I need to send data from PHP to JS in AJAX response and contain "``' characters
  • and finally i need eval () the previous answer in JS

something like this diagram:

JS (encode) β†’ (decoding) PHP (encoding) β†’ (decoding?) MySQL (encoding?) β†’ (decoding) MySQL (encoding) β†’ (decoding) JS

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

+4
source share
2 answers
  • encodeURIComponent
  • $_GET
  • PDO Binding Options
  • PDO binding options in the database. Otherwise, it's just a string in PHP
  • I do not know. You really should have asked a Question for each question that interests you. eval smells bad.
  • Select a data format and use the appropriate encoding for this. JSON is generic.
  • The only time you stand next to eval() is JS when you implement json support in browsers without a native version (and you can use Crockford json2.js for this). So do not do this.
+2
source
  • the escape()
  • No action required. 3-4. The data source does not matter here. There are general rules for constructing a query, I'm sure that you already know all this. If not, refer to this full explanation .
  • NEVER do this. This is a hole the size of a skyscraper in your application. Can't you see?
  • json_encode ()
  • Eval? Are you sure? why not send data only when all codes are already present in JS?
+1
source

Source: https://habr.com/ru/post/1341619/


All Articles