PHP adds backslashes before quotes of PHP removes backslashes

  • 2020-09-16 07:24:04
  • OfStack

The default PHP instruction magic_quotes_gpc is on, which is open. You can then use the stripslashes() function to remove the automatically added backslashes. For example, if the variable containing the string is $str, then use the stripslashes() function to handle the string: stripslashes($str). The output is backslashes removed.

If the output contains backslashes, you can use the stripslashes() function to handle the output content under 1, that is, $str=stripslashes($str), save to remove the backslash contained in the output content.

There is another problem, however, because the local PHP instruction magic_quotes_gpc is for off, this will remove the normal backslash. That's not what we want.

The solution is to use the function get_magic_quotes_gpc() for detection, removing the backslash if it is open and not if it is closed.

The program code is as follows:


 $str=$_POST["str"];           // read str Is assigned to $str variable  
 if(get_magic_quotes_gpc()){   // if get_magic_quotes_gpc() Is turned on  
     $str=stripslashes($str);  // Manipulate the string  
 } 

This article was amended at 10:08:03 on 25 April 2012 as follows:

Here are three ways to solve this problem:

1. Modify PHP configuration file ES42en.ini

This approach works only if you have authority to manage the server, and if you are using virtual space, you can only use the latter two methods.

In the PHP configuration file php.ini, set magic_quotes_gpc, magic_quotes_runtime, magic_quotes_sybase to off. As shown below:


magic_quotes_gpc = Off 
magic_quotes_runtime = Off 
magic_quotes_sybase = Off 

2 Use the.htaccess file

This method only works if the server supports htaccess, which is generally supported by current server 1

Add the following sentence to the.htaccess file in the program directory:

php_flag magic_quotes_gpc Off

Masking in code

This approach is the most portable and can be used regardless of server configuration, as long as PHP is supported.

Add the following code at the beginning of all PHP files


 if(get_magic_quotes_gpc()){ 
     function stripslashes_deep($value){ 
         $value=is_array($value)?array_map('stripslashes_deep',$value):stripslashes($value); 
         return $value; 
     } 
     $_POST=array_map('stripslashes_deep',$_POST); 
     $_GET=array_map('stripslashes_deep',$_GET); 
     $_COOKIE=array_map('stripslashes_deep',$_COOKIE); 
     $_REQUEST=array_map('stripslashes_deep',$_REQUEST); 
 } 


Related articles: