I have a piece of code that print images from a directory.
<?
$directory = 'assets/images/';
$files = glob($directory."*.{jpg}", GLOB_BRACE);
$filecount = count($files);
for($i=1; $i<=$filecount; $i++) {
echo '<img src="'.$file.'" class="img-responsive">';
}
?>
It's working perfectly.
Except that I want to display my image depending the uploaded date.
Is it possible please ?
Thanks.
Try this:
function listdir_by_date($path){
$dir = opendir($path);
$list = array();
while($file = readdir($dir)){
if ($file != '.' and $file != '..'){
// add the filename, to be sure not to
// overwrite a array key
$ctime = filectime($data_path . $file) . ',' . $file;
$list[$ctime] = $file;
}
}
closedir($dir);
krsort($list);
return $list;
}
Reference
Okie, give this a go, using your glob method:
$directory = 'assets/images/';
$images = [];
$files = glob($directory . '*.{jpg}', GLOB_BRACE);
foreach($files as $file) {
$images[] = [filectime($file), $file];
}
array_multisort($images, SORT_DESC);
foreach ($images as $image) {
echo '<img src="' . $image[1] . '" class="img-responsive"><br>';
}
Just a slightly different method then what #mayank-pandey presented, but same basic end results.
Related
Well i am trying to edit this code to include all sub-folders, the problem is this code only search images into 1 folder, it will not search images into sub-folders.
Header("content-type: application/x-javascript");
$pathstring=pathinfo($_SERVER['PHP_SELF']);
$locationstring="http://" . $_SERVER['HTTP_HOST'].$pathstring['dirname'] . "/";
function returnimages($dirname=".")
{
$pattern="~\.(jpe?g|gif)$~";
$files = array();
if($handle = opendir($dirname))
{
while(false !== ($file = readdir($handle))){
if(preg_match($pattern, $file)){
$files[] = $file;
}
}
closedir($handle);
}
// sort pics in reverse order
rsort($files);
// output images into javascript array
foreach($files as $key => $pic)
{
echo "picsarray[$key] = '$pic';";
}
}
echo 'var locationstring="' . $locationstring . '";';
echo 'var picsarray=new Array();';
returnimages();
The idea can someone fix this code to be able to search all images including the sub-folders.
I hope this approach is useful to you:
Header("content-type: application/x-javascript");
$pathstring=pathinfo($_SERVER['PHP_SELF']);
$locationstring="http://" . $_SERVER['HTTP_HOST'].$pathstring['dirname'] . "/";
function returnImages($dir = ".")
{
$files = array_diff(scandir($dir), Array(".", ".."));
$dir_array = Array();
$images = array();
$pattern="~\.(jpe?g|gif)$~";
foreach ($files as $file) {
$path = $dir . "/" . $file;
if (is_dir($path)) {
// This does the magic, if is a folder, we recursively seek for more images.
$images = array_merge($images, returnImages($path));
}
else if (preg_match($pattern, $path)) {
$images[] = $path;
}
}
return $images;
}
function printSortedImages(array $images) {
// sort pics in reverse order
rsort($images);
// output images into javascript array
foreach($images as $key => $pic)
{
echo "picsarray[$key] = '$pic';";
}
}
echo 'var locationstring="' . $locationstring . '";';
echo 'var picsarray=new Array();';
$images = returnImages();
printSortedImages($images);
I am using WordPress. I have an image folder like mytheme/images/myimages.
I want to retrieve all the images name from the folder myimages
Please advice me, how can I get images name.
try this
$directory = "mytheme/images/myimages";
$images = glob($directory . "/*.jpg");
foreach($images as $image)
{
echo $image;
}
you can do it simply with PHP opendir function.
example:
$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="pictures/'.$file.'" border="0" />';
}
}
When you want to get all image from folder then use glob() built in function which help to get all image . But when you get all then sometime need to check that all is valid so in this case this code help you. this code will also check that it is image
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
$supported_format = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format))
{
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
} else {
continue;
}
}
If you do not want to check image type then you can use this code also
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
}
for more information
PHP Manual
Here is my some code
$dir = '/Images';
$ImagesA = Get_ImagesToFolder($dir);
print_r($ImagesA);
function Get_ImagesToFolder($dir){
$ImagesArray = [];
$file_display = [ 'jpg', 'jpeg', 'png', 'gif' ];
if (file_exists($dir) == false) {
return ["Directory \'', $dir, '\' not found!"];
}
else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($file_type, $file_display) == true) {
$ImagesArray[] = $file;
}
}
return $ImagesArray;
}
}
This answer is specific for WordPress:
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );
$media_dir = $base_dir . 'yourfolder/images/';
$media_url = $hase_url . 'yourfolder/images/';
$image_paths = glob( $media_dir . '*.jpg' );
$image_names = array();
$image_urls = array();
foreach ( $image_paths as $image ) {
$image_names[] = str_replace( $media_dir, '', $image );
$image_urls[] = str_replace( $media_dir, $media_url, $image );
}
// --- You now have:
// $image_paths ... list of absolute file paths
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
// $image_urls ... list of absolute file URLs
// e.g. http://example.com/wp-content/uploads/yourfolder/images/sample.jpg
// $image_names ... list of filenames only
// e.g. sample.jpg
Here are some other settings that will give you images from other places than the child theme. Just replace the first 2 lines in above code with the version you need:
From Uploads directory:
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
$upload_path = wp_upload_dir();
$base_dir = trailingslashit( $upload_path['basedir'] );
$base_url = trailingslashit( $upload_path['baseurl'] );
From Parent-Theme
// e.g. /path/to/wordpress/wp-content/themes/parent-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_template_directory() );
$base_url = trailingslashit( get_template_directory_uri() );
From Child-Theme
// e.g. /path/to/wordpress/wp-content/themes/child-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );
$dir = "mytheme/images/myimages";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
$images=preg_grep ('/\.jpg$/i', $files);
Very fast because you only scan the needed directory.
//path to the directory to search/scan
$directory = "";
//echo "$directory"
//get all files in a directory. If any specific extension needed just have to put the .extension
//$local = glob($directory . "*");
$local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
//print each file name
echo "<ul>";
foreach($local as $item)
{
echo '<li>'.$item.'</li>';
}
echo "</ul>";
Check if exist, put all files in array, preg grep all JPG files, echo new array For all images could try this:
$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);
if ($handle = opendir('/path/to/folder')) {
while (false !== ($entry = readdir($handle))) {
$files[] = $entry;
}
$images=preg_grep('/\.jpg$/i', $files);
foreach($images as $image)
{
echo $image;
}
closedir($handle);
}
<?php
$galleryDir = 'gallery/';
foreach(glob("$galleryDir{*.jpg,*.gif,*.png,*.tif,*.jpeg}", GLOB_BRACE) as $photo)
{echo "\n" ;echo "<img style=\"padding:7px\" class=\"uk-card uk-card-default uk-card-hover uk-card-body\" src=\"$photo\">"; echo "";}?>
UIkit php folder gallery
https://webshelf.eu/en/php-folder-gallery/
// Store your file destination to a variable
$fileDirectory = "folder1/folder2/../imagefolder/";
// glob function will create a array of all provided file type form the specified directory
$imagesFiles = glob($fileDirectory."*.{jpg,jpeg,png,gif,svg,bmp,webp}",GLOB_BRACE);
// Use your favorite loop to display
foreach($imagesFiles as $image) {
echo '<img src="'.$image.'" /><br />';
}
get all the images from a folder in php without database
$url='https://demo.com/Images/sliderimages/';
$dir = "Images/sliderimages/";
$file_display = array(
'jpg',
'jpeg',
'png',
'gif'
);
$data=array();
if (file_exists($dir) == false) {
$rss[]=array('imagePathName' =>"Directory '$dir' not found!");
$msg=array('error'=>1,'images'=>$rss);
echo json_encode($msg);
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
#$file_type = strtolower(end(explode('.', $file)));
// $file_type1 = pathinfo($file);
// $file_type= $file_type1['extension'];
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
$data[]=array('imageName'=>$url.$file);
}
}
if(!empty($data)){
$msg=array('error'=>0,'images'=>$data);
echo json_encode($msg);
}else{
$rees[]=array('imagePathName' => 'No Image Found!');
$msg=array('error'=>2,'images'=>$rees);
echo json_encode($msg);
}
}
You can simply show your actual image directory(less secure). By just 2 line of code.
$dir = base_url()."photos/";
echo"Photo Directory";
I'm using this to return images in the order they were added to the directory, however I want them to be ordered from newest to older. How can I do it? Thanks
<?
$handle = #opendir("images");
if(!empty($handle)) {
while(false !== ($file = readdir($handle))) {
if(is_file("images/" . $file))
echo '<img src="images/' . $file . '"><br><br>';
}
}
closedir($handle);
?>
If you want them ordered from newest to older, then you cannot rely on just readdir. That order might be arbitrary. You'll need to sort them by timestamps:
$files = glob("images/*"); // or opendir+readdir loop
$files = array_combine($files, array_map("filemtime", $files));
arsort($files); // sorts by time
$files = array_keys($files); // just leave filenames
I think the easiest way is to read your files into an array, reverse it and output the reversed array:
<?php
$handle = #opendir("images");
if(!empty($handle))
{
$files = array();
while(false !== ($file = readdir($handle)))
{
if(is_file("images/" . $file))
$files[] = $file;
}
foreach(array_reverse($files) as $file) {
echo '<img src="images/' . $file . '"><br><br>';
}
}
closedir($handle);
?>
Like this:
<?
$handle = #opendir("images");
$files = array();
if(!empty($handle)) {
while(false !== ($file = readdir($handle))) {
if(is_file("images/" . $file))
$files[] = $file;
}
}
closedir($handle);
// flip the array over
$files = array_reverse($files);
// display on screen
foreach ($files as $file)
echo '<img src="images/' . $file . '"><br><br>';
?>
This question already has answers here:
Getting the names of all files in a directory with PHP
(15 answers)
Closed 6 months ago.
I have the code below that lists all the images in a folder, the problem is that it finds some files ( a . and a ..) that I am not sure what they are so I am not sure how to prevent them from showing up. I am on a windows XP machine, any help would be great, thanks.
Errors: Warning: rename(images/.,images/.) [function.rename]: No error
in C:\wamp\www\Testing\listPhotosA.php on line 14
Warning: rename(images/..,images/..) [function.rename]: No error in
C:\wamp\www\Testing\listPhotosA.php on line 14
Code:
<?php
define('IMAGEPATH', 'images/');
if (is_dir(IMAGEPATH)){
$handle = opendir(IMAGEPATH);
}
else{
echo 'No image directory';
}
$directoryfiles = array();
while (($file = readdir($handle)) !== false) {
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}
foreach($directoryfiles as $directoryfile){
if(strlen($directoryfile) > 3){
echo '<img src="' . IMAGEPATH . $directoryfile . '" alt="' . $directoryfile . '" /> <br>';
}
}
closedir($handle); ?>
I like PHP's glob function.
foreach(glob(IMAGEPATH.'*') as $filename){
echo basename($filename) . "\n";
}
glob() is case sensitive and the wildcard * will return all files, so I specified the extension here so you don't have to do the filtering work
$d = 'path/to/images/';
foreach(glob($d.'*.{jpg,JPG,jpeg,JPEG,png,PNG}',GLOB_BRACE) as $file){
$imag[] = basename($file);
}
Use glob function.
<?php
define('IMAGEPATH', 'images/');
foreach(glob(IMAGEPATH.'*') as $filename){
$imag[] = basename($filename);
}
print_r($imag);
?>
You got all images in array format
To get all jpg images in all dirs and subdirs inside a folder:
function getAllDirs($directory, $directory_seperator) {
$dirs = array_map(function ($item) use ($directory_seperator) {
return $item . $directory_seperator;
}, array_filter(glob($directory . '*'), 'is_dir'));
foreach ($dirs AS $dir) {
$dirs = array_merge($dirs, getAllDirs($dir, $directory_seperator));
}
return $dirs;
}
function getAllImgs($directory) {
$resizedFilePath = array();
foreach ($directory AS $dir) {
foreach (glob($dir . '*.jpg') as $filename) {
array_push($resizedFilePath, $filename);
}
}
return $resizedFilePath;
}
$directory = "C:/xampp/htdocs/images/";
$directory_seperator = "/";
$allimages = getAllImgs(getAllDirs($directory, $directory_seperator));
Using balphp's scan_dir function:
https://github.com/balupton/balphp/blob/765ee3cfc4814ab05bf3b5512b62b8b984fe0369/lib/core/functions/_scan_dir.funcs.php
scan_dir($dirPath, array('pattern'=>'image'));
Will return an array of all files that are images in that path and all subdirectories, using a $path => $filename structure. To turn off scanning subdirectories, set the recurse option to false
Please use the following code to read images from the folder.
function readDataFromImageFolder() {
$imageFolderName = 14;
$base = dirname(__FILE__);
$dirname = $base.DS.'images'.DS.$imageFolderName.DS;
$files = array();
if (!file_exists($dirname)) {
echo "The directory $dirname not exists.".PHP_EOL;
exit;
} else {
echo "The directory $dirname exists.".PHP_EOL;
$dh = opendir( $dirname );
while (false !== ($filename = readdir($dh))) {
if ($filename === '.' || $filename === '..') continue;
$files[] = $dirname.$filename;
}
uploadImages( $files );
}
}
Please click here for detailed explanation.
http://www.pearlbells.co.uk/code-snippets/read-images-folder-php/
You can use OPP oriented DirectoryIterator class.
foreach (new DirectoryIterator(IMAGEPATH) as $fileInfo) {
// Removing dots
if($fileInfo->isDot()) {
continue;
}
// You have all necessary data in $fileInfo
echo $fileInfo->getFilename() . "<br>\n";
}
while (($file = readdir($handle)) !== false) {
if (
($file == '.')||
($file == '..')
) {
continue;
}
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}
I have a folder structure like this:
/articles
.index.php
.second.php
.third.php
.fourth.php
If I'm writing my code in second.php, how can I scan the current folder(articles)?
Thanks
$files = glob(dirname(__FILE__) . "/*.php");
http://php.net/manual/en/function.glob.php
foreach (scandir('.') as $file)
echo $file . "\n";
From the PHP manual:
$dir = new DirectoryIterator(dirname($path));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
<?php
$path = new DirectoryIterator('/articles');
foreach ($path as $file) {
echo $file->getFilename() . "\t";
echo $file->getSize() . "\t";
echo $file->getOwner() . "\t";
echo $file->getMTime() . "\n";
}
?>
From The Standard PHP Library (SPL)
It depends on what you mean by 'scan' I'm assuming you want to do something like this:
$dir_handle = opendir(".");
while($file = readdir($dir_handle)){
//do stuff with $file
}
try this
$dir = glob(dirname(__FILE__));
$directory = array_diff(scandir($dir[0]), array('..', '.'));
print_r($directory);
Scan current folder
$zip = new ZipArchive();
$x = $zip->open($filepath);
if ($x === true) {
$zip->extractTo($uploadPath); // place in the directory
$zip->close();
$fileArray = scandir($uploadPath);
unlink($filepath);
}
foreach ($fileArray as $file) {
if ('.' === $file || '..' === $file)
continue;
if (!is_dir("$file")){
//do stuff with $file
}
}
List all images inside a folder
$dir = glob(dirname(__FILE__));
$path = $dir[0].'\\images';
$imagePaths = array_diff( scandir( $path ), array('.', '..', 'Thumbs.db'));
?>
<ul style="overflow-y: auto; max-height: 80vh;">
<?php
foreach($imagePaths as $imagePath)
{
?>
<li><?php echo '<img class="pagina" src="images/'.$imagePath.'" />'; ?></li>
<?php
}
?>
</ul>