The code works perfectly. Just don't know how to get it to display the content randomly without using Jquery.
Got it to display a random image from the current directory, but not sure how to get the directory to display randomly.
$dir = 'img/series_thumbnail/';
$dh = opendir($dir);
while (($fileName = readdir($dh)) !== false) {
if (!in_array($fileName, array('.', '..'))) {
$images = glob($dir . $fileName . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$imgMax = count($images)-1;
$imgNum = rand(0, $imgMax);
$imgUrl = $images[$imgNum];
echo '<li>';
echo '<img src="' . $imgUrl . '"/>';
echo '<div class="info"><p>' . $fileName . '</p></div>';
echo '</li>';
}
}
Thank you.
EDIT
Figured it out! Thanks for your help everyone.
$dir = glob("img/series_thumbnail/*", GLOB_ONLYDIR);
shuffle($dir);
foreach ($dir as $folder) {
if (!in_array($folder, array(".", ".."))) {
$folderName = basename($folder).PHP_EOL;
$images = glob($folder . "/*.{jpg,jpeg,png,gif}", GLOB_BRACE);
shuffle($images);
echo "<li>";
echo '<img src="' . $images[0] . '"/>';
echo "<div class='info'><p>" . $folderName . "</p></div>";
echo "</li>";
}
}
If you want to display a single random image from each directory, with the directories in random order, you can use this code:
$dir = 'img/series_thumbnail/';
$directories = glob("$dir*", GLOB_ONLYDIR);
shuffle($directories);
foreach ($directories as $directory) {
$images = glob($dir . $directory. '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$imgMax = count($images)-1;
$imgNum = rand(0, $imgMax);
$imgUrl = $images[$imgNum];
echo '<li>';
echo '<img src="' . $imgUrl . '"/>';
echo '<div class="info"><p>' . $fileName . '</p></div>';
echo '</li>';
}
Related
I am displaying a number of random images from a folder, however I'm not very good with PHP (Code sourced from the internet), how would I go about having a "download" link display on top of the image?
Display random image from folder using PHP:
function random_image($directory)
{
$leading = substr($directory, 0, 1);
$trailing = substr($directory, -1, 1);
if($leading == '/')
{
$directory = substr($directory, 1);
}
if($trailing != '/')
{
$directory = $directory . '/';
}
if(empty($directory) or !is_dir($directory))
{
die('Directory: ' . $directory . ' not found.');
}
$files = scandir($directory, 1);
$make_array = array();
foreach($files AS $id => $file)
{
$info = pathinfo($dir . $file);
$image_extensions = array('jpg', 'jpeg', 'gif', 'png', 'ico');
if(!in_array($info['extension'], $image_extensions))
{
unset($file);
}
else
{
$file = str_replace(' ', '%20', $file);
$temp = array($id => $file);
array_push($make_array, $temp);
}
}
if(sizeof($make_array) == 0)
{
die('No images in ' . $directory . ' Directory');
}
$total = count($make_array) - 1;
$random_image = rand(0, $total);
return $directory . $make_array[$random_image][$random_image];
}
Markup:
echo "<img src=" . random_image('css/images/avatars') . " />";
I've tried looking around google for an answer but I can't find anything, any help would be appreciated
You should save the image location in a variable then use it to create a link, plus display it.
$imageUrl = random_image('css/images/avatars');
echo "<a href=" . $imageUrl . ">";
echo "<img src=" . $imageUrl . " />";
echo "</a>";
or if you want to show the text link above, seperately then
$imageUrl = random_image('css/images/avatars');
echo "Click Here<br />";
echo "<img src=" . $imageUrl . " />";
you could use simple javascript to do so, like onclick event for example :
just add this to img tag onclick='window.open('". random_image('css/images/avatars') ."')'
echo "<img onclick='window.open('". random_image('css/images/avatars') ."')' src='" . random_image('css/images/avatars') . "' />";
Code:
$files = array();
$dir = new DirectoryIterator($directory);
foreach ($dir as $fileinfo) {
$files[$fileinfo->getMTime()] = $fileinfo->getFilename();
}
//krsort will sort in reverse order
krsort($files);
foreach($files as $file){
if ($file == "." or $file == ".." or $file == "thumbs" or $file == "Thumbs.db" or strpos($file, '.') == TRUE){
}else{
if (file_exists($directory.$file.'/zconfirmed.txt')){
echo '<script>console.log("display_subdirectories.php says: '.$directory.$file.'/zconfirmed.txt");</script><li class=""><a class="w3-btn w3-green" href="' .$URL.$file. '" >' .$file. '</a></li>';
}
else{
echo '<script>console.log("display_subdirectories.php says: '.$directory.$file.'");</script><li class="bold"><a class="w3-btn w3-red" href="' .$URL.$file. '" >' .$file. '</a></li>';
}
}
}
Here's My problem. If there is only 1 directory that has the zconfirmed.txt file in it, it doesn't appear when I iterate through the array. If there are 2 or more, it works just fine. Anybody have an answer or even something I can do to better troubleshoot this code?
I'm just trying to list the directories in the order of their last modified date/time.
Thank you guys so much for the help!
You are already storing the filename in the array couldn't you change your foreach loop to something simpler like
foreach($files as $file) {
if ($file == "zconfirmed.txt") {
echo '<script>console.log("display_subdirectories.php says: '.$directory.$file.'/zconfirmed.txt");</script><li class=""><a class="w3-btn w3-green" href="' .$URL.$file. '" >' .$file. '</a></li>';
}
}
This seems to be working:
echo '<div id="subdirectories"><h3>Subdirectories:</h3><ul>';
$files = scandir($directory);
$dir = array();
foreach ($files as $file){
if (checkDirectory($file) == true){
$filetime = filemtime($directory.$file);
$filename = $file;
$dir[$filetime] = $filename;
}
}
ksort($dir);
$files = $dir;
foreach ($files as $time=>$file){
$contiansPhotos = FALSE;
$path = $directory.$file;
$dirs = glob($path.'/{zconfirmed.txt}', GLOB_BRACE);
foreach($dirs as $dir) {
$contiansPhotos = TRUE;
}
if($contiansPhotos === TRUE){
echo '<li class=""><a class="w3-btn w3-green" href="' .$URL.$file. '" >' .$file. '</a></li>';
}
}//foreach $files as $file;
foreach ($files as $time=>$file){
$contiansPhotos = FALSE;
$path = $directory.$file;
$dirs = glob($path.'/{zconfirmed.txt}', GLOB_BRACE);
foreach($dirs as $dir) {
$contiansPhotos = TRUE;
}
if($contiansPhotos === FALSE){
echo '<li class="bold"><a class="w3-btn w3-red" href="' .$URL.$file. '" >' .$file. '</a></li>';
}
}//foreach $files as $file;
echo '</ul></div>';
I have 110 PDF. These are named 001.pdf, 002.pdf [...] 110.pdf. I created all the thumbnail in JPG, called 001.jpg etc.
I created a table in PHP (below).
all the JPG are in ./files/alon/
all the PDF are in ./files/alon/pdf/
So
<img src=".' . $images . $file . '" />
is fine and everything works, but
<td align="center"><a href="' . $images . $big . $file . '">
is not working because $file is looking for 001.jpg in /pdf/ folder.
i need something like
<td align="center"><a href="' . $images . $big . $filename . '.pdf">
i would linke to use the same $filename to create a caption under every image
"N° $filename"
here's my code
$images = "./files/alon/";
$big = "pdf/";
$cols = 2;
if ($handle = opendir($images)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != rtrim($big,"/")) {
$files[] = $file;
rsort($files);
}
}
closedir($handle);
}
$colCtr = 0;
echo '<table width="100%" cellspacing="3"><tr>';
foreach($files as $file)
{
if($colCtr %$cols == 0)
echo '</tr><tr><td colspan="2"><hr /></td></tr><tr>';
echo '<td align="center"><img src=".' . $images . $file . '" /></td>';
$colCtr++;
}
echo '</table>' . "\r\n";
Why don't you replace extension of the file .jpg -->> .pdf in a foreach($files as $file) where you echo stuff on screen ?
foreach($files as $file)
{
$arrPDF = explode(".",$file);
$pdfFile=$arrPDF[0]. ".pdf";
if($colCtr %$cols == 0)
echo '</tr><tr><td colspan="2"><hr /></td></tr><tr>';
echo '<td align="center"><img src=".' . $images . $file . '" /></td>';
$colCtr++;
}
how to folder sortout by time example i create last/latest folder in directory so last folder show on top.
here is code to show directory only
<?php
function folderlist(){
$startdir = './';
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
echo '<li><font face="Tahoma" class="ws10"><B>' . $name . '</B><br /></li>';
}
?>
To do that, you'll need to first grab the created time for the folder, and add that as the start of the key for the array item, then you'll be able to sort based on the key... something like this
<?php
function folderlist(){
$directorylist = array();
$startdir = './';
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$created = filectime($startdir . $folder);
$directorylist[$created . $startdir . $folder]['name'] = $folder;
$directorylist[$created . $startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
ksort($directorylist);
return($directorylist);
}
$folders = folderlist();
$total_files = 0;
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
$count = iterator_count(new DirectoryIterator($path . $name));
$total_files += $count;
echo '<li>';
echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $total_files;
?>
Note the new $created variable in use, and also the ksort() method being used to sort the array by its key.
You could sort in reverse order ising krsort.
You could also change the ordering to be based on the modified date, by using filemtime() instead of filectime()
The following code counts the number of files inside a folder.
<?php
function folderlist(){
$directoryist = array();
$startdir = './';
//get all image files with a .jpg extension.
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
$total_files = 0;
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
$count = iterator_count(new DirectoryIterator($path . $name));
$total_files += $count;
echo '<li>';
echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $total_files;
?>
However for some reason the count is off by 2. I have a folder with 13 files but this code returns count as 15. For an empty folder, this returns a count of 2.
Can someone point to me the issue with the above snippet?
I'm doing it with DirectoryIterator
$files_in_directory = new DirectoryIterator($path_to_folder);
$c = 0;
foreach($files_in_directory as $file)
{
// We want only files
if($file->isDot()) continue;
if($file->isDir()) continue;
$c++;
}
var_dump($c);
For use as function :
function folderlist($directories = array(), $extensions = array())
{
if(empty($directories))
return false;
$result = array();
$total_count = 0;
foreach($directories as $directory)
{
$files_in_directory = new DirectoryIterator($directory);
$c = 0;
foreach($files_in_directory as $file)
{
// We want only files
if($file->isDot()) continue;
if($file->isDir()) continue;
// This is for php < 5.3.6
$file_extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
// If you have php >= 5.3.6 you can use following instead
// $file_extension = $fileinfo->getExtension()
if(in_array($file_extension, $extensions)){
$c++;
$result['directories'][$directory]['files'][$c]['name'] = $file->getFilename();
$result['directories'][$directory]['files'][$c]['path'] = $file->getPath();
$result['directories'][$directory]['count'] = $c;
}
}
$total_count += $c;
}
$result['total_count'] = $total_count;
return $result;
}
Displaying results based on GET superglobal:
if(isset($_GET['album']) && !empty($_GET['album']) && !isset($_GET['listfiles']))
{
// We are in directory view mode
$album = $_GET['album'];
// View all directories and their file count for specified album
$view_directory = folderlist(array($album), array('jpeg', 'jpg', 'log'));
// Loop the folders and display them with file count
foreach ($view_directory['directories'] as $folder_name => $folder_files){
$count = $folder_files['count'];
echo '<li>';
echo '<a href="files.php?album=' . $folder_name . '&listfiles=1" class="style1">';
echo '<strong>' . basename($folder_name) . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $get_dir_info['total_count'];
}
elseif(isset($_GET['album'], $_GET['listfiles']) && !empty($_GET['album']))
{
// We are in file view mode for folder
$album = $_GET['album'];
// View all files in directory
$view_files = folderlist(array($album), array('jpeg', 'jpg', 'log'));
echo 'Showing folder content of: <b>'.basename($album).'</b>';
foreach($view_files['directories'][$album]['files'] as $file)
{
$path = $file['path'];
$name = $file['name'];
echo '<li>';
echo '<a href="files.php?file=' . $name . '&path=' . $path . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo '</a>';
echo '</li>';
}
}
This line is still returning the '.' and '..' vars.
if (!(array_search($folder,$ignoredDirectory) > -1))
see: http://php.net/manual/en/language.types.boolean.php
Try
if (!array_search($folder,$ignoredDirectory))
EDIT:
Also change this:
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
to
$ignoredDirectory = array( '.', '..' );