9

I want to get the first file in a directory using PHP.

I am trying to make a function where the users on my website can change their profile picture. To show their profile picture on their profile page I want to get the first image in their profile picture folder. I want to get the image they have uploaded, regardless of the file type. I have made it so when they upload a new picture the old one will be deleted, so it will just be one file in the folder. How do i do this?

Dromnes
  • 302
  • 2
  • 3
  • 12

3 Answers3

21

You can get first file in directory like this

$directory = "path/to/file/";
$files = scandir ($directory);
$firstFile = $directory . $files[2];// because [0] = "." [1] = ".." 

Then Open with fopen() you can use the w or w+ modes:

w Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

Abdullah
  • 627
  • 9
  • 27
12
$firstFile = scandir("path/to/file/")[2];

scandir: scans the given directory and puts into array: [0] = "." [1] = ".." [2] = "First File"

Hugo Cox
  • 389
  • 4
  • 15
  • Why is [2] the first File? And what do the pots mean? – skm Dec 31 '17 at 10:55
  • 1
    @skm on most non-windows systems '.' and '..' are mean 'this folder' and 'parent folder'. They are listed first by `scandir` making the first 'normal' file the third in the list. – David Amey Jan 10 '18 at 07:51
2

As more files the directory contains, it should be faster to use readdir() instead, because we do not write all files into an array:

if ($h = opendir($dir)) {
    while (($file = readdir($h)) !== false) {
        if ($file != '.' && $file != '..') {
            break;
        }
    }
    closedir($h);
}
echo "The first file in $dir is $file";

But as readdir does not return a sorted result you maybe need to replace break against a check that garantees the most recent file. One idea would be to add an increment numbering to your files and check for the highest number. Or you create a subfolder with the name of the most recent file and remove/create a new subfolder for every new file that is added to the folder.

mgutt
  • 5,867
  • 2
  • 50
  • 77