search
HomeBackend DevelopmentPHP Tutorial编写不受魔术引号影响的php应用

阅读前提:你必须看过php手册上的"第IV部分安全"的"第10章魔术引号"。如果没看过,也没问题,现在马上花10分钟先看一下php手册上的这东西。

魔术引号(Magic Quote)是一个自动将进入 PHP 脚本的数据进行转义的过程

你可能想让你的程序兼容多个数据库,但你使用的不同的数据库可能使用不同的转义符,而我们的程序又有可能运行在不同的php.ini配置的主机上,关于magic_quotes的配置又可能不一样,所以编写不受魔术引号影响的php应用是高兼容性的php应用所必须的。

php.ini中有三个魔术引号配置选项:

  魔术引号配置选项   描述  运行时改变 在 PHP中的默认值为 
  magic_quotes_gpc 如果打开的话,影响到 HTTP 请求数据(GET,POST 和 COOKIE)。  不能  On
 magic_quotes_runtime 如果打开的话,大部份从外部来源取得数据并返回的函数,包括从数据库和文本文件,所返回的数据都会被反斜线转义。(前提是magic_quotes_gpc = On)  能  Off
 magic_quotes_sybase

当关闭时,所有的 '(单引号),"(双引号),/(反斜线)和 NULL 字符都会被自动加上一个反斜线进行转义。这和 addslashes() 作用完全相同。
    如果打开的话,将会使用单引号对单引号进行转义而非反斜线。此选项会完全覆盖 magic_quotes_gpc。如果同时打开两个选项的话,单引号将会被转义成 ''。而双引号、反斜线 和 NULL 字符将不会进行转义。 
(前提是magic_quotes_gpc = On)

 能  Off

 

    但是要处理外部传来的全局变量就比较麻烦了。

要 处理外部超级变量,我们要看magic_quotes_gpc是否已经打开(如果magic_quotes_gpc没打开,而 magic_quotes_sybase打开,magic_quotes_sybase也不起作用),还要看magic_quotes_sybase是否 打开,再看我们的程序需要对外部变量用addslashes转义方式还是使用magic_quotes_sybase式的转义方式。下面的代码是一个具体 的实现。

    有人可能说,当magic_quotes_gpc设成On,而magic_quotes_sybase设成Off,那么直接用 ini_set('magic_quotes_sybase', 1);就能让系统用'来对addslashes式的转义进行覆盖。这样是不行的。你用ini_get('magic_quotes_sybase')输出 看下配置,magic_quotes_sybase的确被改变了,但是你的代码就是不能用'转义符覆盖addslashes式的自动转义。这是因为系统获 取外部变量的时候,是在你的ini_set('magic_quotes_sybase', 1);之前完成的。

 

/**
 * 解决不受magic_quotes影响的php应用
 *
 * 使用这个处理办法需要配置是否使用magic_quotes_sybase, 以适应不同的DBMS
 *
 * 设置方法:
 * $useQuotesSybase[数据库名] = 1;
 * 如:使用sqlite,则定义并初始化 $useQuotesSybase['sqlite'] = 1;
 * 如果使用mysql,可以定义并初始化 $useQuotesSybase['sqlite'] = 0; 也可以不定义
 *
 * CONFIG_DB_DBMS 为所用的DBMS的常量, 在别处定义。比如 define('CONFIG_DB_DBMS', 'mysql');
 *
 * @author 流水孟春 cmpan(at)qq.com
 * @link http://lib.cublog.cn
 * $date 2007.11.18
 */
error_reporting(E_ALL);
set_magic_quotes_runtime(0);
define('CONFIG_DB_DBMS', 'sqlite'); // 测试用

// 使用 ' 做转义符的数据库
$useQuotesSybase = array();
$useQuotesSybase['sqlite'] = 1;
$useQuotesSybase['sybase'] = 1;

if(!empty($_POST)) $_POST = array_map('quotesOuterVars', $_POST);
if(!empty($_GET)) $_GET = array_map('quotesOuterVars', $_GET);
$_COOKIE = array_map('quotesOuterVars', $_COOKIE);
$_REQUEST = array_map('quotesOuterVars', $_REQUEST);

function quotesOuterVars($var) {
    if (is_array($var)) {
        return array_map('quotesOuterVars',$var);
    } else {
        if (get_magic_quotes_gpc()) {
            if (isset($GLOBALS['useQuotesSybase'][CONFIG_DB_DBMS]) && $GLOBALS['useQuotesSybase'][CONFIG_DB_DBMS]) {
                // 当前需要以 ' 为转义符
                // 如果 magic_quotes_sybase = Off, 系统将把外部变量 addslashes, 我们得先 stripslashes
                // 否则系统自动把 ' 换成 '',
                if (!ini_get('magic_quotes_sybase')) {
                    $var = stripslashes($var);
                    $var = str_replace("'", "''", $var);
                }
            } else {
                // 当前需要以 / 为转义符
                // 如果 magic_quotes_sybase = On, 我们先把 '' 替换成 ', 然后在 addslashes
                // 否则系统自动quotes
                if (ini_get('magic_quotes_sybase')) {
                    $var = str_replace("'", "''", $var);
                    $var = addslashes($var);
                }
            }
        } else{
            if (isset($GLOBALS['useQuotesSybase'][CONFIG_DB_DBMS]) && $GLOBALS['useQuotesSybase'][CONFIG_DB_DBMS]) {
                $var = str_replace("'", "''", $var);
            } else {
                $var = addslashes($var);
            }
        }

        return trim($var);
    }
}


    从上面的表我们可以看出,对于magic_quotes_runtime,我在程序中用 ini_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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.