📜 ⬆️ ⬇️

PHP's

I want to tell you about some techniques that I use during the development of sites. Perhaps they will be useful to you.

Placeholders in SQL queries


Surprisingly, in the PHP mysql extension, no placeholders are implemented, which in the SQL query template are in place of the raw data. The values ​​passed to the placeholders are automatically processed by mysql_real_escape_string (), which saves us from the dangers of SQL injection.
An example of using this mechanism:

$name = "O'Reilly";
mysql_exec("SELECT * FROM people WHERE name = ?", $name);


Without it, we would have such code:
')
$name = "O'Reilly";
$name = mysql_real_escape_string($name);
mysql_query("SELECT * FROM people WHERE name = '$name'");


The advantage of the first method on the face.
And now the code itself:

function mysql_exec($sql) {

$args = func_get_args();
$args = array_map("mysql_real_escape_string", $args); // mysql_real_escape_string
$sql = str_replace("?", "'%s'", $sql); // sprintf
$args[0] = $sql;
$sql = call_user_func_array("sprintf", $args);
return mysql_query($sql);

}


unregister_globals


It happens that register_globals is enabled, and it is impossible to change, in this case, you can resort to tricks:

function unregister_globals() {

// , register_globals = off
if (!ini_get("register_globals")) {
return;
}

//
$allowed = array("GLOBALS", "_COOKIE", "_ENV", "_FILES", "_GET", "_POST", "_SERVER");
// ...
foreach ($GLOBALS as $name => $value) {
if (!in_array($name, $allowed)) {
unset($GLOBALS[$name]);
}
}

}


Call this function at the beginning of the script.

Fighting magic_quotes


The same applies to magic_quotes_gpc, if it is enabled then you can do the following:

function magic_quotes_gpc_off() {

if (!get_magic_quotes_gpc()) {
return;
}
function array_stripslashes($array) {
return is_array($array) ? array_map("array_stripslashes", $array) : stripslashes($array);
}
$_GET = array_stripslashes($_GET);
$_POST = array_stripslashes($_POST);
$_COOKIE = array_stripslashes($_COOKIE);

}


I hope this information has been useful to anyone.

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


All Articles