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
Related
I'm trying to generate images on my website by pulling a thumbnail from one folder and the actual image from another. I have no idea what I am doing. This is what I have so far:
<?php
$thumbdirname = "images/thumbs/";
$imgdirname = "images/";
$mainimages = glob($imgdirname."*.{jpg,png,gif}", GLOB_BRACE);
$imagethumbs = glob($thumbdirname."*.{jpg,png,gif}", GLOB_BRACE);
foreach($imagethumbs as $image) {
echo '<a class="imageLink" href="$mainimages" data-lightbox="logo" data-title="Vivid Logo"><img src="'.$image.'"</a> ';
}
?>
I know that it will not work with just "$mainimages" for href, but I haven't been able to figure out what to put there. As is, it will pull up the right thumbnail, but not link to the full associated image.
I tried to put another foreach statement in, but I get four results from my two pictures (and their thumbnails). Which makes sense sense it is showing one of each combination:
(img1,thumb1),(img1,thumb2),(img2,thumb1),(img2,thumb2)
How should I change this to get it playing nicely?
You don't seem to be outputting from $mainimages so I'm going to ignore this for now.
You PHP code seems to be OK from initial glance. Only thing that is a bit iffy is that you are not closing you image tag.
If that does not help try counting the image array/object.
If that returns 0 try the below code.
// Find all files in that folder
$files = glob('images/gallery1/*');
// Display images
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}
Hope that helps
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.
I am storing user uploaded files like pdf images and txt files in separate folders using my php script i want to retrieve the file names from the folder upload and give the pdf and txt in a group and also way to search for specific file.
I also need to rename the file before to $ja variable
$ja
$da = date("dmY");
$ja = $uid.$da;
move_uploaded_file($mi, $uploadpath)
also used this code which i found in stack
Example 01:
<?php
// read all files inside the given directory
// limited to a specific file extension
$files = glob("./ABC/*.txt");
?>
Example 02:
<?php
// perform actions for each file found
foreach (glob("./ABC/*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
the scandir(); function will help you
<?php
$dir = '/tmp';
$files1 = scandir($dir);
print_r($files1);
?>
http://www.php.net/manual/en/function.scandir.php
now you have array of all files in a location you specified you can use array functions to get your work done
you can try listing the directory with scandir, and then filter as you want in the php array of filenames you will get
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.