Jump to content
MakeWebGames

PHP htmlspecialchars same as mysql_real_escape_string?


Recommended Posts

Posted

I am getting tired of getting rid of back slashes when I use mysql_real_escape_string

 

So I wanted to ask, does htmlspecialchars still secure vars when going into mysql_queries? like

$_POST['something'] = mysql_real_escape_string($_POST['something']);

If I did the same thing but with htmlspecialchars instead of mysql_real_escape_string would it still secure it?

That way the html will already translate it into a quote and such.

Posted (edited)

Recently i wanted the same thing and found a class that takes care of all of this.

To use the class simply use

 

sanitizeOne($var, $type);

 

Examples:

sanitizeOne($_POST['string'], "plain");

 

sanitizeOne($_GET['numbers'], "int");

 

Here is the actual code with creators credit.

 

<?php
/*

   Sanitize class

   Copyright (C) 2007 CodeAssembly.com  



   This program is free software: you can redistribute it and/or modify

   it under the terms of the GNU General Public License as published by

   the Free Software Foundation, either version 3 of the License, or

   (at your option) any later version.



   This program is distributed in the hope that it will be useful,

   but WITHOUT ANY WARRANTY; without even the implied warranty of

   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

   GNU General Public License for more details.



   You should have received a copy of the GNU General Public License

   along with this program.  If not, see http://www.gnu.org/licenses/

*/

/**

* Sanitize only one variable .

* Returns the variable sanitized according to the desired type or true/false 

* for certain data types if the variable does not correspond to the given data type.

* 

* NOTE: True/False is returned only for telephone, pin, id_card data types

*

* @param mixed The variable itself

* @param string A string containing the desired variable type

* @return The sanitized variable or true/false

*/



function sanitizeOne($var, $type)

{       

       switch ( $type ) {

                       case 'int': // integer

                       $var = (int) $var;

                       break;



                       case 'str': // trim string

                       $var = trim ( $var );

                       break;



                       case 'nohtml': // trim string, no HTML allowed

                       $var = htmlentities ( trim ( $var ), ENT_QUOTES );

                       break;



                       case 'plain': // trim string, no HTML allowed, plain text

                       $var =  htmlentities ( trim ( $var ) , ENT_NOQUOTES )  ;

                       break;



                       case 'upper_word': // trim string, upper case words

                       $var = ucwords ( strtolower ( trim ( $var ) ) );

                       break;



                       case 'ucfirst': // trim string, upper case first word

                       $var = ucfirst ( strtolower ( trim ( $var ) ) );

                       break;



                       case 'lower': // trim string, lower case words

                       $var = strtolower ( trim ( $var ) );

                       break;



                       case 'urle': // trim string, url encoded

                       $var = urlencode ( trim ( $var ) );

                       break;



                       case 'trim_urle': // trim string, url decoded

                       $var = urldecode ( trim ( $var ) );

                       break;



                       case 'telephone': // True/False for a telephone number

                       $size = strlen ($var) ;

                       for ($x=0;$x<$size;$x++)

                       {

                               if ( ! ( ( ctype_digit($var[$x] ) || ($var[$x]=='+') || ($var[$x]=='*') || ($var[$x]=='p')) ) )

                               {

                                       return false;

                               }

                       }

                       return true;

                       break;



                       case 'pin': // True/False for a PIN

                       if ( (strlen($var) != 13) || (ctype_digit($var)!=true) )

                       {

                               return false;

                       }

                       return true;

                       break;



                       case 'id_card': // True/False for an ID CARD

                       if ( (ctype_alpha( substr( $var , 0 , 2) ) != true ) || (ctype_digit( substr( $var , 2 , 6) ) != true ) || ( strlen($var) != 8))

                       {

                               return false;

                       }

                       return true;

                       break;



                       case 'sql': // True/False if the given string is SQL injection safe

                       //  insert code here, I usually use ADODB -> qstr() but depending on your needs you can use mysql_real_escape();

                       return mysql_real_escape_string($var);

                       break;

               }       

       return $var;



}





/**

* Sanitize an array.

* 

* sanitize($_POST, array('id'=>'int', 'name' => 'str'));

* sanitize($customArray, array('id'=>'int', 'name' => 'str'));

*

* @param array $data

* @param array $whatToKeep

*/



function sanitize( &$data, $whatToKeep )

{

       $data = array_intersect_key( $data, $whatToKeep ); 



       foreach ($data as $key => $value)

       {

               $data[$key] = sanitizeOne( $data[$key] , $whatToKeep[$key] );

       }

}
?>

 

With this code you can also use some of the functions people seem to forget about, like ucwords.

Edited by runthis
Posted

No htmlspecialchars does not do the same thing as mysql_real_escape_string. htmlspecialchars encodes certain characters that are used in the html language and are vital to html parsing (<,>,",',etc...) to a read only state. It can help against mysql injection in some cases but not all.

mysql_real_escape_string will change the charset of the input to utf-8 (decoding any multi byte characters) then add slashes to certain characters and strings vital to mysql in addition to (",',\) also making them read only. mysql_real_escape_string is a function in the mysql extension and is built for sanitizing data going into the database and knows what sub strings/characters should/shouldn't be changed.

So when sanitizing a string I recommend using it in addition to anything else you may want to do to the string. This function also does not fully secure against mysql injection in some cases so be warned.

About you having to strip slahes everytime you do something with the string you did mres(mysql_real_escape_string) on...

You should not have to do this. Are you having to do this after you select the data from the database,or are you mresing the string then echoing/doing something else with it then inserting/updating into database.

If you are having to do it after selecting the info from the database then you or a function are doing something to the data.

Things you may be doing:

- Double mresing the string

- addslashes then mresing the string

- using one of those functions that in some case just screw up or w/o telling it to modify's the string

If you are mresing the string then trying to output it somewhere or further modify it. I recommend mres be the last thing you do on it before it goes into the database or use a separate variable one for whats going into the database and one for whats going to be outputted/further modified.

Posted

You may want to check if magic quotes are on.

Note: mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

From php.net in case anyone is wondering about bluegman's comment on it not securing everything.

Posted

I am a little confused, let me explain.

I always mysql_real_escape_string any post or get var when it is going into the database.

So say a user sends a message with this in it "'I'm"

With the ' it would add a back slash so I would need to strip all back slashes in the message reading part of the game.

 

This is getting old doing this on most pages, so would there be anything other then mysql_real_escape_string that could set it to html chars so that I do not need to get rid of the back slashes, something just as secure as mysql_real_escape_string or even more secure.

Posted (edited)

I will try in a moment, but mysql_real_escape_string always saves a \ in the post var while inserting in the db, like this.

 

$_POST['something'] = mysql_real_escape_string($_POST['something']);

mysql_query("INSERT INTO `something` VALUES ('', ''.$_POST['something'].'')");

Edited by Blade Maker
Posted

Okay I think I get it now, if the code you provided is 1, then it is on, which in this case it will always add a back slash to the posts and gets with quotes and such in?

Then what does mysql_real_escape_string do exactly?

If mysqL_real_escape_string does not protect against % and _ how would I protect against those? If I protected against those as well, will I be fully secure against sql injections?

Posted

To protect against wild cards you could use:

$_POST['var']=addcslashes(mysql_real_escape_string($_POST['var']),'%_');

 

htmlspecialchars does not do as good of a job as mres. htmlspecialchars is meant for encoding html. mres is made for escaping possibly malicious characters.

Posted
Okay, so now I learned how to do all of this, should I be secured against all sql injections as long as I secure them with mysql_real_escape_string and securing wild cards as well?

Not as long as you have magic quotes on. ;)

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...