I have a PHP script written to grab all images in a certain directory and display them, although I want to have the ability to display images also in sub directories of the directory I specified.
So for example right now my script is only getting the following images
uploads/prevImgs/145323.png
uploads/prevImgs/276531.png
Where id want it to get the following
uploads/prevImgs/145323.png
uploads/prevImgs/276531.png
uploads/prevImgs/dir1/12323.png
uploads/prevImgs/dir2/212331.png
My current script is the following
<?php
// Directory Path Of Library Preview Images //
$dirname = "uploads/prevImgs/";
$images = glob("{$dirname}*.*");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
?>
Huge thanks in advance!!!
You can stack a RecursiveDirectoryIterator and an RecursiveIteratorIterator to get the effect you're looking for:
$rdi = new RecursiveDirectoryIterator("uploads/prevImgs/");
$it = new RecursiveIteratorIterator($rdi);
foreach($it as $oneThing)
if (is_file($oneThing))
echo '<img src="'.$oneThing.'" /><br />';
I know, it seems counter-intuitive that you have to take RecursiveDirectoryIterator and stack another iterator on top of it to make it work. The documentation in this area could be better.
I can suggest to use a RecursiveDirectoryIterator for creating a class to iterate through Files of (sub)directories and its files. Together with one of the recursive filter iterators php offers you can only return only image files.
There is a GlobIterator too but I'm not sure if it also do recursive iterations.
Related
I have been told to rewrite my question by Stackoverflow
I upload images mostly to a directory on my sever where my website is hosted. Via a program on my PC and a app on phone and that works a treat.
I have come across PHP scripts that shows all the images in the above folder and returns a basic gallery, and they all work to a point.
What I am hoping to achieve (it might not be possible) is list the images by the date they were added to the server. Not sorting from the EXIF modified date.
If it cant be done, so be it.
Best regards,
RT
PS At the moment I'm use PHP Gallery, its OK but does not quite achive the sorting requirement I would like.
Gallery here. https://www.sidingstudios.com/pix4web/index.php
Is it possible to display the contents of server folder (images) but sort by Last Modified ? using PHP
My very basic script:
<?php
$images = glob('img/*');
foreach ($images as $image) {
echo '<img src="'.$image.'"><br>';
}
?>
Link its used on. https://www.sidingstudios.com/pix4web2/
This will sort the images by last modified time
$files = glob('img/*');
$output = [];
foreach ($files as $f)
{
$output[filemtime($f)] = $f;
}
ksort($output);
$images = array_reverse($output);
foreach ($images as $image)
{
echo '<img src="' . $image . '"><br />';
}
I'm creating a method that will inspect files in an upload folder and some of these files are archive (tar, tar.gz, zip, rar, etc). I would like to read these archive files and list all files in a nested tree format.
For example, I have an archive file called sandwich.tar.gz, I would like it to be listed as below:-
sandwich.tar.gz
lettuce
mayonaise
cheese
bread (directory)
wholemeal
My code thus far:-
<?php $archive = new PharData('/upload/directory/sandwich.tar.gz');
foreach($archive as $file) {
echo $file . "<br />";
}
But it failed to list files inside the bread directory. How do I fix this?
You can do this using a RecursiveIteratorIterator, because PharData extends the Phar class and the Phar class extends the RecursiveDirectoryIterator class:
$archive = new PharData('/upload/directory/sandwich.tar.gz');
foreach (new RecursiveIteratorIterator($archive) as $file) {
echo $file . "<br />";
}
Although this question is rather dated, considering the stupidity and the uselessness of the previous answer, I cannot but reply.
It seems whatever PHP does is always non-standard and awkward at best...
You got it right to inspect the first level. However, the objects returned from the iteration are not of the same type, thus calling foreach on them will lead to failure.
Iterating on a PharData object gives you PharFileInfo ones. From there you can check for the file type (checking if it is a directory with the inherited isDir() method).
From there, you will need to create another PharData object on the path to the resource obtained from the (also inherited) getPathname() (sic, not getPathName() say the docs!) method. You will then be able to iterate over it...
Full example:
<?php
$archive = new PharData('/upload/directory/sandwich.tar.gz');
foreach($archive as $file) {
echo $file;
if($file->isDir()) {
echo ':';
$dir = new PharData($file->getPathname());
foreach($dir as $child) {
echo "<br />$child";
}
}
echo "<br />";
}
?>
Of course, that kills easy recursion if you have multiple levels in your archive. You will have to cook your own recursive crawler...
Some advice that I was given once, and think about often, comes to mind: code will do EXACTLY what you ask it to do: nothing more, nothing less.
Ask the machine: 'if this is a directory, please display the contents?'
Your function thinks that it is looking for a $file, and thus outputs the name of that file.
Consider http://php.net/manual/en/function.readdir.php and http://www.php.net/manual/en/function.is-dir.php
I've been struggling with this for a while now.
I've got an image gallery running using jQuery cycle plugin and the files are pulled from a folder using PHP glob(). Problem is, when I navigate to another page the gallery breaks due to the url of the new page being tacked on at the beginning of the file path.
Example:
Front Page url: http://localhost/project/image-display-images/image.jpg
Other Page url: http://localhost/**NEWPAGE**/project/image-display-images/image.jpg
Here's my code:
$files = glob('image-display-images/*.*');
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'"'.' alt="Campus Images" width="362" height="246"/>';
}
This would generate a list of images for jQuery cycle to scroll through. It only works on the front page though.
Any ideas?
SOLVED!
Here is my new code:
$files = glob(ABSPATH.'/image-display-images/*.*');
foreach ($files as $f) {
echo '<image src="'.home_url(str_replace(ABSPATH,'',$f)).'"alt="Campus Images" width="362" height="246"/>';
}
This works on all pages.
Thank you!
Use an absolute path:
$files = glob(ABSPATH.'image-display-images/*.*');
The WordPress Core sets the ABSPATH constant so it should be fairly reliable.
glob deals with filesystem paths, but you are trying to load URLs. To display the files the way you are trying to, you will need to convert the results to URLs. Here is a bare-bones example.
$files = glob(ABSPATH."*.*");
foreach ($files as $f) {
echo home_url(str_replace(ABSPATH,'',$f));
}
You may better off writing you own function to grab your file names, rather than depending on glob which does come with a warning about not being available on some systems. See: http://codex.wordpress.org/Filesystem_API
Define the full path of your gallery instead of 'image-display-images/*.*'
For example glob('/var/etc/www/image-display-images/*.*')
I have a image folder which contains sub directory for each album of images like
Images
Images/Album1
Images/Album2
in PHP file
I create a link for each album using a thumbnail for the album using GLOB to read all folders under Images
$dir=glob('images/*');
$dir_listing=array();
foreach($dir as $list)
{
if(is_dir($list))
$dir_listing[]= (basename($list));
}
$thumbs=glob('images/thumbnails/*');
$count=0;
foreach($thumbs as $th )
{
echo" $dir_listing <br/>";
echo"<a href='$dir_listing[$count]' ><img src='$th' /> </a>";
$count++;
}
I use Glob on each page load to get list of directories and images.
I want to know if there is a better way of doing this.
I also want to get list of all files and folder based on there Last Modified time in descending Order {Latest files and Folders first}.
Is using Glob correct or should we save the sub-directories and files in text file and read from it?
I can't tell you for sure if there is a better way of doing this, but your code should definitely work.
Using glob() is the right approach only if you have a relatively low number of files in the directory (<10,000), because if yoy have a lot of files then you could get a "Allowed memory size of XYZ bytes exhausted ..." error. In this case, it is best to use opendir();
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
// do something with the file
// note that '.' and '..' is returned even
}
closedir($handle);
Finally, use the flag GLOB_NOSORT on glob() so the end result is just like its listed on the directory in case that may be used to give you results based on last modified date.
Hope this helps.
I'm trying to make a site where users can submit photos, and then randomly view others photos one by one on another page. I have a directory called "uploads" where the pictures are submitted. I'm having trouble reading the pictures from the file. I just want to randomly select a picture from the directory uploads and have it displayed on the page. Any suggestions appreciated.
You can use glob to get all files in a directory, and then take a random element from that array. A function like this would do it for you:
function random_pic($dir = 'uploads')
{
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
I've turned it a little to get more than one random file from a directory using array.
<?php
function random_pic($dir)
{
$files = glob($dir . '/*.jpg');
$rand_keys = array_rand($files, 3);
return array($files[$rand_keys[0]], $files[$rand_keys[1]], $files[$rand_keys[2]]);
}
// Calling function
list($file_1,$file_2,$file_3)= random_pic("images");
?>
You can also use loop to get values.
This single line of code displays one random image from the target directory.
<img src="/images/image_<?php $random = rand(1,127); echo $random; ?>.png" />
Target directory: /images/
Image prefix: image_
Number of images in directory: 127
https://perishablepress.com/drop-dead-easy-random-images-via-php/
Drawbacks
images must be named sequentially (eg image_1.png, image_2.png, image_3.png, etc).
you need to know how many images are in the directory in advance.
Alternatives
Perhaps there's a simple way to make this work with arbitrary image-names and file-count, so you don't have to rename or count your files.
Untested ideas:
<img src=<?php $dir='/images/'; echo $dir . array_rand(glob($dir . '*.jpg')); ?> />
shuffle()
scanDir() with rand(1,scanDir.length)
Or you can use opendir() instead of glob() because it's faster