I need to get 15 random images from a folder and show them on a page:
I tried the following code, however it did not do what I wanted:
$string =array();
$filePath='wp-content/themes/tema/img-test/';
$dir = opendir($filePath);
while ($file = readdir($dir)) {
if (eregi("\.png",$file) || eregi("\.jpg",$file) || eregi("\.gif",$file) ) {
$string[] = $file;
}
}
while (sizeof($string) != 0){
$img = array_pop($string);
echo "<img src='$filePath$img' width='100px'/>";
}
So, you have all the files in $string array, that's good.
You can either use the rand() function to get some random integer in the arrays size:
$string = ['img1.jpg','img2.jpg','img3.jpg'];
$rand = rand(0,count($string)-1);
echo $string[$rand];
You would have to loop that.
Or, you could use array_rand() which will automate all that:
$string = ['img1.jpg','img2.jpg','img3.jpg'];
$amount = 3;
$rand_arr = array_rand($string, $amount);
for($i=0;$i<$amount;$i++) {
echo $string[$rand_arr[$i]] ."<br>";
}
You could do this using the glob() function native to PHP. It will get all files in a directory. Following that you can pick one file from the retrieved list.
$randomFiles = array();
$files = glob($dir . '/*.*');
$file = array_rand($files);
for ($i = 0; $i <= 15; $i++) {
$randomFiles[] = $files[$file];
}
Use this code. Your random image will be available in $arRandomFiles.
$filePath = 'wp-content/themes/tema/img-test/';
$files = glob($filePath. '*.{jpeg,gif,png}', GLOB_BRACE);
$arKeys = array_rand($files, 15);
$arRandomFiles = array();
foreach ($arKeys as $key) {
$arRandomFiles[] = $files[$key];
}
var_dump($arRandomFiles);
Simple function that handles that
<?php
function getImg( $path ) {
$filePath= $path . '*';
$imgs = glob( $filePath );
if( $imgs ) {
$i = 1;
foreach( $imgs as $img ) {
if( $i <= 15 ) {
$ext = pathinfo( $img, PATHINFO_EXTENSION );
if( in_array( $ext, array( 'jpg', 'jpeg', 'png', 'gif' ) ) )
$r[] = $img;
}
else
break;
$i++;
}
shuffle( $r );
return $r;
}
else
return array();
}
print_r( getImg( 'wp-content/themes/tema/img-test/' ) );
You can try function like:
function getRandomFile($directory)
{
$directoryIterator = new DirectoryIterator($directory);
$count = iterator_count($directoryIterator) - 2;
foreach ($directoryIterator as $fileInfo) {
$last = $fileInfo->getRealPath();
if ($fileInfo->isFile() && (rand() % $count == 0)) {
break;
}
}
return $last;
}
Related
I have a short PHP code to help me display random images from a specific folder. But now it seems to select any image in any size. I want those selected images are between 100-500 kb. If it's less than 100 kb or over 500 kb, the function won't select and display it.
Could you please tell me how to modify this code? Probably need to add some function.
<?php $randomdir = dir('images/random');
$count = 1;
$pattern="/(gif|jpg|jpeg|png)/";
while($file = $randomdir->read()) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (preg_match($pattern, $ext)) {
$imagearray[$count] = $file;
$count++;
}
}
$random = mt_rand(1, $count - 1);
echo '<img src="images/random/'.$imagearray[$random].'" alt />';
?>
Try this one We have to set 2 conditions
$min = 100; //KB
$max = 500; //KB
if($_FILES['myfile']['size'] < $min * 1024 || $_FILES['myfile']['size'] > $max * 1024){
echo 'error';
}
Try now
<?php
$dir_name = 'images/random/';
$pattern="/(gif|jpg|jpeg|png)/";
$min = 100;
$max = 500;
$imagearray = array();
$scanned_directory = array_diff(scandir($dir_name), array('..', '.'));
$count = count($scanned_directory);
$ids = array_keys($scanned_directory);
$s = TRUE;
$stop = $count;
while( ($s === TRUE) && ($stop >=0))
{
$random = mt_rand(0, $count - 1);
$full_path_to_file = $dir_name.$scanned_directory[$ids[$random]];
$ext = pathinfo($full_path_to_file, PATHINFO_EXTENSION);
$file_size_kb = round(filesize($full_path_to_file)/1024);
if (preg_match($pattern, $ext) && ($file_size_kb>=$min && $file_size_kb<=$max))
{
$s = FALSE;
echo '<img src="'.$full_path_to_file.'" alt />';
}
$stop--;
}
?>
How do we return the absolute path of largest file in a particular directory?
I've been fishing around and haven't turned up anything concrete?
I'm thinking it has something to do with glob()?
$sz = 0;
$dir = '/tmp'; // will find largest for `/tmp`
if ($handle = opendir($dir)) { // will iterate through $dir
while (false !== ($entry = readdir($handle))) {
if(($curr = filesize($dir . '/' . $entry)) > $sz) { // found larger!
$sz = $curr;
$name = $entry;
}
}
}
echo $dir . '/' . $name; // largest
$dir = 'DIR_NAME';
$max_filesize = 0;
$path= '';
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(realpath($dir),FilesystemIterator::SKIP_DOTS)) as $file){
if ($file->getSize() >= $max_filesize){
$max_filesize = $file->getSize();
$path = $file->getRealPath(); // get absolute path
}
}
echo $path;
function getFileSize($directory) {
$files = array();
foreach (glob($directory. '*.*') as $file) {
$files[] = array('path' => $file, 'size' => filesize($file));
}
return $files;
}
function getMaxFile($files) {
$maxSize = 0;
$maxIndex = -1;
for ($i = 0; $i < count($files); $i++) {
if ($files[$i]['size'] > $maxSize) {
$maxSize = max($maxSize, $files[$i]['size']);
$maxIndex = $i;
}
}
return $maxIndex;
}
usage:
$dir = '/some/path';
$files = getFileSize($dir);
echo '<pre>';
print_r($files);
echo '</pre>';
$maxIndex = getMaxFile($files);
var_dump($files[$maxIndex]);
I'm using the following to create a list of my files in the 'html/' and link path.
When I view the array it shows, for example, my_file_name.php
How do I make it so the array only shows the filename and not the extension?
$path = array("./html/","./link/");
$path2= array("http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/html/","http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/link/");
$start="";
$Fnm = "./html.php";
$inF = fopen($Fnm,"w");
fwrite($inF,$start."\n");
$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
$folder2 = opendir($path[1]);
$imagename ='';
while( $file2 = readdir($folder2) ) {
if (substr($file2,0,strpos($file2,'.')) == substr($file,0,strpos($file,'.'))){
$imagename = $file2;
}
}
closedir($folder2);
$result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n\n$file2\n<span class=\"glow\"><br></span>
</li>\n";
fwrite($inF,$result);
}
}
fwrite($inF,"");
closedir($folder);
fclose($inF);
pathinfo() is good, but I think in this case you can get away with strrpos(). I'm not sure what you're trying to do with $imagename, but I'll leave that to you. Here is what you can do with your code to compare just the base filenames:
// ...
$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
$folder2 = opendir($path[1]);
$imagename ='';
$fileBaseName = substr($file,0,strrpos($file,'.'));
while( $file2 = readdir($folder2) ) {
$file2BaseName = substr($file2,0,strrpos($file2,'.'));
if ($file2BaseName == $fileBaseName){
$imagename = $file2;
}
}
closedir($folder2);
$result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n\n$file2\n<span class=\"glow\"><br></span>
</li>\n";
fwrite($inF,$result);
}
}
I hope that helps!
I'm quite new to PHP so I'm still learning the very basics, however I'm trying to create an image gallery.
After countless Google searches later, I found a PHP script that does what I want it to do, and after looking at the code and manipulating it slightly it was working perfectly with my site; except that the images were not in alphabetical order.
This is the code
$max_width = 100;
$max_height = 100;
$imagedir = 'gifs/animals/'; //Remember trailing slash
function getPictureType($ext) {
if ( preg_match('/jpg|jpeg/i', $ext) ) {
return 'jpg';
} else if ( preg_match('/png/i', $ext) ) {
return 'png';
} else if ( preg_match('/gif/i', $ext) ) {
return 'gif';
} else {
return '';
}
}
function getPictures() {
global $max_width, $max_height, $imagedir;
if ( $handle = opendir($imagedir) ) {
$lightbox = rand();
echo '<ul id="pictures">';
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) ) {
$split = explode($imagedir, $file);
$ext = $split[count($split) - 1];
if ( ($type = getPictureType($ext)) == '' ) {
continue;
}
$name = substr($file, 0, -4);
$title = str_replace("_"," ",$name);
echo '<li><a href="'.$name.'">';
echo '<img src="thumbs/'.$file.'" class="pictures" alt="'.$file.'" />';
echo '</a>';
echo ''.$title.'';
echo '</li>';
}
}
echo '</ul>';
}
}
I've used the scandir() function which works in sorting them alphabetically, however I was left with an array. I then used the implode function to join the array together, however after that I was stuck with what to do.
Any help would be greatly appreciated!
Cheers.
You can use glob() to get the files from a directory, sorted alphabetically:
$files = glob('gifs/animals/*.{gif,jpg,png}', GLOB_BRACE);
To iterate over your files, use a foreach loop:
foreach($files as $file){
$title = str_replace("_"," ",$file);
echo '<li><a href="'.$name.'">';
echo '<img src="thumbs/'.basename($file).'" class="pictures" alt="'.basename($file).'" />';
echo '</a>';
echo ''.$title.'';
echo '</li>';
}
What's wrong with the arrays?
Also it would be better if you use pathinfo to obtain the filename and the extension.
$max_width = 100;
$max_height = 100;
$imagedir = 'gifs/animals/'; //Remember trailing slash
function getPictureType($ext) {
if ( preg_match('/jpg|jpeg/i', $ext) ) {
return 'jpg';
} else if ( preg_match('/png/i', $ext) ) {
return 'png';
} else if ( preg_match('/gif/i', $ext) ) {
return 'gif';
} else {
return '';
}
}
function getPictures() {
global $max_width, $max_height, $imagedir;
if ( $files = scandir($imagedir) ) {
$lightbox = rand();
echo '<ul id="pictures">';
foreach ($files as $file) {
$full_path = $imagedir.'/'.$file;
if ( !is_dir($file) ) {
$finfo = pathinfo($full_path);
$ext = $finfo['extension'];
if ( ($type = getPictureType($ext)) == '' ) {
continue;
}
$name = $finfo['filename'];
$title = str_replace("_"," ",$name);
echo '<li><a href="'.$name.'">';
echo '<img src="thumbs/'.$file.'" class="pictures" alt="'.$file.'" />';
echo '</a>';
echo ''.$title.'';
echo '</li>';
}
}
echo '</ul>';
}
}
The code below is part of a function for grabbing 5 image files from a given directory.
At the moment readdir returns the images 'in the order in which they are stored by the filesystem' as per the spec.
My question is, how can I modify it to get the latest 5 images? Either based on the last_modified date or the filename (which look like 0000009-16-5-2009.png, 0000012-17-5-2009.png, etc.).
if ( $handle = opendir($absolute_dir) )
{
$i = 0;
$image_array = array();
while ( count($image_array) < 5 && ( ($file = readdir($handle)) !== false) )
{
if ( $file != "." && $file != ".." && $file != ".svn" && $file != 'img' )
{
$image_array[$i]['url'] = $relative_dir . $file;
$image_array[$i]['last_modified'] = date ("F d Y H:i:s", filemtime($absolute_dir . '/' . $file));
}
$i++;
}
closedir($handle);
}
If you want to do this entirely in PHP, you must find all the files and their last modification times:
$images = array();
foreach (scandir($folder) as $node) {
$nodePath = $folder . DIRECTORY_SEPARATOR . $node;
if (is_dir($nodePath)) continue;
$images[$nodePath] = filemtime($nodePath);
}
arsort($images);
$newest = array_slice($images, 0, 5);
If you are really only interested in pictures you could use glob() instead of soulmerge's scandir:
$images = array();
foreach (glob("*.{png,jpg,jpeg}", GLOB_BRACE) as $filename) {
$images[$filename] = filemtime($filename);
}
arsort($images);
$newest = array_slice($images, 0, 5);
Or you can create function for the latest 5 files in specified folder.
private function getlatestfivefiles() {
$files = array();
foreach (glob("application/reports/*.*", GLOB_BRACE) as $filename) {
$files[$filename] = filemtime($filename);
}
arsort($files);
$newest = array_slice($files, 0, 5);
return $newest;
}
btw im using CI framework. cheers!