search
HomeBackend DevelopmentPHP Tutorial用PHP4.2书写安全的脚本_PHP


在很长一段时间内,PHP作为服务器端脚本语言的最大卖点之一就是会为从表单提交的值自动建立一个全局变量。在PHP 4.1中,PHP的制作者们推荐了一个访问提交数据的替代手段。在PHP 4.2中,他们取消了那种老的做法!正如我将在这篇文章中解释的那样,作出这样的变化的目的是出于安全性的考虑。我们将研究PHP在处理表单提交及其它数据时的新的做法,并说明为什么这样做会提高代码的安全性。 

这里有什么错误? 

看看下面的这段PHP脚本,它用来在输入的用户名及口令正确时授权访问一个Web页面: 
// 检查用户名及口令 
if ($username == 'kevin' and $password == 'secret') 
$authorized = true; 
?> 

Please enter your username and password:

Username: 

Password: 

OK,我相信大约半数的读者会不屑的说“太愚蠢了-- 我不会犯这样的错误的!”但是我保证有很多的读者会想“嗨,没什么问题啊,我也会这么写的!”当然还会有少数人会对这个问题感到困惑(“什么是PHP?”)。PHP被设计为一个“好的而且容易的”脚本语言,初学者可以在很短的时间内学会使用它;它也应该能够避免初学者犯上面的错误。 
再回到刚才的问题,上面的代码中存在的问题是你可以很容易地获得访问的权力,而不需要提供正确的用户名和口令。只在要你的浏览器的地址栏的最后添加?authorized=1。因为PHP会自动地为每一个提交的值创建一个变量 -- 不论是来自动一个提交的表单、URL查询字符串还是一个cookie -- 这会将$authorized设置为1,这样一个未授权的用户也可以突破安全限制。 
那么,怎么简单地解决这个问题呢?只要在程序的开头将$authorized默认设置为false。这个问题就不存在了!$authorized是一个完全在程序代码中创建的变量;但是为什么开发者得为每一个恶意的用户提交的变量担心呢? 

PHP 4.2作了什么改变? 

在PHP 4.2中,新安装的PHP中的register_globals选项默认为关闭,因此EGPCS值(EGPCS是Environment、Get、Post、Cookies、Server的缩写 -- 这是PHP中外部变量来源的全部范围)不会被作为全局变量来创建。当然,这个选项还可以通过手工来开启,但是PHP的开发者推荐你将其关闭。要贯彻他们的意图,你需要使用其它的方法来获取这些值。 
从PHP 4.1开始,EGPCS值就可以从一组指定的数组中获得: 
$_ENV -- 包含系统环境变量 
$_GET -- 包含查询字符串中的变量,以及提交方法为GET的表单中的变量 
$_POST -- 包含提交方式为POST的表单中的变量 
$_COOKIE -- 包含所有cookie变量 
$_SERVER -- 包含服务器变量,例如HTTP_USER_AGENT 
$_REQUEST -- 包含$_GET、$_POST和$_COOKIE的全部内容 
$_SESSION -- 包含所有已注册的session变量 
在PHP 4.1之前,当开发者关闭register_globals选项(这也被考虑为提高PHP性能的一种方法)后,必须使用诸如$HTTP_GET_VARS这样的令人讨厌的名字来获取这些变量。这些新的变量名不仅仅短,而且它们还有其他优点。 
首先,让我们在PHP 4.2中(也就是说关闭register_globals 选项)重写上面提到的代码: 
$username = $_REQUEST['username']; 
$password = $_REQUEST['password']; 

// 检查用户名和口令 
if ($username == 'kevin' and $password == 'secret') 
$authorized = true; 
?> 

Please enter your username and password:

Username: 

Password: 

正如你看到的,我所需要做的只是在代码的开始增加下面两行: 
$username = $_REQUEST['username']; 
$password = $_REQUEST['password']; 
因为我们希望用户名和密码是由用户提交的,所以我们从$_REQUEST数组中获取这些值。使用这个数组使得用户可以自由选择传递方式:通过URL查询字符串(例如允许用户创建书签时自动输入他们的证书)、通过一个提交的表单或者是通过一个cookie。如果你想要限制只能通过表单提交证书(更精确地说,是通过HTTP POST请求),你可以使用$_POST数组: 
$username = $_POST['username']; 
$password = $_POST['password']; 
除了“引入”这两个变量以外,程序代码没有任何改变。简单地关闭register_globals选项促使开发者更进一步了解哪些数据是来自外部的(不可信任的)资源。 
请注意这里还有一个小问题:PHP中默认的error_reporting设置仍然是E_ALL & ~E_NOTICE,因此如果“username”和“password”这两个值没有被提交,试图从$_REQUEST数组或$_POST数组中获得这两个值并不会招致任何错误信息。如晨不你的PHP程序需要严格的错误检查,你还需要增加一些代码以首先检查这些变量。 

但是这是不是意味着更多的输入? 

是的,在象上面这样的简单程序中,使用PHP 4.2常常会增加输入量。但是,还是看看光明的一面吧 -- 你的程序终究是更安全了! 
不过认真的说,PHP的设计者并没有完全忽视你的痛苦。在这些新数组中有一个特殊的其它所PHP变量都不具备的特征,它们是完全的全局变量。这对你有什么帮助呢?让我们先对我们的示例进行一下扩充。 
为了使得站点中的多个页面可以使用用户名/口令论证,我们将我们用户认证程序写到一个include文件(protectme.php)中: 
function authorize_user($authuser, $authpass) 

$username = $_POST['username']; 
$password = $_POST['password']; 
// 检查用户名和口令 
if ($username != $authuser or $password != $authpass): 
?> 

Please enter your username and password:

Username: 

Password: 

exit(); 
endif; 

?> 
现在,我们刚才的页面看上去将是这样的: 
require('protectme.php'); 
authorize_user('kevin','secret'); 
?> 

很简单,很清晰明了,对不对?现在是考验你的眼力和经验的时候了 -- 在authorize_user 函数中少了什么? 
在函数中没有申明$_POST是一个全局变量!在php 4.0中,当register_globals开启时,你需要增加一行代码以在函数中获取$username和$password变量: 
function authorize_user($authuser, $authpass) 

global $username, $password; 
... 
在PHP中,和其它具有类似语法的语言不同,函数外的变量在函数中不能自动获得,你需要象上面所说明的那样增加一行以指定其来自global范围。 
在PHP 4.0中,当关闭register_globals以提供安全性时,你可以使用$HTTP_POST_VARS数组以获得你的表单提交的值,但是你还是需要从全局范围导入这个数组: 
function authorize_user($authuser, $authpass) 

global $HTTP_POST_VARS; 
$username = $HTTP_POST_VARS['username']; 
$password = $HTTP_POST_VARS['password']; 
但是在PHP 4.1及以后的版本中,特殊的$_POST变量(以及上面提到的其它变量)可以在所有范围内使用。这就是不需要在函数中申明$_POST变量是一个全局变量的原因: 
function authorize_user($authuser, $authpass) 

$username = $_POST['username']; 
$password = $_POST['password']; 

这对session有什么影响? 

特殊的$_SESSION数组的引入实际上有助于简化session代码。你不需要将session变量申明为全局变量,然后再去留意哪些变量被注册了,你现在可以简单地从$_SESSION['varname']中引用你所有的session变量。 
现在让我们来看看另一个用户认证的例子。这一次,我们使用sessions以标志一个在你的网站继续逗留的用户已经经过了用户认证。首先,我们来看看PHP 4.0版本(开启register_globals): 
session_start(); 
if ($username == 'kevin' and $password == 'secret') 

$authorized = true; 
session_register('authorized'); 

?> 

和刚开始的程序一样,这个程序也存在安全漏洞,在URL的最后加上?authorized=1可以绕过安全措施直接访问页面内容。开发者可以将$authorized视为一个session变量而忽视了可以很容易地通过用户输入设置同样的变量。 
当我们增加了我们的特殊的数组(PHP 4.1)并关闭register_globals(PHP 4.2)后,我们的程序将是这样的: 
session_start(); 
if ($username == 'kevin' and $password == 'secret') 
$_SESSION['authorized'] = true; 
?> 

是不是更加简单了?你不再需要再将普通的变量注册为一个session变量,你只需要直接设置session变量(在$_SESSION数组中),然后用同样的方法使用它。程序变得更短了,而且对于什么变量是session变量也不会引起混乱! 

总结 

在这篇文章中,我解释了PHP脚本语言作出改变的深层原因。在PHP 4.1中,添加了一组特殊数据以访问外部数据。这些数组可以在任何范围内调用,这使得外部数据的访问更方便。在PHP 4.2中,register_globals被默认关闭以鼓励使用这些数组以避免无经验的开发者编写出不安全的PHP代码。 
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

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),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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.

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software