繁体   English   中英

防止直接 url 访问 php 文件

[英]prevent direct url access to php file

我的网站中有一个 php 文件,上面写着“check.php” ,它在提交表单时执行。

说我的网站是“myweb.com” ,php 文件在目录“PHP”中

我想阻止对“check.php”文件的直接 url 访问,即如果有人输入 url“ myweb.com/PHP/check.php ”,则不应执行 php 文件,而是应返回错误消息。

我试图通过在 .htaccess 中设置规则来阻止访问,但即使我尝试提交表单,它也会阻止 php。

.htaccess 规则:

RewriteEngine on 
RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/ 
(.*)\.php$ /index.html [L] 

有什么可能的方法吗?

你可以用PHP做到这一点

<?php
    /* at the top of 'check.php' */
    if ( $_SERVER['REQUEST_METHOD']=='GET' && realpath(__FILE__) == realpath( $_SERVER['SCRIPT_FILENAME'] ) ) {
        /* 
           Up to you which header to send, some prefer 404 even if 
           the files does exist for security
        */
        header( 'HTTP/1.0 403 Forbidden', TRUE, 403 );

        /* choose the appropriate page to redirect users */
        die( header( 'location: /error.php' ) );

    }
?>

将此代码放在check.php的顶部:

if(!isset($_SERVER['HTTP_REFERER'])){
    // redirect them to your desired location
    header('location:../index.php');
    exit;
}

如果用户通过直接键入URL来访问check.php,它会将它们重定向到您想要的位置。

在Root / .htaccess中尝试:

RewriteEngine on


RewriteCond %{REQUEST_METHOD} !^POST$
RewriteRule ^php/check.php$ - [NC,R=404,L]

如果不通过表单发布方法访问check.php,则将返回404。

我尝试了选择的答案,但我遇到了一些实现它的问题,特别是如果我想使用GET和Ajax从PHP文件中的函数返回值。

在对其他解决方案进行了大量研究之后(以及对我自己的一些测试),我想出了以下代码:

<?php
$currentPage = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

if ($_SERVER['REQUEST_METHOD'] == "GET" && strcmp(basename($currentPage), basename(__FILE__)) == 0)
{
    http_response_code(404);
    include('myCustom404.php'); // provide your own 404 error page
    die(); /* remove this if you want to execute the rest of
              the code inside the file before redirecting. */
}
?>

我发现上面的代码按照我想要的方式工作,我认为它不会像多个浏览器那样有任何问题,就像其他答案被指出的那样。 我也不认为它会有任何安全问题,但我可能是错的(请告诉我,如果我(以及为什么)),我对网络编程相对较新。

只需将代码添加到您希望阻止直接URL访问的每个文件之上(在所有内容之前,甚至需要,包含和session_starts),您就可以了。

这是谷歌在他们的PHP示例中使​​用的

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

试试这个吧。 过去在check.php的顶部

<?php debug_backtrace() || die ("<h2>Access Denied!</h2> This file is protected and not available to public."); ?>

当文件直接在URL中访问时,将显示“拒绝访问”

if (basename($_SERVER['SCRIPT_FILENAME']) === 'common.php')
{
    exit('This page may not be called directly!');
}

这个问题有很多答案,但我做了这样的事情。

<?php
    $page = basename($_SERVER['PHP_SELF']);
    
    if($page == "somefile.php"){
      header('Location: index.php');
    }
 ?>

暂无
暂无

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

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