[英]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.