Sort alphabetically with opendir() - php

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>';
}
}

Related

Sort array by time only on image echos

I'm trying to sort these echo results by using only time, and I can't seen to find a way to read when was the image placed on the folder (to sort them by the specific time).
<?php
$all_files = glob(DIR_PATH."*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
$supported_format = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format))
{
echo '<div class="col" ><img src="/led/images/autoplay/'.str_replace(DIR_PATH,'',$image_name) .' " /><div align="center"><br />Delete</div><br /></div>';
} else {
continue;
}
}
?>
Maybe using usort() and filetime() function:
$files = glob(DIR_PATH."*.*");
usort( $files, function( $a, $b ) {
return filemtime($a) - filemtime($b);
} );
foreach ($files as $file) {
$image_name = $file;
$supported_format = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format))
{
echo '<div class="col" ><img src="/led/images/autoplay/'.str_replace(DIR_PATH,'',$image_name) .' " /><div align="center"><br />Delete</div><br /></div>';
} else {
continue;
}
}

How to get 15 random images from a folder in Wordpress?

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;
}

Insert Images from folder and subfolder php

Im trying to insert into html all images that are on the folder "assets/imagens/" and on any subfolders. I also need help to validate not to echo the subfolders.
Im using the code below:
$path = "assets/imagens/";
$diretorio = dir($path);
while($arquivo = $diretorio -> read()){
if($arquivo != '.' && $arquivo != '..'){
echo '<div href="#" class="list-group-item">';
echo '<span class="close-button" secao="imagens">x</span>';
echo "<img class='max-width' src='".base_url().$path.$arquivo."' />";
echo '</div>';
}
}
$diretorio -> close();
$path = "assets/imagens/";
echo_directory_images($path);
function echo_directory_images($path)
{
$diretorio = dir($path);
while($arquivo = $diretorio -> read()){
if($arquivo != '.' && $arquivo != '..'){
if( is_dir($path.$arquivo))
{
//if subfolder
echo_directory_images($path.$arquivo.'/')
}
else{
echo '<div href="#" class="list-group-item">';
echo '<span class="close-button" secao="imagens">x</span>';
echo "<img class='max-width' src='".base_url().$path.$arquivo."' />";
echo '</div>';
}
}
}
}
You may want to give a try to this function. I doubt if this will work exactly but this will surely give an idea about how to recursively call folders and subfolders.
Try this :
function listDir( $path ) {
global $startDir;
$handle = opendir( $path );
while (false !== ($file = readdir($handle))) {
if( substr( $file, 0, 1 ) != '.' ) {
if( is_dir( $path.'/'.$file ) ) {
listDir( $path.'/'.$file );
}
else {
if( #getimagesize( $path.'/'.$file ) ) {
/*
// Uncomment if using with the below "pic.php" script to
// encode the filename and protect from direct linking.
$url = 'http://domain.tld/images/pic.php?pic='
.urlencode( str_rot13( substr( $path, strlen( $startDir )+1 ).'/'.$file ) );
*/
$url='http://localhost/'.$path.'/'.$file;
substr( $path, strlen( $startDir )+1 ).'/'.$file;
// You can customize the output to use img tag instead.
echo "<a href='".$url."'>".$url."</a><br>";
echo "<img class='max-width' src='".$url."' />";
}
}
}
}
closedir( $handle );
} // End listDir function
$startDir = "assets/imagens/";
listDir( $startDir );
You can use RecursiveDirectoryIterator.
For example:
$directory = new RecursiveDirectoryIterator('assets/imagens');
$iterator = new RecursiveIteratorIterator($directory);
foreach ($entities as $name => $entity) {
if ($entity->isDir()) {
continue;
}
$extension = pathinfo($name, PATHINFO_EXTENSION);
if ($extension == 'jpg' || $extension == 'png' || $extension == 'gif') {
echo '<img src="' . $entity->getPathname() . '" />';
}
}

Add EXIF Title to PHP Gallery

I have the following code now, and I want to simply add the EXIF Title data where the "CAPTION" text is. How do I do that? I know how to get the data, but I'm not sure how to add it to the "foreach" loop I already have going.
<?php
$path = "./images/bettydew/";
$file_array = array ();
readThisDir ( $path, &$file_array );
echo '<ul class="gallery">';
foreach ( $file_array as $file )
{
if (strstr($file, "png")||strstr($file, "jpg")||strstr($file, "bmp")||strstr($file, "gif"))
{
echo '<li><img src="'.$file.'" alt="'.$file.'"/></li>';
}
}
echo '</ul>';
function readThisDir ( $path, $arr )
{
if ($handle = opendir($path))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
if (is_dir ( $path."/".$file ))
{
readThisDir ($path."/".$file, &$arr);
} else {
$arr[] = $path."/".$file;
}
}
}
closedir($handle);
}
}
?>
Replace the foreach loop with this:
foreach ( $file_array as $file )
{
if (strstr($file, "png")||strstr($file, "jpg")||strstr($file, "bmp")||strstr($file, "gif"))
{
list($width, $height) = getimagesize($file);
$info = exif_read_data($file);
echo '<li><img src="'.$file.'" width="'.$width.'" height="'.$height.'" alt="'.$file.'"/>'.$info['Title'].'</li>';
}
}
this code is my answer to Steve's other SO answer #Steve - Please try harder.

PHP: Sorting array with natsort

I have a PHP script that creates a thumbnail and lists an image gallery. The problem I'm having is that it lists it by timestamp on the server but I want it to list 'naturally'.
<?php
# SETTINGS
$max_width = 100;
$max_height = 100;
$per_page = 24;
$page = $_GET['page'];
$has_previous = false;
$has_next = false;
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir(".") ) {
$lightbox = rand();
echo '<ul id="pictures">';
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
if ( ! is_dir('thumbs') ) {
mkdir('thumbs');
}
if ( ! file_exists('thumbs/'.$file) ) {
makeThumb( $file, $type );
}
echo '<li><a href="'.$file.'" class="zoom" rel="group">';
echo '<img src="thumbs/'.$file.'" alt="" />';
echo '</a></li>';
$count++;
}
}
echo '</ul>';
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}
function getPictureType($file) {
$split = explode('.', $file);
$ext = $split[count($split) - 1];
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 makeThumb( $file, $type ) {
global $max_width, $max_height;
if ( $type == 'jpg' ) {
$src = imagecreatefromjpeg($file);
} else if ( $type == 'png' ) {
$src = imagecreatefrompng($file);
} else if ( $type == 'gif' ) {
$src = imagecreatefromgif($file);
}
if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
$newW = $oldW * ($max_width / $oldH);
$newH = $max_height;
} else {
$newW = $max_width;
$newH = $oldH * ($max_height / $oldW);
}
$new = imagecreatetruecolor($newW, $newH);
imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
if ( $type == 'jpg' ) {
imagejpeg($new, 'thumbs/'.$file);
} else if ( $type == 'png' ) {
imagepng($new, 'thumbs/'.$file);
} else if ( $type == 'gif' ) {
imagegif($new, 'thumbs/'.$file);
}
imagedestroy($new);
imagedestroy($src);
}
?>
similair to hobodave but i would use php's built in natsort function:
uksort($output, "strnatcmp");
You're not even using an array.
Instead of echo'ing your li's as you encounter them you need to put them into an array, indexed by filename.
$output[$file] = '<li>etc</li>';
Then once your loop has completed, you'll need to use a custom function to do a natural key sort, since PHP's natsort() only works on values.
function natksort($array) {
$keys = array_keys($array);
natsort($keys);
$ret = array();
foreach ($keys as $k) {
$ret[$k] = $array[$k];
}
return $ret;
}
$output = natksort($output);
echo '<ul>';
foreach ($output as $out) {
echo $out;
}
echo '</ul>';
Edit
Wow, I found this little gem to do the sorting:
uksort($array, 'strnatcasecmp');
Credit: http://www.chipstips.com/?p=269
The trick was to put everything inside an array... I took the liberty of rewriting your getPictures() function... This one implements the sorting.
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if (!is_dir('thumbs')) {
mkdir('thumbs');
}
if ($handle = opendir(".")) {
$lightbox = rand();
$files = array();
while (($file = readdir($handle)) !== false) {
if (!is_dir($file) && ($type = getPictureType($file)) != '') {
$files[] = $file;
}
}
natsort($files);
$has_previous = $skip != 0;
$has_next = (count($files) - $skip - $per_page) > 0;
$spliceLength = min($per_page, count($files) - $skip);
$files = array_slice($files, $skip, $spliceLength);
echo '<ul id="pictures">';
foreach($files as $file) {
if (!file_exists('thumbs/' . $file)) {
$type = getPictureType($file);
makeThumb($file, $type);
}
echo '<li><a href="' . $file . '" class="zoom" rel="group">';
echo '<img src="thumbs/' . $file . '" alt="" />';
echo '</a></li>';
}
echo '</ul>';
}
}

Categories