如何使用 glob() 函数获取上传的文件名?

How to Get Uploaded File Name with glob() Function?

我有一个表格供用户将文件上传到文件夹中。 HTML和PHP代码如下:

<form enctype="multipart/form-data" method="post" action="test.php">
  <input type="text" name="name"/><br/>
  <input type="file" name="photo" /><br/>
  <input type="submit"/>
</form>
<?php  //test.php
    move_uploaded_file($_FILES["photo"]["tmp_name"], "testFolder/".$_POST["name"]);
?>

上传表单效果很好,上传的文件在文件夹 testFolder/ .

现在我想使用 glob() 函数来获取文件夹中的所有文件名。

<?php
  foreach(glob("testFolder/*.*") as $file) {
    echo $file."<br/>";
  }
?>

然而,它没有回应任何东西。

glob() 函数适用于包含现有文件而非上传文件的其他文件夹。

但是为什么它在这个包含上传文件的文件夹中不起作用?

可能的通配符扩展名可能是问题所在。

可能是 glob 不允许通配符扩展,我在文档中没有看到任何提及。您是否尝试过目录迭代器?

$dir = new DirectoryIterator(__DIR__.'/testFolder);
foreach ($dir as $file) {
    echo $file->getFilename();
}

更新:路径不是问题所在

您使用的是相对文件路径,因此 glob 可能找不到您要搜索的目录。

调用该函数的脚本需要位于“testFolder”的父目录中,或者您需要像这样使用绝对路径。

<?php
  foreach(glob("/absolute/path/to/testFolder/*.*") as $file) {
    echo $file."<br/>";
  }
?>

如果您确实想使用相对路径,您可以执行以下操作:

<?php
  //__DIR__ is a PHP super constant that will get the absolute directory path of the script being ran

  // .. = relative, go up a folder level

  foreach(glob(__DIR__."/../testFolder/*.*") as $file) {
    echo $file."<br/>";
  }
?>

显然上面的路径只是示例,但应该能让您走上正确的轨道。

希望对您有所帮助

因为我没有为上传的文件提供扩展名,所以 glob("testFolder/*.*") 没有得到任何东西。

两种解决方案:

  1. 给上传的文件一个扩展名。

$ext = strrchr($_FILES["photo"]["name"], ".");

move_uploaded_file($_FILES["photo"]["tmp_name"], "testFolder/".$_POST["name"].$ext);

然后,glob("testFolder/*.*")就可以得到这些上传的带扩展名的文件了。

  1. 只要把glob("testFolder/*.*")改成glob("testFolder/*")