防止直接 url 访问 php 文件 [英] prevent direct url access to php file

查看:26
本文介绍了防止直接 url 访问 php 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站中有一个名为 "check.php" 的 php 文件,它在提交表单时执行.

I have a php file say "check.php" in my website and it is executed when a form is submitted.

假设我的网站是 "myweb.com" 并且 php 文件在目录 "PHP" 中

say my website is "myweb.com" and the php file is in a directory "PHP"

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

I want to prevent direct url access to the "check.php" file i.e. if anyone types the url "myweb.com/PHP/check.php" ,then the php file should not be executed and it should return a error message instead.

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

I tried to prevent the access by setting a rule in .htaccess ,but it blocks the php even when I try to submit the form.

.htaccess 规则:

.htaccess rule :

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

有没有办法做到这一点?

Is there any possible way to do it ?

推荐答案

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' ) );

    }
?>

这篇关于防止直接 url 访问 php 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆