search
HomeBackend DevelopmentPHP Tutorial基于magic_quotes_gpc与magic_quotes_runtime的区别与使用介绍_PHP

当你的数据中有一些   \  ”  ‘
这样的字符要写入到数据库里面,又想不被过滤掉的时候,它就很有用,会在这些字符前自动加上\,如
中国\地大物博”哈哈”
中国\\地大物博\”哈哈\”
可以使用set_maginc_quotes_runtime(0)关闭掉,当然你也可以直接在php.ini中设置。
get_magic_quotes_runtime() 取得 PHP 环境变量 magic_quotes_runtime 的值。

magic_quotes_gpc 为 on,它主要是对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes()。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义。遇到这种情况时可以使用函数 get_magic_quotes_gpc() 进行检测。

两者不同

set_magic_quotes_runtime() 可以让程序员在代码中动态开启或关闭 magic_quotes_runtime,
set_magic_quotes_runtime(1) 表示开启,set_magic_quotes_runtime(0) 则表示关闭。当set_magic_quotes_runtime(1) 时,从数据库或通过fread之类的函数读取的文本,将自动对' “和\自动加上反斜杠\进行转义,防止溢出。这在对数据库的数据进行转移的时候非常有用。但在一般情况下,应当将其关闭,否则从数据库读取出来的数据单引号、双引号和反斜杠都会被加上\,导致显示不正常。像Discuz,PHPWind都在公共文件的头部加上一句 set_magic_quotes_runtime(0); 强制关闭 magic_quotes_runtime 。

magic_quotes_gpc

作用范围是:WEB客户服务端;
作用时间:请求开始是,例如当脚本运行时.

magic_quotes_runtime

作用范围:从文件中读取的数据或执行exec()的结果或是从SQL查询中得到的;
作用时间:每次当脚本访问运行状态中产生的数据.

所以

magic_quotes_gpc的设定值将会影响通过Get/Post/Cookies获得的数据,
magic_quotes_runtime的设定值将会影响从文件中读取的数据或从数据库查询得到的数据,
magic_quotes_gpc 是对通过GET、POST、COOKIE传递的数据进行转义,一般在数据入库前要先进行转义,
magic_quotes_gpc不能在代码中动态开启或关闭,需要到php.ini将magic_quotes_gpc设置为on或off,
代码中可以用get_magic_quotes_gpc获取magic_quotes_gpc的状态。
当magic_quotes_gpc为off时,需要手工对数据进行addslashes,代码如下:
复制代码 代码如下:
if (!get_magic_quotes_gpc()) { 
     new_addslashes($_GET); 
     new_addslashes($_POST); 
     new_addslashes($_COOKIE); 
 } 

 function new_addslashes($string) { 
     if (is_array($string)) { 
         foreach ($string as $key => $value) { 
             $string[$key] = new_addslashes($value); 
         } 
     } else { 
         $string = addslashes($string); 
     } 
     return $string; 
 }

另一示例:
复制代码 代码如下:
$data1 = $_POST['aaa']; 
 $data2 = implode(file('1.txt')); 

 if (get_magic_quotes_gpc()) { 
     //把数据$data1直接写入数据库 
 } else { 
     $data1 = addslashes($data1); 
     //把数据$data1写入数据库 
 } 

 if (get_magic_quotes_runtime()){ 
     //把数据$data2直接写入数据库 
     //从数据库读出的数据要经过一次stripslashes()之后输出 
 } else { 
     $data2 = addslashes($data2); 
     //把数据$data2写入数据库 
     //从数据库读出的数据直接输出 
 }

++++++++++++++++++++++++++++++++++++++++++++++++++++++

经验总结:

一、对于GPC,不管系统有没有开启magic_quotes_gpc(即php.ini中magic_quotes_gpc = On),我们统一开启 magic_quotes_gpc,对get、post、cookie的内容进行转义。操作如下:
(摘自uchome系统)
复制代码 代码如下:
function saddslashes($string) { 
     if (is_array($string)) { 
         foreach ($string as $key => $val) { 
             $string[$key] = saddslashes($val); 
         } 
     } else { 
         $string = addslashes($string); 
     } 
     return $string; 
 } 

 //GPC过滤 
 $magic_quote = get_magic_quotes_gpc(); 
 if(empty($magic_quote)) { 
     $_GET = saddslashes($_GET); 
     $_POST = saddslashes($_POST); 
 } 

 //COOKIE,给cookie值转义 
 $prelength = strlen($_SC['cookiepre']); 
 foreach ($_COOKIE as $key => $val) { 
     if(substr($key, 0, $prelength) == $_SC['cookiepre']) { 
         $_SCOOKIE[(substr($key, $prelength))] = empty($magic_quote) ? saddslashes($val) : $val; 
     } 
 }

二、对于magic_quotes_runtime,我们统一关闭它,即set_magic_quotes_runtime(0);不让从数据库读取出来的数据的单引号、双引号和反斜杠都自动被加上\。这样,对数据库的操作如下:添加数据到数据库之前,我们手动对数据进行addslashes(),而从数据库取出数据时,则作相反操作,即stripslashes()。

三、对于要序列化的内容,要保持裸数据,即要去掉转义,stripslashes(),然后在把序列化过的内容保存到数据库当中(注意,序列化过的内容是不带单引号(')、双引号(”)、反斜线(\)的),示例如下:
$feedarr['body_data'] = serialize(stripslashes($body_data));

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

出现Function set_magic_quotes_runtime() is deprecated 问题?

在安装PHPCMS出现Deprecated: Function set_magic_quotes_runtime() is deprecated 错误,查了一下网络及资料发现是PHP5.3和PHP6.0之后移除了set_magic_quotes_runtime()函数。
我可以使用如下方案替代:

view sourceprint?
 @set_magic_quotes_runtime(0);

view sourceprint?
 ini_set("magic_quotes_runtime", 0);

view sourceprint?
 if (phpversion()      set_magic_quotes_runtime(0); 
 }

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),