简体   繁体   English

防止直接访问 php 包含文件

[英]Prevent direct access to a php include file

I have a php file which I will be using as exclusively as an include.我有一个 php 文件,我将把它用作包含文件。 Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included.因此,当通过输入 URL 而不是被包含来直接访问它时,我想抛出一个错误而不是执行它。

Basically I need to do a check as follows in the php file:基本上我需要在php文件中进行如下检查:

if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) die ("Direct access not premitted");

Is there an easy way to do this?有没有简单的方法来做到这一点?

Add this to the page that you want to only be included将此添加到您只想包含的页面

<?php
if(!defined('MyConst')) {
   die('Direct access not permitted');
}
?>

then on the pages that include it add然后在包含它的页面上添加

<?php
define('MyConst', TRUE);
?>

The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file.对于通用的“运行在您可能完全控制或可能不完全控制的 Apache 服务器上的 PHP 应用程序”情况,最简单的方法是将您的包含放在一个目录中,并在您的 .htaccess 文件中拒绝对该目录的访问。 To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:为了避免人们使用谷歌搜索的麻烦,如果您使用的是 Apache,请将其放在您不想访问的目录中名为“.htaccess”的文件中:

Deny from all

If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from.如果您实际上完全控制了服务器(这些天甚至对于小应用程序比我第一次写这个答案时更常见),最好的方法是将您想要保护的文件粘贴在您的 Web 服务器正在提供服务的目录之外. So if your app is in /srv/YourApp/ , set the server to serve files from /srv/YourApp/app/ and put the includes in /srv/YourApp/includes , so there literally isn't any URL that can access them.因此,如果您的应用程序位于/srv/YourApp/ ,请将服务器设置为提供来自/srv/YourApp/app/并将包含项放入/srv/YourApp/includes ,因此实际上没有任何可以访问它们的 URL .

I have a file that I need to act differently when it's included vs when it's accessed directly (mainly a print() vs return() ) Here's some modified code:我有一个文件,当它被包含与直接访问时(主要是print()return() ),我需要采取不同的行动,这是一些修改后的代码:

if(count(get_included_files()) ==1) exit("Direct access not permitted.");

The file being accessed is always an included file, hence the == 1.被访问的文件始终是包含文件,因此 == 1。

The best way to prevent direct access to files is to place them outside of the web-server document root (usually, one level above).防止直接访问文件的最佳方法是将它们放在 Web 服务器文档根目录之外(通常在上一级)。 You can still include them, but there is no possibility of someone accessing them through an http request.您仍然可以包含它们,但不可能有人通过 http 请求访问它们。

I usually go all the way, and place all of my PHP files outside of the document root aside from the bootstrap file - a lone index.php in the document root that starts routing the entire website/application.我通常会一路走下去,将所有 PHP 文件放在文档根目录之外,除了引导文件- 文档根目录中的一个单独的 index.php,它开始路由整个网站/应用程序。

1: Checking the count of included files 1:检查包含文件的数量

if( count(get_included_files()) == ((version_compare(PHP_VERSION, '5.0.0', '>='))?1:0) )
{
    exit('Restricted Access');
}

Logic: PHP exits if the minimum include count isn't met.逻辑:如果不满足最小包含计数,PHP 将退出。 Note that prior to PHP5, the base page is not considered an include.请注意,在 PHP5 之前,基页不被视为包含。


2: Defining and verifying a global constant 2:定义和验证一个全局常量

// In the base page (directly accessed):
define('_DEFVAR', 1);

// In the include files (where direct access isn't permitted):
defined('_DEFVAR') or exit('Restricted Access');

Logic: If the constant isn't defined, then the execution didn't start from the base page, and PHP would stop executing.逻辑:如果没有定义常量,那么执行不是从基页开始,PHP 将停止执行。

Note that for the sake of portability across upgrades and future changes, making this authentication method modular would significantly reduce the coding overhead as the changes won't need to be hard-coded to every single file.请注意,为了跨升级和未来更改的可移植性,使此身份验证方法模块化将显着减少编码开销,因为更改不需要硬编码到每个文件。

// Put the code in a separate file instead, say 'checkdefined.php':
defined('_DEFVAR') or exit('Restricted Access');

// Replace the same code in the include files with:
require_once('checkdefined.php');

This way additional code can be added to checkdefined.php for logging and analytical purposes, as well as for generating appropriate responses.通过这种方式,可以将附加代码添加到checkdefined.php以用于记录和分析目的,以及生成适当的响应。

Credit where credit is due: The brilliant idea of portability came from this answer .信用应得的地方:可移植性的绝妙想法来自这个答案


3: Remote address authorisation 3:远程地址授权

// Call the include from the base page(directly accessed):
$includeData = file_get_contents("http://127.0.0.1/component.php?auth=token");

// In the include files (where direct access isn't permitted):
$src = $_SERVER['REMOTE_ADDR']; // Get the source address
$auth = authoriseIP($src); // Authorisation algorithm
if( !$auth ) exit('Restricted Access');

The drawback with this method is isolated execution, unless a session-token provided with the internal request.这种方法的缺点是隔离执行,除非内部请求提供了会话令牌。 Verify via the loop-back address in case of a single server configuration, or an address white-list for a multi-server or load-balanced server infrastructure.在单服务器配置的情况下通过环回地址进行验证,或多服务器或负载平衡服务器基础设施的地址白名单进行验证。


4: Token authorisation 4:代币授权

Similar to the previous method, one can use GET or POST to pass an authorization token to the include file:与前一种方法类似,可以使用 GET 或 POST 将授权令牌传递给包含文件:

if($key!="serv97602"){header("Location: ".$dart);exit();}

A very messy method, but also perhaps the most secure and versatile at the same time, when used in the right way.一种非常凌乱的方法,但如果以正确的方式使用,同时可能也是最安全和最通用的方法。


5: Webserver specific configuration 5:Webserver特定配置

Most servers allow you to assign permissions for individual files or directories.大多数服务器允许您为单个文件或目录分配权限。 You could place all your includes in such restricted directories, and have the server configured to deny them.您可以将所有包含放在此类受限目录中,并将服务器配置为拒绝它们。

For example in APACHE, the configuration is stored in the .htaccess file.例如在 APACHE 中,配置存储在.htaccess文件中。 Tutorial here .教程在这里

Note however that server-specific configurations are not recommended by me because they are bad for portability across different web-servers.但是请注意,我不推荐特定于服务器的配置,因为它们不利于跨不同 Web 服务器的可移植性。 In cases like Content Management Systems where the deny-algorithm is complex or the list of denied directories is rather big, it might only make reconfiguration sessions rather gruesome.在拒绝算法复杂或被拒绝目录列表相当大的内容管理系统等情况下,它可能只会使重新配置会话变得相当可怕。 In the end it's best to handle this in code.最后最好在代码中处理这个问题。


6: Placing includes in a secure directory OUTSIDE the site root 6:放置在站点根目录之外的安全目录中

Least preferred because of access limitations in server environments, but a rather powerful method if you have access to the file-system.由于服务器环境中的访问限制,因此最不受欢迎,但如果您可以访问文件系统,则是一种相当强大的方法。

//Your secure dir path based on server file-system
$secure_dir=dirname($_SERVER['DOCUMENT_ROOT']).DIRECTORY_SEPARATOR."secure".DIRECTORY_SEPARATOR;
include($secure_dir."securepage.php");

Logic:逻辑:

  • The user cannot request any file outside the htdocs folder as the links would be outside the scope of the website's address system.用户不能请求htdocs文件夹之外的任何文件,因为链接将超出网站地址系统的范围。
  • The php server accesses the file-system natively, and hence can access files on a computer just like how a normal program with required privileges can. php 服务器本机访问文件系统,因此可以像具有所需权限的普通程序一样访问计算机上的文件。
  • By placing the include files in this directory, you can ensure that the php server gets to access them, while hotlinking is denied to the user.通过将包含文件放在此目录中,您可以确保 php 服务器可以访问它们,同时拒绝用户盗链。
  • Even if the webserver's filesystem access configuration wasn't done properly, this method would prevent those files from becoming public accidentally.即使网络服务器的文件系统访问配置没有正确完成,这种方法也可以防止这些文件意外公开。

Please excuse my unorthodox coding conventions.请原谅我非正统的编码约定。 Any feedback is appreciated.任何反馈表示赞赏。

An alternative (or complement) to Chuck's solution would be to deny access to files matching a specific pattern by putting something like this in your .htaccess file Chuck 解决方案的替代(或补充)是通过在 .htaccess 文件中放置类似的内容来拒绝访问匹配特定模式的文件

<FilesMatch "\.(inc)$">
    Order deny,allow
    Deny from all
</FilesMatch>

Actually my advice is to do all of these best practices.实际上,我的建议是执行所有这些最佳实践。

  • Put the documents outside the webroot OR in a directory denied access by the webserver AND将文档放在 webroot 之外或被网络服务器拒绝访问的目录中,并且
  • Use a define in your visible documents that the hidden documents check for:在隐藏文档检查的可见文档中使用定义:
      if (!defined(INCL_FILE_FOO)) {
          header('HTTP/1.0 403 Forbidden');
          exit;
      }

This way if the files become misplaced somehow (an errant ftp operation) they are still protected.这样,如果文件以某种方式错位(错误的 ftp 操作),它们仍然受到保护。

I had this problem once, solved with:我曾经遇到过这个问题,解决了:

if (strpos($_SERVER['REQUEST_URI'], basename(__FILE__)) !== false) ...

but the ideal solution is to place the file outside of the web-server document root, as mentioned in another anwser.但理想的解决方案是将文件放在 web 服务器文档根目录之外,如另一个 anwser 中所述。

I wanted to restrict access to the PHP file directly, but also be able to call it via jQuery $.ajax (XMLHttpRequest) .我想直接限制对PHP文件的访问,但也可以通过jQuery $.ajax (XMLHttpRequest)调用它。 Here is what worked for me.这对我有用。

if (empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] != "XMLHttpRequest") {
    if (realpath($_SERVER["SCRIPT_FILENAME"]) == __FILE__) { // direct access denied
        header("Location: /403");
        exit;
    }
}

You'd better build application with one entrance point, ie all files should be reached from index.php你最好用一个入口点构建应用程序,即所有文件都应该从 index.php 访问

Place this in index.php把它放在 index.php 中

define(A,true);

This check should run in each linked file (via require or include)此检查应在每个链接文件中运行(通过 require 或 include)

defined('A') or die(header('HTTP/1.0 403 Forbidden'));

My answer is somewhat different in approach but includes many of the answers provided here.我的答案在方法上有些不同,但包括此处提供的许多答案。 I would recommend a multipronged approach:我会推荐一种多管齐下的方法:

  1. .htaccess and Apache restrictions for sure .htaccess 和 Apache 限制肯定
  2. defined('_SOMECONSTANT') or die('Hackers! Be gone!');

HOWEVER the defined or die approach has a number of failings.然而defined or die方法有许多失败之处。 Firstly, it is a real pain in the assumptions to test and debug with.首先,测试和调试的假设是一个真正的痛苦。 Secondly, it involves horrifyingly, mind-numbingly boring refactoring if you change your mind.其次,如果你改变主意,它涉及可怕的、令人麻木的无聊重构。 "Find and replace!" “找到并替换!” you say.你说。 Yes, but how sure are you that it is written exactly the same everywhere, hmmm?是的,但你有多确定它在任何地方都写得完全一样,嗯? Now multiply that with thousands of files... oO现在乘以数千个文件...... oO

And then there's .htaccess.然后是.htaccess。 What happens if your code is distributed onto sites where the administrator is not so scrupulous?如果您的代码分发到管理员不那么谨慎的站点上,会发生什么? If you rely only on .htaccess to secure your files you're also going to need a) a backup, b) a box of tissues to dry your tears, c) a fire extinguisher to put out the flames in all the hatemail from people using your code.如果你只依靠 .htaccess 来保护你的文件,你还需要 a) 一个备份,b) 一盒纸巾擦干眼泪,c) 一个灭火器来扑灭人们所有仇恨邮件中的火焰使用您的代码。

So I know the question asks for the "easiest", but I think what this calls for is more "defensive coding".所以我知道这个问题要求“最简单”,但我认为这需要更多的“防御性编码”。

What I suggest is:我的建议是:

  1. Before any of your scripts require('ifyoulieyougonnadie.php');在你的任何脚本之前require('ifyoulieyougonnadie.php'); ( not include() and as a replacement for defined or die ) include()并作为defined or die的替代品)
  2. In ifyoulieyougonnadie.php , do some logic stuff - check for different constants, calling script, localhost testing and such - and then implement your die(), throw new Exception, 403 , etc.ifyoulieyougonnadie.php ,做一些逻辑的事情——检查不同的常量、调用脚本、本地主机测试等等——然后实现你的die(), throw new Exception, 403等。

    I am creating my own framework with two possible entry points - the main index.php (Joomla framework) and ajaxrouter.php (my framework) - so depending on the point of entry, I check for different things.我正在使用两个可能的入口点创建自己的框架——主 index.php(Joomla 框架)和 ajaxrouter.php(我的框架)——所以根据入口点,我检查不同的东西。 If the request to ifyoulieyougonnadie.php doesn't come from one of those two files, I know shenanigans are being undertaken!如果对ifyoulieyougonnadie.php的请求不是来自这两个文件之一,我知道正在进行ifyoulieyougonnadie.php

    But what if I add a new entry point?但是如果我添加一个新的入口点呢? No worries.不用担心。 I just change ifyoulieyougonnadie.php and I'm sorted, plus no 'find and replace'.我只是更改ifyoulieyougonnadie.php并且我已排序,并且没有“查找和替换”。 Hooray!万岁!

    What if I decided to move some of my scripts to do a different framework that doesn't have the same constants defined() ?如果我决定移动我的一些脚本来做一个不同的框架,它没有相同的常量defined()怎么办? ... Hooray! ……万岁! ^_^ ^_^

I found this strategy makes development a lot more fun and a lot less:我发现这个策略让开发变得更有趣,但更少:

/**
 * Hmmm... why is my netbeans debugger only showing a blank white page 
 * for this script (that is being tested outside the framework)?
 * Later... I just don't understand why my code is not working...
 * Much later... There are no error messages or anything! 
 * Why is it not working!?!
 * I HATE PHP!!!
 * 
 * Scroll back to the top of my 100s of lines of code...
 * U_U
 *
 * Sorry PHP. I didn't mean what I said. I was just upset.
 */

 // defined('_JEXEC') or die();

 class perfectlyWorkingCode {}

 perfectlyWorkingCode::nowDoingStuffBecauseIRememberedToCommentOutTheDie();

The easiest way is to set some variable in the file that calls include, such as最简单的方法是在调用include的文件中设置一些变量,比如

$including = true;

Then in the file that's being included, check for the variable然后在包含的文件中,检查变量

if (!$including) exit("direct access not permitted");
debug_backtrace() || die ("Direct access not permitted");

What Joomla!什么Joomla! does is defining a Constant in a root file and checking if the same is defined in the included files. do 是在根文件中定义一个常量并检查是否在包含的文件中定义了相同的常量。

defined('_JEXEC') or die('Restricted access');

or else否则

one can keep all files outside the reach of an http request by placing them outside the webroot directory as most frameworks like CodeIgniter recommend.可以通过将所有文件放置在 webroot 目录之外,如 CodeIgniter 等大多数框架推荐的那样,将所有文件置于 http 请求范围之外。

or even by placing an .htaccess file within the include folder and writing rules, you can prevent direct access.甚至通过在包含文件夹中放置一个 .htaccess 文件并编写规则,您可以阻止直接访问。

Besides the .htaccess way, I have seen a useful pattern in various frameworks, for example in ruby on rails.除了 .htaccess 方式,我在各种框架中看到了一个有用的模式,例如在 ruby​​ on rails 中。 They have a separate pub/ directory in the application root directory and the library directories are living in directories at the same level as pub/.它们在应用程序根目录中有一个单独的 pub/ 目录,并且库目录位于pub/相同级别的目录中。 Something like this (not ideal, but you get the idea):像这样的东西(不理想,但你明白了):

app/
 |
 +--pub/
 |
 +--lib/
 |
 +--conf/
 |
 +--models/
 |
 +--views/
 |
 +--controllers/

You set up your web server to use pub/ as document root.您将 Web 服务器设置为使用 pub/ 作为文档根目录。 This offers better protection to your scripts: while they can reach out from the document root to load necessary components it is impossible to access the components from the internet.这为您的脚本提供了更好的保护:虽然它们可以从文档根目录访问以加载必要的组件,但无法从 Internet 访问这些组件。 Another benefit besides security is that everything is in one place.除了安全性之外,另一个好处是一切都集中在一个地方。

This setup is better than just creating checks in every single included file because "access not permitted" message is a clue to attackers, and it is better than .htaccess configuration because it is not white-list based: if you screw up the file extensions it will not be visible in the lib/, conf/ etc. directories.这种设置比仅仅在每个包含的文件中创建检查要好,因为“不允许访问”消息是攻击者的线索,而且它比 .htaccess 配置更好,因为它不是基于白名单的:如果你搞砸了文件扩展名它在 lib/、conf/ 等目录中不可见。

If more precisely, you should use this condition:如果更准确地说,你应该使用这个条件:

if (array_search(__FILE__, get_included_files()) === 0) {
    echo 'direct access';
}
else {
    echo 'included';
}

get_included_files() returns indexed array containing names of all included files (if file is beign executed then it was included and its name is in the array). get_included_files()返回包含所有包含文件名称的索引数组(如果文件被正常执行,则它被包含并且其名称在数组中)。 So, when the file is directly accessed, its name is the first in the array, all other files in the array were included.所以,当直接访问文件时,它的名字是数组中的第一个,数组中的所有其他文件都被包含在内。

if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) { die('Access denied'); };
<?php       
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  if (false !== strpos($url,'.php')) {
      die ("Direct access not premitted");
  }
?>
<?php
if (eregi("YOUR_INCLUDED_PHP_FILE_NAME", $_SERVER['PHP_SELF'])) { 
 die("<h4>You don't have right permission to access this file directly.</h4>");
}
?>

place the code above in the top of your included php file.将上面的代码放在包含的 php 文件的顶部。

ex:例如:

<?php
if (eregi("some_functions.php", $_SERVER['PHP_SELF'])) {
    die("<h4>You don't have right permission to access this file directly.</h4>");
}

    // do something
?>

The following code is used in the Flatnux CMS ( http://flatnux.altervista.org ):以下代码用于 Flatnux CMS ( http://flatnux.altervista.org ):

if ( strpos(strtolower($_SERVER['SCRIPT_NAME']),strtolower(basename(__FILE__))) )
{
    header("Location: ../../index.php");
    die("...");
}

I found this php-only and invariable solution which works both with http and cli :我发现了这个仅适用于 php 和不变的解决方案,它适用于 http 和 cli :

Define a function :定义一个函数:

function forbidDirectAccess($file) {
    $self = getcwd()."/".trim($_SERVER["PHP_SELF"], "/");
    (substr_compare($file, $self, -strlen($self)) != 0) or die('Restricted access');
}

Call the function in the file you want to prevent direct access to :调用要防止直接访问的文件中的函数:

forbidDirectAccess(__FILE__);

Most of the solutions given above to this question do not work in Cli mode.上面针对这个问题给出的大多数解决方案在 Cli 模式下都不起作用。

Storing your include files outside the web accessible directory has been mentioned a few times, and is certainly a good strategy where possible.将包含文件存储在 Web 可访问目录之外已多次被提及,这在可能的情况下当然是一个好策略。 However, another option I have not yet seen mentioned: ensure that your include files don't contain any runnable code .但是,我还没有提到另一个选项:确保您的包含文件不包含任何可运行代码 If your include files merely define functions and classes, and have no code other than that, they will simply produce a blank page when accessed directly.如果您的包含文件仅定义了函数和类,而没有除此之外的其他代码,则直接访问它们时只会产生一个空白页。

By all means allow direct access to this file from the browser: it won't do anything .无论如何,允许从浏览器直接访问这个文件:它不会做任何事情 It defines some functions, but none of them are called, so none of them run.它定义了一些函数,但是它们都没有被调用,所以它们都没有运行。

<?php

function a() {
    // function body
}

function b() {
    // function body
}

The same applies to files which contain only PHP classes, and nothing else.这同样适用于仅包含 PHP 类而没有其他任何内容的文件。


It's still a good idea to keep your files outside of the web directory where possible.尽可能将您的文件保存在 Web 目录之外仍然是一个好主意。

  • You might accidentally deactivate PHP, in which case your server may send content of the PHP files to the browser, instead of running PHP and sending the result.您可能不小心停用了 PHP,在这种情况下,您的服务器可能会将 PHP 文件的内容发送到浏览器,而不是运行 PHP 并发送结果。 This could result in your code (including database passwords, API keys, etc.) leaking.这可能会导致您的代码(包括数据库密码、API 密钥等)泄漏。
  • Files in the web directory are squatting on URLs you may want to use for your app. Web 目录中的文件占用了您可能希望用于您的应用程序的 URL。 I work with a CMS which cannot have a page called system , because that would conflict with a path used for code.我使用的 CMS 不能有一个名为system的页面,因为这会与用于代码的路径冲突。 I find this annoying.我觉得这很烦人。

i suggest that don't use of $_SERVER for security reasons .出于安全原因,我建议不要使用$_SERVER
You can use a variable like $root=true;您可以使用像$root=true;这样的变量$root=true; in first file that included another one.在包含另一个文件的第一个文件中。
and use isset($root) in begin of second file that be included.并在包含的第二个文件的开头使用isset($root)

What you can also do is password protect the directory and keep all your php scripts in there, ofcourse except the index.php file, as at the time of include password won't be required as it will be required only for http access.您还可以做的是密码保护目录并将所有 php 脚本保存在那里,当然除了 index.php 文件,因为在包含密码时不需要密码,因为它仅用于 http 访问。 what it will do is also provide you the option to access your scripts in case you want it as you will have password to access that directory.它还可以为您提供访问脚本的选项,以防万一,因为您将拥有访问该目录的密码。 you will need to setup .htaccess file for the directory and a .htpasswd file to authenticate the user.您需要为该目录​​设置 .htaccess 文件和一个 .htpasswd 文件来验证用户。

well, you can also use any of the solutions provided above in case you feel you don't need to access those files normally because you can always access them through cPanel etc.好吧,您也可以使用上面提供的任何解决方案,以防您觉得不需要正常访问这些文件,因为您始终可以通过 cPanel 等访问它们。

Hope this helps希望这有帮助

The easiest way is to store your includes outside of the web directory.最简单的方法是将包含的内容存储在 Web 目录之外。 That way the server has access to them but no outside machine.这样服务器可以访问它们但不能访问外部机器。 The only down side is you need to be able to access this part of your server.唯一的缺点是您需要能够访问服务器的这一部分。 The upside is it requires no set up, configuration, or additional code/server stress.好处是它不需要设置、配置或额外的代码/服务器压力。

I didn't find the suggestions with .htaccess so good because it may block other content in that folder which you might want to allow user to access to, this is my solution:我没有发现 .htaccess 的建议那么好,因为它可能会阻止该文件夹中您可能希望允许用户访问的其他内容,这是我的解决方案:

$currentFileInfo = pathinfo(__FILE__);
$requestInfo = pathinfo($_SERVER['REQUEST_URI']);
if($currentFileInfo['basename'] == $requestInfo['basename']){
    // direct access to file
}
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

会顺利完成工作

Earlier mentioned solution with PHP version check added:添加了前面提到的带有 PHP 版本检查的解决方案:

    $max_includes = version_compare(PHP_VERSION, '5', '<') ? 0 : 1;
    if (count(get_included_files()) <= $max_includes)
    {
        exit('Direct access is not allowed.');
    }

Do something like:做类似的事情:

<?php
if ($_SERVER['SCRIPT_FILENAME'] == '<path to php include file>') {
    header('HTTP/1.0 403 Forbidden');
    exit('Forbidden');
}
?>

You can use phpMyAdmin Style: 您可以使用phpMyAdmin样式:

/**
 * block attempts to directly run this script
 */
if (getcwd() == dirname(__FILE__)) {
    die('Attack stopped');
}

this is what google uses in their php examples see here 这是谷歌在其PHP示例中使​​用的内容, 请参见此处

if (php_sapi_name() != 'cli') {
  throw new \Exception('This application must be run on the command line.');
}

You can use the following method below although, it does have a flaw, because it can be faked, except if you can add another line of code to make sure the request comes only from your server either by using Javascript.您可以使用下面的方法,但它确实有一个缺陷,因为它可以被伪造,除非您可以添加另一行代码以确保请求仅来自您的服务器或使用 Javascript。 You can place this code in the Body section of your HTML code, so the error shows there.您可以将此代码放在 HTML 代码的正文部分,以便在那里显示错误。

<?
if(!isset($_SERVER['HTTP_REQUEST'])) { include ('error_file.php'); }
else { ?>

Place your other HTML code here将您的其他 HTML 代码放在这里

<? } ?>

End it like this, so the output of the error will always show within the body section, if that's how you want it to be.像这样结束它,因此错误的输出将始终显示在正文部分中,如果您希望它是这样的话。

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

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