分类:
2010-02-05 11:11:42
Magic Quotes is a process that automagically escapes incoming data to the PHP script. Its preferred to code with magic quotes off and to instead escape the data at runtime, as needed.
When on, all (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.
There are three magic quote directives: ;
Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP.
If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP.
If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULLs will remain untouched and unescaped.
Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.
Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient.
Although php.ini-dist enables these directives by default, php.ini-recommended disables it. This recommendation is mainly due to performance reasons.
Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of within the email. To fix, this may require excessive use of stripslashes().
1.
条件: magic_quotes_gpc=off
写入数据库的字符串未经过任何过滤处理。从数据库读出的字符串也未作任何处理。
数据:  $data="snow''''sun" ; (snow和sun之间是四个连续的单引号).
操作: 将字符串:"snow''''sun" 写入数据库,
结果: 出现sql语句错误,mysql不能顺利完成sql语句,写入数据库失败。
数据库保存格式:无数据。
输出数据格式:无数据。
说明: 对于未经处理的单引号在写入数据库时会使sql语句发生错误。
2.
条件: magic_quotes_gpc=off
写入数据库的字符串经过函数addlashes()处理。从数据库读出的字符串未作任何处理。
数据:  $data="snow''''sun" ; (snow和sun之间是四个连续的单引号).
操作: 将字符串:"snow''''sun" 写入数据库,
结果: sql语句顺利执行,数据成功写入数据库
数据库保存格式:snow''''sun (和输入一样)
输出数据格式:snow''''sun (和输入一样)
说明: addslashes()函数将单引号转换为'的转义字符使sql语句成功执行,
但\'并未作为数据存入数据库,数据库保存的是snow'''sun 而并不是我们想象的snowsun
3.
条件: magic_quotes_gpc=on
写入数据库的字符串未经过任何处理。从数据库读出的字符串未作任何处理。
数据:  $data="snow''''sun" ; (snow和sun之间是四个连续的单引号).
操作: 将字符串:"snow''''sun" 写入数据库,
结果: sql语句顺利执行,数据成功写入数据库
数据库保存格式:snow''''sun (和输入一样)
输出数据格式:snow''''sun (和输入一样)
说明: magic_quotes_gpc=on 将单引号转换为'的转义字符使sql语句成功执行,
但\'并未作为数据入数据库,数据库保存的是snow'''sun而并不是我们想象的snowsun。
4.
条件: magic_quotes_gpc=on
写入数据库的字符串经过函数addlashes()处理。从数据库读出的字符串未作任何处理。
数据:  $data="snow''''sun" ; (snow和sun之间是四个连续的单引号).
操作: 将字符串:"snow''''sun" 写入数据库,
结果: sql语句顺利执行,数据成功写入数据库
数据库保存格式:snowsun (添加了转义字符)
输出数据格式:snowsun (添加了转义字符)
说明: magic_quotes_gpc=on 将单引号转换为的转义字符使sql语句成功执行,
addslashes又将即将写入数据库的单引号转换为,后者的转换被作为数据写入
数据库,数据库保存的是snowsun