This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get the Files inside a directory
Is there a function that can be used to get the contents of a directory (a photo gallery directory for example) ?
I'm trying to save time on a project by automating a photo gallery based on which files are available.
Thanks
Shane
You can either use the DirectoryIterator:
$dir = new DirectoryIterator('path/to/images');
foreach ($dir as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
or alternatively glob():
$filenames = glob('path/to/images/*.jpg');
foreach ($filenames as $filename) {
echo $filename ."\n";
}
glob()
scandir()
I use a while loop to grab a list of files, omit the 2nd if statement if you want to grab a all files.
if ($handle = opendir('/photos/')) {
while(false !== ($sFile = readdir($handle))) {
if (strrpos($sFile, ".jpg") === strlen($sFile)-strlen(".jpg")) {
$fileList[] = $sfile;
}
}
}
Related
This question already has answers here:
How to sort files by date in PHP
(6 answers)
Closed 7 years ago.
Suppose there's a directory named "abc"
This directory contains number of files. Out of all these files, I just want latest "X" or latest 15 files in an array(if possible using glob function) in php.
Every help will be greatly appreciable.
// directory for searching files
$dir = "/etc/php5/*";
// getting files with specified four extensions in $files
$files = glob($dir."*.{extension1,extension2,extension3,extension4}", GLOB_BRACE);
// will get filename and filetime in $files
$files = array_combine($files, array_map("filemtime", $files));
// will sort files according to the values, that is "filetime"
arsort($files);
// we don't require time for now, so will get only filenames(which are as keys of array)
$files = array_keys($files);
$starting_index = 0;
$limit = 15;
// will limit the resulted array as per our requirement
$files = array_slice($files, $starting_index,$limit);
// will print the final array
echo "Latest $limit files are as below : ";
print_r($files);
Please improve me, if am wrong
Use the function posted here: http://code.tutsplus.com/tutorials/quick-tip-loop-through-folders-with-phps-glob--net-11274
$dir = "/etc/php5/*";
// Open a known directory, and proceed to read its contents
foreach(glob($dir) as $file)
{
echo "filename: $file : filetype: " . filetype($file) . "<br />";
}
And use filetime() function inside your foreach loop as an IF statement.: http://php.net/manual/en/function.filemtime.php
One way to do this and it's better than glob is to use the RecursiveDirectoryIterator
$dir = new \RecursiveDirectoryIterator('path/to/folder', \FilesystemIterator::SKIP_DOTS);
$it = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST);
$it->setMaxDepth(99); // search for other folders and they child folders
$files = [];
foreach ($it as $file) {
if ($file->isFile()) {
var_dump($file);
}
}
or if you still want to do it with glob
$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
var_dump($file);
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
get last modified file in a dir?
I have a folder which contents more than 30000 subfolders in it. How can I get a list of subfolders with last modification date >= one hour ago? Is it possible to do that without getting a list of all files in an array and sorting it? I cannot use a readdir function because it returns files in the order in which they are stored by the filesystem and exhaustive search of the list of files will take a very long time.
Use GNU Find - it is simpler and faster!
find [path] -type d -mmin +60
The linux "find" command is pretty powerful.
$cmd = "find ".$path." type -d -mmin +60";
$out=`$cmd`;
$files=explode("\n",$out);
Give this a try:
<?php
$path = 'path/to/dir';
if (is_dir($path)) {
$contents = scandir($path);
foreach ($contents as $file) {
$full_path = $path . DIRECTORY_SEPARATOR . $file;
if ($file != '.' && $file != '..') {
if (is_dir($full_path)) {
$dirs[filemtime($full_path)] = $file;
}
}
}
// Sort in reverse order to put newest modification at the top
krsort($dirs);
$iteration = 0;
foreach ($dirs as $mtime => $name) {
if ($iteration != 5) {
echo $name . '<br />';
}
$iteration++;
}
}
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does glob() have negation?
I want to delete all files from a directory (could be any number of file extentions) apart from the single index.html in there.
I'm using:
$path = "/assets/cache/";
foreach(glob($path ."*.*") as $file) {
unlink($file);
}
But can't for the life of me how to say unlink, if not .html!
Thanks!
Try this here...
$path = "/assets/cache/";
foreach(glob($path ."*.*") as $file) {
$pathPart = explode(".",$file);
$fileEx = $pathPart[count($pathPart)-1];
if($fileEx != "html" && $fileEx != "htm"){
unlink($file);
}
}
try
$path = "/assets/cache/";
foreach(glob($path ."*.*") as $file) {
if(pathinfo($file, PATHINFO_EXTENSION) != 'html') {
unlink($file);
}
}
if you want to delete other html files also (apart from "index.html"):
$path = "/assets/cache/";
foreach(glob($path ."*.*") as $file) {
if(pathinfo($file, PATHINFO_BASENAME) != 'index.html') {
unlink($file);
}
}
The php function glob has no negation, however PHP can give you the difference between two globs via array_diff:
$all = glob("*.*");
$not = glob("php_errors.log");
var_dump(
$all,
$not,
array_diff($all, $not)
);
See the demo: http://codepad.org/RBFwPUWm
If you do not want to use arrays, I highly suggest to take a look into PHPs directory iterators.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Finding a file with a specific name with any extension
i've this code for put into an array all the files contained into a directory
$directory = "./";
$ourDirList = scandir($directory);
$arraylistafiles=array();
foreach($ourDirList as $ourItem)
{
if (is_file($ourDir . $ourItem))
{$arraylistafiles[]=$ourItem;}
}
but if i want to put only the file that have ".jpg" extension, what i can do?
Using PHP's glob() you can avoid the is_file() call because glob will only return files that actually exist in the directory. There is no need to create a UDF (user defined function) in your case.
$dir = './';
foreach(glob($dir.'*.jpg') as $file) {
print $file . "\n";
}
UPDATE
From your comment it's clear that you don't understand how glob() works. You can achieve what you're trying to do like this:
$arraylistafiles = glob($dir.'*.jpg');
if(is_file($ourDir.$ourItem) && substr($ourItem,-4) == '.jpg') {
//
}
You can use bellow function.
public function getFileList($dirpath,$list_ignore,$list_allowed_ext)
{
$filelist = array();
if ($handle = opendir(dirname ($dirpath)))
{
while (false !== ($file = readdir($handle)))
{
if (!is_dir($file) && !in_array($file,$list_ignore) && in_array(strtolower(end(explode('.',$file))),$list_allowed_ext))
{
$filelist[] = $file;
}
}
closedir($handle);
}
return $filelist;
}
Implementation will be looks like..
$fileTypes = array ("jpg");
$list_ignore = array ('.','..');
$fileList = getFileList("./",$list_ignore,$fileTypes);
Cheers!
First you have to check for the file extension for the file in foreach array. . If the extension is jpg then add that item into the new array. . . Hope you understand. .
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
List all folders on my computer (php)
I have tried:
$handle = opendir($path);
But what is the path? I put everything but the kitchen sink in there! I can't get it to work. I'm on my localhost right now.
I did:
opendir(dirname(__FILE__));
Here is what a got to work...
$dir = dirname(__FILE__);
// Open a known directory, and proceed to read its contents
if(is_dir($dir))
{
if($dh = opendir($dir))
{
while(($file = readdir($dh)) !== false)
{
echo "filename: ".$file."<br />";
}
closedir($dh);
}
}
Will do some cleaning to get the information I was wanting. However, thanks to "some" of you on Stackoverflow I like this code alot better for localhost application.
foreach(glob("*") as $filename)
{
echo $filename."<br />";
}
$path is the path to the directory you want to open.
Like c:\users\MP123\Photos
or /home/MP123/Photos
This is really a "read the PHP manual, which has full examples for how to list folders and files", not an "ask professionals for help with my problem" type topic.
You're looking for glob (for easy stuff) or DirectoryIterator (for a more OOP approach).
(Examples from the respective doc pages w/ some modifications)
<?php
// all files in current directory (including '.' and '..')
foreach (glob("*") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
<?php
// all files in current directory (excluding'.' and '..')
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
?>