I want to display 2 images with their created time to be displayed parallely in wordpress . So tried to write css (display flex) using 'echo' command . Although logic is correct but tag of the image is not working and there may be other syntactical error.As the beginners please review the code and help me.
In this below, if i close table tag before div it is not working properly.
<?php
$dir = opendir('/var/www/html/data1/products/images/avhrr/rgb');
$files = array();
while (($file = readdir($dir)) !== false)
{
if ($file == '.' || $file == '..' ) continue;
if (is_dir("/var/www/html/data1/products/images/avhrr/rgb/$file")) continue;
$lastModified = filemtime("/var/www/html/data1/products/images/avhrr/rgb/$file");
$files[$file] = $lastModified;
}
closedir($dir);
asort($files);
$files=array_reverse($files);
$count = 0;
foreach ($files as $file => $lastModified)
$name = basename($file);
$str = $name;
$pattern = "/top/i";
if(preg_match_all($pattern, $str, $matches))
{
$file_stats = stat("/var/www/html/data1/products/images/avhrr/rgb/".$name);
echo '<div class="container" style="display:flex">';
echo '<table border="5">';
echo '<tr><td>';
echo 'Daily_RGB : '.date('d-m-Y h:m:i A',$file_stats["mtime"]).PHP_EOL; //Equivalent of filemtime()
echo "<br>";
echo "<a href='/data1/products/images/avhrr/rgb/$file' target='_blank'></a>";
echo "<img src='/data1/products/images/avhrr/rgb/$file' height='450' width='450'/>";
echo '</td></tr>';
echo '</div>';
echo '</table>';
$count++;
}
if ($count == 2) break;
}
?>
I have successfully uploaded some images to the server. Im thinking to display them in my admin page in grid view.. currently it displayed vertically.
Can anyone help?
Thanks in advance for you kind assistance.
<?php
$dir_path = "../../img/gallery/";
$extensions_array = array('jpg','png','jpeg');
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
if($files[$i] !='.' && $files[$i] !='..')
{
// get file name
echo "File Name: $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
{
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'><br>
</br>";
}
}
}
}
?>
This code works fine but I just don't know to display it in grid or table..
You can achieve that by echoing each table part inside the loop:
<?php
$dir_path = "../../img/gallery/";
$extensions_array = array('jpg','png','jpeg');
$numCol = 3;
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
$n = 0;
echo '<table>';
echo '<tr>';
if($files[$i] !='.' && $files[$i] !='..')
{
$n ++;
// get file name
echo "<td>File Name: $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'></td>";
if($n % $numCol == 0) echo "</tr><tr>";
}
echo '</tr>';
echo '</table>';
}
}
?>
$numCol defines how many column must have every table's row.
Also, I removed these {} that were useless:
$extension = $file['extension'];
{
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'><br>
</br>";
}
I am using the following script for listing the files in a particular directory as a hyperlink list.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
echo "<li><a href='$files[$x]'>$files[$x]</a></li>";
}
Please tell us whether the following is possible
1. The file extension should not be displayed
2. I need " " instead of "-" in the file names
If possible how to incorporate it.
Update 2:
Thanks for your kindly help. I followed,
The files names which i have mentioned must not be displayed (like dont display index.php), How do i change the code for this?
<?php
$directory = '';
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", " ", $parts['filename']);
echo "<li>{$name}</li>";
}
?>
Try the following using glob in a loop.
$directory = 'folder/';
foreach (glob($directory . "*.*") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", "", $parts['filename']);
echo "{$name}";
}
Example with your provided code, two lines added pathinfo and a preg_replace.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
$parts = pathinfo($files[$x]);
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li><a href='$files[$x]'>$name</a></li>";
}
Updated:
The following doesn't show the files called index.php, wtf.php, and hide.php
$directory = 'folder/';
$blacklist = array(
'index',
'wtf',
'hide'
);
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
if (!in_array($parts['filename'], $blacklist)) {
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li>{$name}</li>";
}
}
how to use multiple different a href link on each different images? and images are getting from the `folder or directory?
Php Code
<?php
$directory = "data/uploads/bottomslider/";
if (glob($directory . "*") != false)
{
$filecount = count(glob($directory . "*"));
}
$files_index = glob("data/uploads/"."bottom"."slider/*.*");
for ($i=0; $i<$filecount; $i++)
{
$num2 = $files_index[$i];
?>
<li class="jcarousel-item"><a href=""><img src="<?php echo $num2;?>"
style="height: 119px!important; width:132px !important;"/></a></li>
<? }?>
For Example
i want like this?
Image1
Image2
Image2
I did not test the code. But this should work. Assuming that the folder "data" is in the root of your webpage.
$directory = "data/uploads/bottomslider/";
if(file_exists($directory)) {
$files = scandir($directory);
$output = "";
foreach($files as $key => $value) {
if($value != '.' && $value != '..' && $value != '.quarantine' && $value != '.tmb') {
$output .= '<li class="jcarousel-item"><a href="/'.$directory.$value.'"><img src="/'.$directory.$value.'"
style="height: 119px!important; width:132px !important;"/></a></li>';
}
}
//$output contains all the images.
echo $output;
}
<?php
$directory = "data/uploads/bottomslider/";
$link = "";
if (glob($directory . "*") != false)
{
$filecount = count(glob($directory . "*"));
}
$files_index = glob("data/uploads/"."bottom"."slider/*.*");
//this array must be same size like number of images
$array1 = array('www.yahoo.com', 'www.google.com', 'www.facebook.com', 'www.stackovrflow.com', 'www.blahblah.com');
for ($i=0; $i<$filecount; $i++)
{
$num2 = $files_index[$i];
$link = $array1[$i];
?>
<li class="jcarousel-item"><a href="<?php echo $link?>"><img src="<?php echo $num2;?>"
style="height: 119px!important; width:132px !important;"/></a></li>
<?php
}
?>
Give full path of link like "https://www.facebook.com/"
I'd like to randomly load images from a directory and have a button somewhere that refreshes the entire page. Here's the current code I have now:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
The problem is it loads all 400,000 images at once. I only want 30 to load. 30 random images from the directory. I tried looking up some code such as modifying the above to this:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
if (++$i == 2) break;
}
?>
But it seems to do absolutely nothing.. So if someone can help me get 30 random photos from that directory to load and have some type of reload button, that would be of great help.
Thank you in advance
Here is my solution with a cache:
<?php
define('CACHE_FILE', 'mycache.tmp');
define('CACHE_TIME', 20); // 20 seconds (for testing!)
define('IMG_COUNT', 30);
define('IMG_DIR', '../public/wp-content/uploads/2012/01');
/**
* Loads the list (an array) from the cache
* Returns FALSE if the file couldn't be opened or the cache was expired, otherwise the list (as an array) will be returned.
*/
function LoadListFromCache($cacheFile, $cacheTime)
{
if ( file_exists($cacheFile) )
{
$fileHandle = fopen($cacheFile, 'r');
if ( !$fileHandle )
return false;
// Read timestamp (separated by "\n" from the content)
$timestamp = intval( fgets($fileHandle) );
fclose($fileHandle);
// Expired?
if ( $timestamp+$cacheTime > time() )
return false;
else
{
// Unserialize the content!
$content = file_get_contents($cacheFile);
$content = substr( $content, strpos($content, "\n") );
$list = unserialize($content);
return $list;
}
}
return false;
}
/**
* Caches the passed array
* Returns FALSE if the file couldn't be opened, otherwise TRUE.
*/
function SaveListToCache($cacheFile, $list)
{
$fileHandle = fopen($cacheFile, 'w');
if ( $fileHandle === FALSE ) return false;
fwrite($fileHandle, time());
fwrite($fileHandle, "\n");
fwrite($fileHandle, serialize($list));
fclose($fileHandle);
return true;
}
/**
* Generates the list of all image files (png, jpg, jpeg) and caches it.
* Returns the list as an array.
*/
function GenerateList()
{
$a = array();
$dir = IMG_DIR;
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
SaveListToCache(CACHE_FILE, $a);
return $a;
}
function GetRandomImages($list, $count)
{
$listCount = count($list);
$randomEntries = array();
for ($i=0; $i<$count; $i++)
{
$randomEntries[] = $list[ rand(0, $listCount) ];
}
return $randomEntries;
}
// This code will execute the other functions!
$list = LoadListFromCache(CACHE_FILE, CACHE_TIME);
if ( $list === FALSE )
{
$list = GenerateList();
}
$images = GetRandomImages($list, IMG_COUNT);
foreach ($images as $image)
{
echo '<img src="', IMG_DIR.DIRECTORY_SEPARATOR.$image, '" />';
}
If you have 400,000 images then I think reading the entire directory everytime is going to be an expensive means of showing random images. I would use a database instead and store the file paths in it.
If you want to use your existing code then think of it this way. You have an array of length n containing image names. You want to generate thirty random numbers between 0 and n-1. Then display the image associated with that position in the array. I'm not a php expert, but here is some pseudocode:
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
for ( i=0; i < 30; i++) {
//generate a random number between 0 and N-1
random = rand(0, $a.length - 1);
//display that image in the array
echo "<img src='" . $dir . '/' . $a[random] . "' />";
}
You need to create a new variable for the counter instead of using $i
For example, you can do this instead
$j = 0;
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
$j++;
if ($j >= 30)
{
break;
}
}
EDIT: Perhaps for the random part you can first generate a random number between 0 and n-1 where n is the total number of the images and then just echo out the image from the array with the index number.
Instead of using foreach, I think you'll need a for loop instead.
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 30; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
You should maybe only read 30 file from your directory. Stop looking in the directory when readdir return false or your array's length is 30.
This should work
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle)) && (count($a) <= 30) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
It may not execute (I didn't try). But the idea is here
For randomize the image: shuffle($a) should do the trick
in simplest way ,
you can use
find , sort , head
commands in linux,in conjuction with PHP's built in
exec()
function to get 30 random image links easily , the folowing snippet lists how to do it
(How to get random 30 image links in an array.)
<?php
$picdir = "directory/containing/pictures"; // directory containing only pictures
exec("find " . $picdir . " | sort -R | head -30 ",$links);
while(list($index,$val) = each($links) ) {
echo "<img src =" .$val . "> <br/>"; // shows image
}
?>
Here $links array contain random 30 image names(from folder) with complete path . This is used with img tag in echo to generate images
Here $picdir has the path of the directory having images and it is assumed that dirrectory is having only image files . in other case its only matter of modifying find command to exclude non image files(such as using grep command to exclude )