Find files with PHP
In PHP you can find files with function glob. The glob function searches for all the pathnames matching pattern according to the rules used by the libc glob function, which is similar to the rules used by common shells. It is nice, but it works for the current directory only. If you need function to search whole directory subtree, then it can be done with few lines more.
Here is first solution for PHP file search. I found PHP function on glob manual page PHP: glob – Manual. Original function works but ignores dot directories in subtree. So, I applied a little modification to include missing dot directories. Returned result are found files packed in array. It’s important to mention implemented recursion and possible high memory consumption.
/** * find files matching a pattern * using PHP "glob" function and recursion * * @return array containing all pattern-matched files * * @param string $dir - directory to start with * @param string $pattern - pattern to glob for */ function find($dir, $pattern)< // escape any character in a string that might be used to trick // a shell command into executing arbitrary commands $dir = escapeshellcmd($dir); // get a list of all matching files in the current directory $files = glob("$dir/$pattern"); // find a list of all directories in the current directory // directories beginning with a dot are also included foreach (glob("$dir/<.[^.]*,*>", GLOB_BRACE|GLOB_ONLYDIR) as $sub_dir) < $arr = find($sub_dir, $pattern); // resursive call $files = array_merge($files, $arr); // merge array with files from subdirectory >// return all found files return $files; >
If you use Unix (Linux) then you can try solution with “find” command. “Find” is very powerful and you can see how files can be searched in post The “find” command. Function will also return array with found files as the first version.
/** * find files matching a pattern * using unix "find" command * * @return array containing all pattern-matched files * * @param string $dir - directory to start with * @param string $pattern - pattern to search */ function find($dir, $pattern) < // escape any character in a string that might be used to trick // a shell command into executing arbitrary commands $dir = escapeshellcmd($dir); // execute "find" and return string with found files $files = shell_exec("find $dir -name '$pattern' -print"); // create array from the returned string (trim will strip the last newline) $files = explode("\n", trim($files)); // return array return $files; >
Both versions return the same result, so you can choose between pure PHP version or version with “find” command.
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?
It sounds like there will only be one image. You could use glob(‘*’) to get an array of files and choose the first (and only) one.
3 Answers 3
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.
$firstFile = scandir("path/to/file/")[2];
scandir: scans the given directory and puts into array: [0] = «.» [1] = «..» [2] = «First File»
@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.
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.
how to search for a file with php
First thing is first. I am not a php developer this is something that is needed for my job so I took it on and I am learning as i go Right now we have an excel sheet that holds links for a manuals for the items we make and these have to be updated manually. It can take hours to do. so I am trying to find a way to do this to cut the time. I can read the excel file to get the info I need using javascript and then I send that to php with an ajax call. I have made sure I get the data I need and make it look how they do on the server. I have been googling all day trying to get it to work but I just keep coming up empty. Here is my code in the php file.
". $pathfile . "| Search var => " . $search; $encodedUrl = rawurlencode($pathfile .$search); echo 'link = http://manuals.myCompany.com/'. $doneUrl .'
'; >else < echo "File does not exist =>"; echo $path. " break; >
So I need to give the php file the name of a manual and see if it is in the directory somewhere. this file is searchManuals.php stored in the manuals folder (manuals/searchManuals.php).The files I look for are in folders in the same directory with it (manuals/english/jdv0/pdf/manual.pdf).
your post is very confusing. are you looking for function to search files in any specific directory using php?
Sorry. I need to put in a manual name and find it on the server in one of the many files that hold them. I only get the name. and need to return the link to that file
Why don’t you use this amazing library? symfony.com/doc/current/components/finder.html The first example actually searches a directory recursively
PHP : Finding Files on Directory
If you’re looking for a recursive search you might be interested in the spl’s RecursiveDirectoryIterator.
Working nicely. Thank you. However, i have to use the exact search as filename. Let say filename is : ‘i like blue.jpg’, my search is : ‘blue’. How do it make it the jpg file is shown when blue is searched for example.
That could be something like if ( false!==stripos($info->getFilename(), $searchstring) ) , docs.php.net/stripos
Hi, its worked good. Thanks. Another question, i have three file called, blue.jpg, blue.avi, blue.mp3. whenever i searched for blue, only blue.avi returned. Is it possible to return 3 files?
The break statement is responsible for ending the search after the first match, see docs.php.net/break
As long as you only want to look in one directory, then yes, coding it using the PHP functions is quicker. But if you want to search recursively through the tree for a particular filename then it’ll probably be a lot quicker to shell out:
$cmd="dir $fname /s" chdir("C:/"); $found=explode("\n",`$cmd`);
But I believe that these days NT has file indexing built in to the OS — so there must be hooks exposed somewhere for an even faster search.
I use scandir for this purpose, like so:
$path = $_SERVER['DOCUMENT_ROOT']; $files = scandir($path); echo '
'; if (count($files) > 2) < // first 2 entries are '.' and '..' $files = array_slice($files, 2); print_r($files); >echo '';
If you are talking about the server on whcih PHP is installed, it should be infinitely possible with the PHP file command, as long as you are accessing areas of the HDD that share permissions with the webserver. The first example on PHP.net says as much .
If you are talking about your user’s machine, they can select a file to upload using a form element, but you cannot browse it using any server side language, because it is exactly that.
Unless you’re talking about the C: drive on the server, or a command-line version of PHP running on your Windows machine, PHP as a server side language, doesn’t have access to your C: drive.
If you are referring to the C: drive on the server, then the readdir function (as haim evgi suggested) should work for you.
Remember to read the warning on the readdir reference page, and remember to open the directory first. The function reference provides sample code.
I assume you want to run from the actual PHP interpreter (ie as a local script), you can use SPL(php 5)
see here and here for just 2 examples. More examples if you read the PHP manual and lots of others on the web if you search hard enough.
This question is in a collective: a subcommunity defined by tags with relevant content and experts.