阻止直接url访问php文件 [英] prevent direct url access to php file
问题描述
我在我的网站上有一个php文件,内容为check.php,并在表单提交时执行。
说我的网站是myweb.com,而php文件位于PHP目录中
我想阻止直接url访问check.php文件,即如果任何人输入URL myweb.com/PHP/check.php ,那么php文件不应该被执行,它应该返回我试图通过在.htaccess中设置规则来阻止访问,但即使在我尝试提交表单时,它也会阻止php。
.htaccess规则:
RewriteEngine on
RewriteCond%{ THE_REQUEST} \.php [\ /?].*HTTP/
(。*)\.php $ /index.html [L]
有没有办法做到这一点?
您可以用PHP完成
<?php
/ *在'ch eck.php'* /
if($ _SERVER ['REQUEST_METHOD'] =='GET'&& realpath(__ FILE__)== realpath($ _SERVER ['SCRIPT_FILENAME'])){
/ *
要发送哪个头,有些人更喜欢404,即使
文件存在安全
* /
头('HTTP / 1.0 403 Forbidden',TRUE,403);
/ *选择适当的页面重定向用户* /
die(header('location:/error.php'));
}
?>
I have a php file say "check.php" in my website and it is executed when a form is submitted.
say my website is "myweb.com" and the php file is in a directory "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.
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 rule :
RewriteEngine on
RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/
(.*)\.php$ /index.html [L]
Is there any possible way to do it ?
You can do it with 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屋!