Jump to content

Why wont StripSlashes() work?


kmaid

Recommended Posts

Hi,

 

I am trying to sanatize single variables or arrays of variables from SQL injection and CSS. I have been working on this for a while and seem unable to get the StripSlashes function to work. Here is my code

 

function cleanInput($input) 
{
	$search = array(
		'@<script[^>]*?>.*?</script>@si',   // Strip out javascript
		'@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
		'@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
		'@<![\s\S]*?--[ \t\n\r]*>@');         // Strip multi-line comments
	return preg_replace($search, '', $input);
}

function libStripInputSlashes($Data)
{
    if (is_array($Data)) 
	{
        foreach($Data as $var=>$val) 
		{
            $output[$var] = libStripInputSlashes($val);
        }
    }
    else 
	{
        $Data = stripslashes($Data);
        $Data  = cleanInput($Data);
        $output = mysql_real_escape_string($Data);
    }
    return $output;
}

 

The problem is if i put "Test's" into the script the first time it runs the output is correct with "Test\'s" but each additional run on "Test\'s" adds more unrequired slashes. I have tried using pregreplace but it doesnt seem to like backslahses either. Any suggestions?

Link to comment
https://forums.phpfreaks.com/topic/141461-why-wont-stripslashes-work/
Share on other sites

The data is validated in a save function so each time the data is saved it updates the table with the additional slashes. This means if one of my user's added a ' into their first name every time they saved changes to their profile with ' or \ it would add more slashes as it would need to be re-validated.

 

I guess i could remove the slashes before i display the data but for that i would still need stripslashes  ::)

I read that having magic quotes on could actually be the issue. How is this normally worked around?

 

Its really lame but i may have found another solution though. In the comments of the PHP manual i found a function that will only add the backslashes once. Does mysql_real_escape_string do anything other than add back slashes to 's?

 

Here is the code anyways

 

function addslashes_once($input)
{
        //These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
        $pattern = array("\\'", "\\\"", "\\\\", "\\0");
        $replace = array("", "", "", "");
        if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $input)))
	{
            return addslashes($input);
        }
        else return $input;
    }

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.