Search code examples
phpfilenamesglob

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


I have a form for users to upload files into the folder. HTML and PHP codes are as below:

<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"]);
?>

The upload form works well, and uploaded files are in the folder testFolder/ .

Now I want to use glob() function to get all file names in the folder.

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

However, it doesn't echo anything.

The glob() function works well on other folders, which contains existing files, not uploaded files.

But why doesn't it work on this folder with uploaded files ?


Solution

  • Because I didn't give the extension for the uploaded file, that's why glob("testFolder/*.*") doesn't get anything.

    Two solutions:

    1. Give uploaded files an extension.

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

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

    Then, glob("testFolder/*.*") will be able to get these uploaded files with an extension.

    1. Just change glob("testFolder/*.*") to be glob("testFolder/*")