简体   繁体   English

防止在Web应用程序中直接访问PHP文件

[英]Prevent direct URL Access of PHP files in the Web Application

All of the php files in the application are directly accessible through URL. 应用程序中的所有php文件都可以通过URL直接访问。 Adding this code at the start of my php files works for few of them which are being requested with POST method: 在我的php文件的开头添加此代码适用于使用POST方法请求的少数代码:

if ( $_SERVER['REQUEST_METHOD']=='GET' && realpath(__FILE__) == realpath( $_SERVER['SCRIPT_FILENAME'] ) ) {

    die(header( 'location:/webapp/postings' ));
}

But, I do have some php files which are being requested through GET method and the above code doesn't work for them, because of which I came with the following code: 但是,我确实有一些通过GET方法请求的php文件,上面的代码对它们不起作用,因为我带有以下代码:

if(!isset($_SERVER['HTTP_REFERER'])){
die(header('location:/webapp/postings'));    
}

I know that the HTTP_REFERER coudn't be trusted. 我知道HTTP_REFERER不值得信任。 Any other options? 还有其他选择吗?

can someone please tell me a generic way of preventing direct URL access without altering the code across all the php files. 有人可以告诉我一种防止直接URL访问的通用方法,而不会改变所有php文件中的代码。

Note: My Application is running on IIS 7.5 Web server. 注意:我的应用程序正在IIS 7.5 Web服务器上运行。

Don't do this: 不要这样做:

public_html/
   includes/
       dont_access_me_bro.php
       ...
   index.php
   ...

Do this instead: 改为:

includes/
   dont_access_me_bro.php
   ...
public_html/
   index.php
   ...

Explanation 说明

Keeping your source files outside of the document root guarantees that users will be unable to access them directly by changing the URI on their HTTP request. 将源文件保留在文档根目录之外可以保证用户无法通过更改HTTP请求中的URI来直接访问它们。 This will not protect against LFI exploits. 不会防止LFI攻击。

To find out where your document root is, this handy PHP script can help: 要找出文档根目录的位置,这个方便的PHP脚本可以帮助:

var_dump($_SERVER['DOCUMENT_ROOT']);

If this prints out string (25) "C:\\htdocs\\www\\example.com" , you don't want to store your files in C:\\htdocs\\www\\example.com or any subdirectory of C:\\htdocs\\www\\example.com . 如果打印出string (25) "C:\\htdocs\\www\\example.com" ,则不希望将文件存储在C:\\htdocs\\www\\example.comC:\\htdocs\\www\\example.com任何子目录中C:\\htdocs\\www\\example.com

If you place user-provided files inside your document root, you're creating the risk that someone will access them directly from their browser, and if Apache/nginx/etc. 如果您将用户提供的文件放在文档根目录中,则会产生直接从浏览器访问它们的风险,以及Apache / nginx /等。 screws something up, their uploaded file may be executed as code. 搞砸了,他们上传的文件可以作为代码执行。

So you would not want your files to be inside C:\\htdocs\\www\\example.com\\uploaded , you would want something like C:\\uploads\\example.com\\ . 所以你希望你的文件在C:\\htdocs\\www\\example.com\\uploaded ,你会想要像C:\\uploads\\example.com\\

This is covered in-depth in this article on secure file uploads in PHP . 本文将详细介绍PHP中的安全文件上载

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM