可以通过以下措施防止 PHP 文件路径访问:使用 .htaccess 文件重写请求;禁用目录浏览;隐藏文件扩展名;使用 PHP 的 basename() 函数获取文件路径的最后一部分。

如何防止 PHP 文件路径访问
为了防止访问 PHP 文件路径,可以采取以下措施:
1. 使用 .htaccess 文件
在网站的根目录下创建一个名为 .htaccess 的文件,并添加以下代码:
立即学习“PHP免费学习笔记(深入)”;
<code>RewriteEngine On RewriteRule ^(.*)$ /index.php</code>
这将重写所有对 PHP 文件路径的请求,将其定向到 index.php 文件。
2. 禁用目录浏览
在服务器的配置文件中(通常是 httpd.conf 或 nginx.conf),禁用目录浏览:
Apache:
<code>Options -Indexes</code>
Nginx:
<code>autoindex off;</code>
3. 隐藏文件扩展名
在服务器的配置文件中,隐藏 PHP 文件扩展名:
Apache:
<code>AddType application/x-httpd-php .php</code>
Nginx:
<code>location ~ \.php$ {
include fastcgi_params;
fastcgi_pass ...;
index index.php;
}</code>4. 使用 PHP 的内置函数
在 PHP 脚本中,可以使用 basename() 函数获取文件路径的最后一部分,而不包括路径:
<code class="php">$filename = basename(__FILE__);</code>
以上就是如何不让访问php文件路径的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号