我正在使用 htacces mod_rewrite 重写我的网站 URL,例如:
/dir/file.php
/dir/file_example.php
/dir/file2.php?id=test
成为
/dir/file
/dir/file-example
/dir/file2-test
一切都好。现在我有一个 PHP 脚本来执行某些重定向,但在重定向之前我想检查文件(或 url)是否存在:
if(file_exists("/dir/file2-test")){ // redirect on page
}else{ // redirect on index
但是 file_exists() 在这种情况下返回 false。
还有另一种方法可以通过 php 检查这些页面/url(file2-test、file-example 等)是否存在?
PS:由于 htaccess 规则的复杂性,我无法在末尾附加“.php”。
最佳答案
您可以通过实际调用来检查该 URL 是否确实存在,但代价是执行真正的 http 请求,并产生由此导致的所有服务器负载和延迟。
$file = 'http://www.domain.com/dir/file2-test';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
来源:http://www.php.net/manual/en/function.file-exists.php#75064
我根本不推荐这个。
我没有看到任何真正的机会从 php 探测 RewriteEngine 逻辑,因此我建议将整个重写逻辑集成到 htaccess 或 php 中。
关于php 使用 htaccess mod_rewrite 检查 file_exists() 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35457911/