简体   繁体   English

如何在PHP中获取区分大小写的文件名?

[英]How to get case sensitive file name in PHP?

I've created a function to call file from folder.我创建了一个函数来调用文件夹中的文件。 But the problem is that it is not matching case.但问题是它不匹配大小写。 My function is我的功能是

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

So if file is exists, I include it.因此,如果文件存在,我将其包含在内。 Like if $var = profile then it will check in core folder for profile.php and if it exists then it will include it.就像如果 $var = profile 那么它将检查 profile.php 的核心文件夹,如果它存在,那么它将包含它。 I am including file when I am calling this function.我在调用此函数时包含文件。 But the problem is that it is not case sensitive.但问题是它不区分大小写。 like if I look for "PrOFile" then it will include profile.php so how to solve this?就像如果我寻找“PrOFile”,那么它将包含 profile.php 那么如何解决这个问题? Please help me if anyone can.如果有人可以,请帮助我。

Use realpath() combined with converting the slashes if needed.如果需要,将 realpath() 与转换斜杠结合使用。

Examples:例子:

// 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)) {

On Windows, filenames are case-insensitive.在 Windows 上,文件名不区分大小写。 That's just how they work.这就是他们的工作方式。

So you need to manually code around this:所以你需要围绕这个手动编码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM