phpimagedirectoryuser-profile

Get first file in directory PHP


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?


Solution

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