What should be done to get titles (eg abc.jpg) of images from a folder/directory using PHP and storing them in an array.
For example:
a[0] = 'ac.jpg'
a[1] = 'zxy.gif'
etc.
I will be using the array in a slide show.
It's certainly possible. Have a look at the documentation for opendir and push every file to a result array. If you're using PHP5, have a look at DirectoryIterator. It is a much smoother and cleaner way to traverse the contents of a directory!
EDIT: Building on opendir:
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
$images = array();
while (($file = readdir($dh)) !== false) {
if (!is_dir($dir.$file)) {
$images[] = $file;
}
}
closedir($dh);
print_r($images);
}
}
'scandir' does this:
$images = scandir($dir);
One liner :-
$arr = glob("*.{jpg,gif,png,bmp}", GLOB_BRACE)
glob in php - Find pathnames matching a pattern
<?php
//path to directory to scan
$directory = "../images/team/harry/";
//get all image files with a .jpg extension. This way you can add extension parser
$images = glob($directory . "{*.jpg,*.gif}", GLOB_BRACE);
$listImages=array();
foreach($images as $image){
$listImages=$image;
}
?>
Related
How can I just return the file name. $image is printing absolute path name?
<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
$images = glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
foreach($images as $image)
echo $image
?>
All I want is the file name in the specific directory not the absolute name.
Use php's basename
Returns trailing name component of path
<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
$images = glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
foreach($images as $image)
echo basename($image);
?>
Instead of basename, you could chdir before you glob, so the results do not contain the path, e.g.:
<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
chdir($directory); // probably add some error handling around this
$images = glob("*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
foreach($images as $image)
echo $image;
?>
This is probably a little faster, but won't make any significant difference unless you have tons of files
One-liner:
$images = array_map('basename', glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE));
Use basename()
echo basename($image);
You can also remove the extension like this:
echo basename($image, '.php');
Take a look at pathinfo
http://php.net/manual/en/function.pathinfo.php
Pretty helpful function
Example extracting only file names and converting in new array of filenames width extension.
$dir = get_stylesheet_directory();//some dir - example of getting full path dir in wordpress
$filesPath = array_filter(glob($dir . '/images/*.*'), 'is_file');
$files = array();
foreach ($filesPath as $file)
{
array_push($files, basename($file));
}
If you're nervous about the unintended consequences of changing the working directory, you can store the current dir with getcwd() before changing, then simply use that value to switch back after you've done everything you need to do in that dir.
<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
$working_dir = getcwd();
chdir($directory);
$files = glob("*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
chdir($working_dir);
?>
I am looking for a php function to grab images from a directory and load them into an array so that I can output them automatically
For example instead of creating such an array on my own:
$pics = array('../photos/t.png','../photos/t1.png','../photos/t2.png','../photos/t3.png','../photos/t4.png');
It would be much easier if I had a function that fetches all the (.jpg, .png, .jpeg, .bmp) extension files and load them into an array
Your ideas will be very helpful.
You could try something like this:
<?php
$directory = "/var/site/images";
$images = array();
if ($handle = opendir($directory)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$image = realpath("{$directory}/{$entry}");
array_push($images, $image);
}
}
closedir($handle);
}
?>
This will loop through all the files in your images directory and store their path off to the images array. You could even use a substring function to identify images as you loop through (if you have other filetypes in your images folder) and only add the allowed file types to the array.
This is not all my code, some was borrowed from the PHP manual on readdir().
my code is not extracting all of the files inside the directory and i donde know why, i dont have any extension restrictions or anything, ok so this is my code what am i doing wrong? there are 24 images with jpg and png extensions and only 13 are detected when i print_r($arr)
:
<?php
function loadimages($dir) {
if(substr($dir, -1) != "/") $dir .= "/";
$rootdir = $_SERVER["DOCUMENT_ROOT"];
$fulldir = $rootdir."/".$dir;
$dir = opendir($fulldir);
$arr = array();
while(readdir($dir)) {
$arr[] = readdir($dir);
}
echo "<h1>".count($arr). "</h1><br />";
foreach($arr as $img) {
echo "<img src='/pages/course-images/{$img}' />";
}
}
loadimages("pages/course-images");
?>
I would use glob() instead.
$images = glob('*.{png,jpg}', GLOB_BRACE);
print_r($images);
http://php.net/manual/en/function.glob.php
It doesn't work because while(readdir($dir)), then you read one value and skips one step forward to the next file. The correct way would be this, and it's explaind in the manual.
while(false !== ($entry = readdir($dir))) {
$arr[] = $entry;
}
http://php.net/manual/en/function.readdir.php
But glob is better, now it only returns images.
i have searched through the Internet and found the scrip to do this but am having some problems to read the file names.
here is the code
$dir = "folder/*";
foreach(glob($dir) as $file)
{
echo $file.'</br>';
}
this display in this format
folder/s0101.htm
folder/s0692.htm
for some reasons i want to get them in this form.
s0101.htm
s0692.htm
can anyone tell me how to do this?
Just use basename() wrapped around the $file variable.
<?php
$dir = "folder/*";
foreach(glob($dir) as $file)
{
if(!is_dir($file)) { echo basename($file)."\n";}
}
The above code ignores the directories and only gets you the filenames.
You can use pathinfo function to get file name from dir path
$dir = "folder/*";
foreach(glob($dir) as $file) {
$pathinfo = pathinfo($file);
echo $pathinfo['filename']; // as well as other data in array print_r($pathinfo);
}
Is there any way to get only images with extensions jpeg, png, gif etc while using
$dir = '/tmp';
$files1 = scandir($dir);
You can use glob
$images = glob('/tmp/*.{jpeg,gif,png}', GLOB_BRACE);
If you need this to be case-insensitive, you could use a DirectoryIterator in combination with a RegexIterator or pass the result of scandir to array_map and use a callback that filters any unwanted extensions. Whether you use strpos, fnmatch or pathinfo to get the extension is up to you.
The actual question was using scandir and the answers end up in glob. There is a huge difference in both where blob considerably heavy. The same filtering can be done with scandir using the following code:
$images = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
I hope this would help somebody.
Here is a simple way to get only images. Works with PHP >= 5.2 version. The collection of extensions are in lowercase, so making the file extension in loop to lowercase make it case insensitive.
// image extensions
$extensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
// init result
$result = array();
// directory to scan
$directory = new DirectoryIterator('/dir/to/scan/');
// iterate
foreach ($directory as $fileinfo) {
// must be a file
if ($fileinfo->isFile()) {
// file extension
$extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION));
// check if extension match
if (in_array($extension, $extensions)) {
// add to result
$result[] = $fileinfo->getFilename();
}
}
}
// print result
print_r($result);
I hope this is useful if you want case insensitive and image only extensions.
I would loop through the files and look at their extensions:
$dir = '/tmp';
$dh = opendir($dir);
while (false !== ($fileName = readdir($dh))) {
$ext = substr($fileName, strrpos($fileName, '.') + 1);
if(in_array($ext, array("jpg","jpeg","png","gif")))
$files1[] = $fileName;
}
closedir($dh);
You can search the resulting array afterward and discard files not matching your criteria.
scandir does not have the functionality you seek.
If you would like to scan a directory and return filenames only you can use this:
$fileNames = array_map(
function($filePath) {
return basename($filePath);
},
glob('./includes/*.{php}', GLOB_BRACE)
);
scandir() will return . and .. as well as the files, so the above code is cleaner if you just need filenames or you would like to do other things with the actual filepaths
I wrote code reusing and putting together parts of the solutions above, in order to make it easier to understand and use:
<?php
//put the absolute or relative path to your target directory
$images = scandir("./images");
$output = array();
$filer = '/(.jpg|.png|.jpeg|.gif|.bmp))/';
foreach($images as $image){
if(preg_match($filter, strtolower($image))){
$output[] = $image;
}
}
var_dump($output);