PHP 查找 post 包含文件名部分的文件

PHP finding file where post INCLUDES portion of filename

我正在将变量发布到 PHP 进程以尝试在目录中查找文件。

问题是文件名比用户提交的文件名长得多。他们只会提交如下所示的航次编号:

222INE

而文件名将如下所示:

CMDU-YMUNICORN-222INE-23082016.txt

所以我需要 PHP 才能查看目录,找到具有匹配航行编号的文件,并确认它的存在(我确实需要能够下载该文件,但是如果我想不通,我会提出不同的问题。

无论如何,这里是 PHP 过程,它接受一个已发布的变量:

<?php
  if($_POST['voyage'] == true)
  {
    $voyage = mysqli_real_escape_string($dbc, $_POST['voyage']);
    $files = glob("backup/................."); // <-this is where the voyage will go
    // it should look like this
    // $files = glob("backup/xxxx-xxxxxxxx-222INE-xxxx.txt");

    if(count($files) > 0)
    {
      foreach($files as $file)
      {
        $info = pathinfo($file);
        echo "File found: " . $info["name"];
      }
    }
    else
    {
      echo "File doesn't exist";
    }
  }
?>

文件名将始终以 CMDU 开头。第二部分可能会有所不同。然后是航次号。日期,后跟 txt。

您可以使用scandir功能。
它将 return 目录中的文件数组。
所以,你可以这样做:

$dir = "backup/";  
$files = scandir( $dir );
$myFile = null;  

foreach( $files as $each ) {
    if(preg_match(/*some magic here*/, $each)) {
        $myFile = $dir . $each;
}  
return $myFile;  

我知道这段代码可能有一些错误,但我会尝试这样的事情。

我会使用 scandir 函数获取备份目录中的文件列表,并将其筛选为适当的文件。

$voyageFiles = array_filter( scandir( "backup" ), 

     function($var) use ($voyage) { 
        // expand this regexp as needed. 
        return preg_match("/$voyage/", $var ); 
     } 
)
$voyageFile = array_pop( $voyageFiles ); 

好的,首先,你必须做一个目录列表

<?php
  if($_POST['voyage'] == true)
  {
    $voyage = $_POST['voyage']; //in this case is not important to escape
    $files = scandir("backup"); // <-this is where the voyage will go ***HERE YOU USE DIR LISTING***
   unset($files[0], $files[1]) // remove ".." and ".";

    if(count($files) > 0)
    {
      $fileFound = false;
      foreach($files as $file)
      {

        if((preg_match("/$voyage/", $file) === 1)){
          echo "File found: $file \n";
          $fileFound = true;
        }

      }
       if(!$fileFound) die("File $voyage doesn't exist"); // after loop ends, if no file print "no File"
    }
    else
    {
      echo "No files in backup folder"; //if count === 0 means no files in folder
    }
  }
?>

您的正则表达式模式:

$voyage = $_POST['voyage'];
$pattern = '/^CMDU-.*-'.$voyage.'-.*\.txt/';

您可以在 preg_match 函数中使用 $pattern 变量