phpmysqlmysql-real-escape-string

mysql_real_escape_string() for entire $_REQUEST array, or need to loop through it?


Is there an easier way of safely extracting submitted variables other than the following?

if(isset($_REQUEST['kkld'])) $kkld=mysql_real_escape_string($_REQUEST['kkld']);
if(isset($_REQUEST['info'])) $info=mysql_real_escape_string($_REQUEST['info']);
if(isset($_REQUEST['freq'])) $freq=mysql_real_escape_string($_REQUEST['freq']);

(And: would you use isset() in this context?)


Solution

  • To escape all variables in one go:

    $escapedGet = array_map('mysql_real_escape_string', $_GET);
    

    To extract all variables into the current namespace (i.e. $foo = $_GET['foo']):

    extract($escapedGet);
    

    Please do not do this last step though. There's no need to, just leave the values in an array. Extracting variables can lead to name clashes and overwriting of existing variables, which is not only a hassle and a source of bugs but also a security risk. Also, as @BoltClock says, stick to $_GET or $_POST. Also2, as @zerkms points out, there's no point in mysql_real_escaping variables that are not supposed to be used in a database query, it may even lead to further problems.


    Note that really none of this is a particularly good idea at all, you're just reincarnating magic_quotes and global_vars, which were horrible PHP practices from ages past. Use prepared statements with bound parameters via mysqli or PDO and use values through $_GET or filter_input. See http://www.phptherightway.com.