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.
Related
This is my code:
<?php
function recursive($directory){
$nr = 0;
$files = scandir($directory);
foreach($files as $file){
if($file == '.' || $file == '..') continue;
if(is_dir($file)){
echo $file.'<br>';
continue;
}
echo $file.' ----------<br>';
}
}
recursive('.');
?>
Basically I want the code at the bottom of the loop to be skipped until they are no more files in the directory.
How I want it to look:
How it looks:
A different take on your code but have you looked at the recursiveIterator family of classes? It's part of the php core and is pretty powerful.
$folder='c:/temp';
foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $folder, RecursiveDirectoryIterator::KEY_AS_PATHNAME ), RecursiveIteratorIterator::CHILD_FIRST ) as $file => $info ) {
if( $info->isFile() && $info->isReadable() && $info->isWritable() ){
echo $info->getFilename().'-------<br />';
} elseif( $info->isDir() ){
echo $info->getPath().'<br />';
}
}
I think you first need to list the directories, then the files. You can do that by changing a bit your function and running it twice:
function recursive($directory, $type){
$nr = 0;
$files = scandir($directory);
foreach($files as $file){
if($file == '.' || $file == '..') continue;
if(is_dir($file) && $type == 'dir'){
echo $file.'<br>';
} else if(!is_dir($file) && $type == 'file'){
echo $file.' ----------<br>';
}
}
}
recursive('.', 'dir');
recursive('.', 'file');
(By the way, although it's called "recursive", it doesn't do recursion)
Like this?
echo $file.'<br>';
if(is_dir($file) === false){
echo $file.' ----------<br>';
}
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() . '" />';
}
}
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>';
}
}
I read in many forums to remove the ampersand (&) before any $ listed in a variable, and I did, but doing so removes the functionality of the code I'm using. What should I do?
Demo here.
Code here:
<?php
$val = $_GET['name'];
$path = "./images/".$val."/";
$file_array = array ();
readThisDir ( $path, &$file_array );
echo '<div class="gallery" style="display:block;" id="'.$val.'">';
echo '<ul>';
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.'"/><span>'.$info['Title'].'<div class="gallerynav">«»</div></span></li>';
}
}
echo '</ul>';
echo '</div>';
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);
}
}
?>
You are supposed to mark the pass-by-reference in the function declaration, not where the function is called.
...
function readThisDir ( $path, &$arr )
{ ...
Change
function readThisDir ( $path, $arr )
To
function readThisDir ( $path, &$arr )
And
readThisDir ($path."/".$file, &$arr);
To
readThisDir ($path."/".$file, $arr);
PHP doesn't want you to pass the address of the variable directly to the function.
It doesn't answer your question directly, but you can replace all that code with the following (assuming 5.2+) using RecursiveDirectoryIterator:
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path);
);
$files = array();
foreach ($it as $file) {
$files[] = $file->getPathname();
}
Make the function readThisDir to return an array with the file info populated and assign that to the $file_array variable.
something like:
$file_array = readThisDir ($path);
function readThisDir ( $path)
{
$arr = array ();
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);
}
return $arr;
}
I have written this code having not used PHP for 2 years now to loop through a folder of photos and write them to the page in alphabetical order. It is a fairly simple request but it took me the best part of 15 minutes to write.
if ($handle = opendir('photos')) {
$count = 0;
$list[] = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$list[$count] = $file;
$count ++;
}
}
closedir($handle);
asort($list);
$sorted_list = array();
$sorted_list = array_values($list);
foreach ($sorted_list as $i => $value) {
echo "<li><img src=\"photos/$sorted_list[$i]\" alt=\"$sorted_list[$i]\" title=\"\"></li>\n";
}
}
Have I written it totally the wrong way? Are there ways I can improve the code? Any constructive feedback gladly received.
You could take advantage of the scandir() function, which will handle reading the directory as well as sorting the results.
$files = scandir('photos');
if ($files !== false)
{
foreach($files as $f) {
if ($f == '..' || $f == '.') continue;
echo '<li><img src="photos/'.$f.'" alt="'.$f.'" title=""></li>'."\n";
}
}
I edited it a bit for readability.
Try this:
$photos = glob('photos/*');
foreach($photos as $photo) {
echo "<li><img src=\"{$photo}" alt=\"{$photo}\" title=\"\"></li>\n";
}
http://us.php.net/manual/en/function.glob.php
You don't need the $count. This will give you the same result
$list[] = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$list[] = $file;
}
}
Replace sorting and displaying with just:
sort($list);
for ($i = 0; $i < count($list); $i++) {
echo "<li><img src=\"photos/{$list[$i]}\" alt=\"{$list[$i]}\" title=\"\"></li>\n";
}
You can replace
foreach ($sorted_list as $i => $value) {
echo "<li><img src=\"photos/$sorted_list[$i]\" alt=\"$sorted_list[$i]\" title=\"\"></li>\n";
}
with
foreach ($sorted_list as $value) {
echo "<li><img src=\"photos/$value\" alt=\"$value\" title=\"\"></li>\n";
}
Then you don't need to call array_values(), because it doesn't matter that the array keys aren't in numeric order.
A simplier way is using the scandir function:
$dir = 'photos';
$files = array_diff( scandir($dir), array(".", "..") );
foreach ($files as $i => $value) {
echo "<li><img src=\"photos/$value\" alt=\"$value\" title=\"\"></li>\n";
}
good luck!