John Beasley John Beasley - 3 years ago 60
PHP Question

PHP finding file where post INCLUDES portion of filename

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


Whereas the filename will look like this:

CMDU-YMUNICORN-222INE-23082016.txt


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

Anyways, 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";
}
}
?>


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

I hope that makes sense.

If you can help, i'd appreciate it.

Answer Source

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
    }
  }
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download