2017-07-25 50 views
0

我正在向PHP进程发布变量以试图在目录中查找文件。PHP查找文件后缀INCLUDES部分文件名

问题是文件名比用户提交的时间长很多。他们只会提交看起来像这样一个航次:

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。

我希望这是有道理的。

如果你能帮助,我会很感激。

回答

1

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

<?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 
    } 
    } 
?> 
+0

我确实相信这是我一直在寻找的东西。仍在测试,但到目前为止,这是有效的。我必须改变(“备份”)到(“备份/”)才能使其工作。另外,我也不需要未设置的部分。接受你的回答作为答案。谢谢你,先生。 –

+0

告诉我是否有效,由于文件系统请求,我无法在在线测试器上测试(或演示给您)。 –

+0

欢迎:) :) :) :) :) –

1

您可以使用scandir函数。
它将返回一个目录内的文件数组。
所以,你可以做这样的事情:

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

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

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

+0

看起来很有希望,然而,我会用什么替换/ *这里有一些魔法* /? –

1

我会使用scandir函数获取备份目录中的文件列表并将其过滤到适当的文件。

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

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

在这种情况下,我无法回显$ voyageFile。有什么想法吗? –

0

您regix模式:

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

你可以在的preg_match功能使用$pattern变量

相关问题