Safe alternative to mysql_real_escape_string? (Php)

I pass the variable to the function executing the request

MySQL connection occurs only inside the function and closes inside the function

I want to be able to safely delete strings before sending their function

I cannot use mysql_real_escape_string because it requires a MySQL connection (which only runs inside the function)

I know that the simple answer would be to avoid the lines inside the function, but I cannot do this because I need to send some shielded and some unshielded parts of the string

For example, I need to run a function as follows:

myquery("'" . escape_me("My string") . "'");

Notice that I am sending two apostrophes - unescaped, with escaped string inside. For this reason, I cannot use the mysql_real_escape_string shell for arguments inside the myquery function.

I found the following code suggesting to use it as an alternative to mysql_real_escape_string:

// escape characters
function escape_me($value) {
    $return = '';
    for($i = 0; $i < strlen($value); ++$i) {
        $char = $value[$i];
        $ord = ord($char);
        if($char !== "'" && $char !== "\"" && $char !== '\\' && $ord >= 32 && $ord <= 126)
            $return .= $char;
        else
            $return .= '\\x' . dechex($ord);
    }
    return $return;
}

I donโ€™t know if this function is safe from multi-byte attacks, but I think I also need to cancel the function every time I request

For example, input: Testing 3 "OK" turns into Testing 3x27s x22OKx22 in the database

So my main question is: Do you know if there is another function that I can use as an alternative to mysql_real_escape_string that will safely avoid characters?

+3
source share
2 answers
  • , . .
  • , , myquery("SELECT * FROM table WHERE id = %s","My string");

  • , : . .

, .

function fetchAll(){
 $args = func_get_args();
 $query = array_shift($args);
 $stmt = $pdo->prepare($query);
 $stmt->execute($args);
 return $stmt->fetchAll();
}
$a=$db->fetchAll("SELECT * FROM users WHERE status=? LIMIT ?,?",$status,$start,$num);
  • utf-8, mysql_real_escape_string, mysql_escape_string ()
+5

, , sprintf() , . :

public function querya($query, $args=null){
    //check if args was passed in
    if($args !== null){
        //if an array...
        if(is_array($args)){
            //...escape each value in the args array
            foreach($args as $key=>$value){
                $args[$key] = mysql_real_escape_string($value);
            }
            //add the query to the beginning of the args array
            array_unshift($args, $query);
            //call sprintf with the array as arguments to sprintf
            $query = call_user_func_array("sprintf", $args);
        } else {
            //if args is not an array, then string (single argument passed in).
            $query = sprintf($query, mysql_real_escape_string($args));
        }
    }

    //perform query, other stuff
}
0

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


All Articles