PHP查找文件,其中包含文件名的一部分 [英] PHP finding file where post INCLUDES portion of filename

查看:459
本文介绍了PHP查找文件,其中包含文件名的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向PHP进程发布变量,以尝试在目录中查找文件.

I am posting a variable to a PHP process in an attempt to find a file in a directory.

问题在于文件名比用户提交的文件名长得多.他们只会提交看起来像这样的航程号码:

The problem is the filename is much longer than what the user will submit. They will only submit a voyage number that looks like this:

222INE

文件名看起来像这样:

CMDU-YMUNICORN-222INE-23082016.txt

因此,我需要PHP能够查看目录,找到具有匹配航程编号的文件,并确认其存在(我确实需要能够下载所述文件,但这将是另一个问我是否无法解决这个问题.)

So I need PHP to be able to look into the directory, find the file that has the matching voyage number, and confirm it's existence (I really need to be able to download said file, but that'll be for a different question if I can't figure that out).

无论如何,这是需要一个发布变量的PHP流程:

Anyway, so here is the PHP process that takes a posted variable:

<?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.

The filename will always begin with CMDU. The second part may vary. Then the voyage number. The the date, followed by txt.

推荐答案

好的,首先,您必须列出目录

Ok, first, you must do a directory listing

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

这篇关于PHP查找文件,其中包含文件名的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆