Get first file in directory PHP

时间:2015-10-31 00:13:57

标签: php image directory user-profile

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?

3 个答案:

答案 0 :(得分:11)

你可以在这样的目录中获得第一个文件

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

然后使用fopen()打开,您可以使用w或w +模式:

  

w 仅限写作;将文件指针放在开头   该文件并将文件截断为零长度。如果文件没有   存在,试图创造它。

答案 1 :(得分:7)

$firstFile = scandir("path/to/file/")[2];

scandir:扫描给定目录并放入数组:[0] ="。" [1] =" .." [2] ="第一个文件"

答案 2 :(得分:1)

随着目录包含的文件越多,使用readdir()的速度应该更快,因为我们不会将所有文件都写入数组:

if ($h = opendir($dir)) {
    while (($file = readdir($h)) !== false) {
        if ($file != '.' && $file != '..') {
            break;
        }
    }
    closedir($h);
}