【问题标题】:How to get case sensitive file name in PHP?如何在 PHP 中获取区分大小写的文件名?
【发布时间】:2014-03-31 17:23:01
【问题描述】:

我创建了一个从文件夹调用文件的函数。但问题是它不匹配大小写。我的功能是

function CheckFile($var){
    if($var){
        $file = $_SERVER['DOCUMENT_ROOT'].'/include_folder/'.$var.'.php';
        if (file_exists($file)) {
        return true;
        } 
    } 
}

所以如果文件存在,我会包含它。就像如果 $var = profile 那么它会检查 profile.php 的核心文件夹,如果它存在,那么它将包含它。我在调用此函数时包含文件。但问题是它不区分大小写。就像如果我寻找“PrOFile”那么它将包括 profile.php 那么如何解决这个问题?如果有人可以,请帮助我。

【问题讨论】:

  • 不使用Windows运行PHP?
  • 我用 xampp 来开发我的应用程序。还有 Windows 8。
  • 尝试使用正则表达式。
  • 理想情况下,您的开发和生产环境应该相同。如果没有大量的混乱,您将无法绕过核心 Windows 文件系统“功能”。同样,PHP 在 Windows 和 *nix 上的行为方式有很多不同之处。我是否可以建议使用 VirtualBox 之类的东西来运行要在其上开发的 *nix 虚拟机?
  • 我尝试了很多。我尝试了 preg_match 和 preg_match_all。但它根本不起作用。

标签: php file include file-exists


【解决方案1】:

如果需要,使用 realpath() 并转换斜杠。

例子:

// Check the filename is the same (don't worry on the path)
if (file_exists($filepath) && basename(realpath($filepath)) === basename($filepath)) {

// Check the full path, converting slashes to be sure
// Assumes final path is Lunix orientated
if (file_exists($filepath) && str_replace('\\', '/', realpath($filepath)) === $filepath) {

// Check the full path, converting slashes to be sure
// Assumes final path may not be Lunix orientated
if (file_exists($filepath) && str_replace('\\', '/', realpath($filepath)) === str_replace('\\', '/', $filepath)) {

【讨论】:

    【解决方案2】:

    在 Windows 上,文件名不区分大小写。它们就是这样工作的。

    所以你需要手动编写代码:

    if( file_exists($file) && glob($file)[0] === $file) // assumes PHP 5.4
                 // older versions need a temporary variable for glob
    

    【讨论】:

    • 它没有用。我试图用小字符查找个人资料,但出现 404 错误
    • 关于文件名在 Windows 中不区分大小写的评论值得记住。
    • 这个glob 什么都不做。它返回提供的大小写,而不是文件系统中的真实大小写。 Windows 10 上的 PHP 7。
    猜你喜欢
    • 2012-02-03
    • 2019-06-16
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多