Image gallery system with search engine using php - php

I am trying to make an image gallery system with keywords.
Each image has a .php file with a few variables:
$keywords = 'Keywords that describe the image';
$src = 'directory path leading to the image';
$other = 'any specific remarks about the image';
the files of each image are stored in a directory called imageinfo.
How can I get all the images listed in the files in the directory imageinfo to display in one .phpfile? They all have the same variable names. Can I make a search engine system to search the files?
This is very hard to explain, and I understand if you don't understand - feel free to grab a diet coke and come and write your problems in the comments!

Try this:
(you have to fille the right imageinfo folder in)
<?php
// Folder with all the Info PHP files
$infodir = __DIR__ .'/imageinfo/';
// read Folder contens
$files = scandir( $infodir );
// Array to store all image infos
$allimages = array();
// loop, file for file
foreach ($files as $file) {
// . and .. are in the array of files, but we don't need them
if( $file != '..' && $file != '.' ){
//path to actual Image Info file
$thisfile = $infodir.'/'.$file;
//Check if file exists
if( is_file( $thisfile ) ){
//parse file
include( $thisfile );
//add vars to Array
$allimages[] = array(
'keywords' => $keywords,
'src' => $src,
'other '=> $other
);
}
}
}
//Output Data of all files
echo '<pre>';
print_r( $allimages );
echo '<pre>';
//show images in browser
foreach ($allimages as $image ) {
echo '<div class="img">';
echo '<img src="'.$image['src'].'" title="" alt="" >';
echo '<br />';
echo $image['keywords'];
echo '<br />';
echo $image['other'];
echo '</div>';
}
?>

Related

PHP GLOB skips the first image in each folder

I am trying to understand why GLOB is skipping the first image in whatever folder I direct it too. I work around it by placing a dummy image named so it is listed first but I would like to solve this irk in a more efficient way. Here is my code.
<?php
// This retrieves images from a selected folder - anchor with a data-xx-xx attribute
// via jQuery - click - the data-xx-x value is put into a hidden field : foldpath
// It all works fine BUT, it always fails to return the first image in a folder
// I get around it by placing within each folder a dummy image called aa.jpg
// which hopefully will always be the first image but it is not really a
// satisfactory solution.
if($_POST && isset($_POST["foldsub"]) && isset($_POST["foldpath"]) ){
// hidden field $_POST["foldpath"];
//A typical path might be :
// ../images/products/CLIENTS_images/bridal_whatnots/bridal_belts
//the ../ prefix is reoved via php when the page is displayed and replaced by DIR
// for testing between admin folders and the main root folders I use the relative paths.
$fp = $_POST["foldpath"];
$files = glob($fp ."/" ."*.*");
//this is a pop up page which needs to stay open after the selection has been made
echo "<script> $(\"#imgstuff\").css({\"display\":\"block\"});</script>";
//the form closed on whgen the close x is selected
}else
{
//default
$files = glob("../images/bannerImgs/*.*");
}
for ($i=0; $i<count($files); $i++)
{
$image = $files[$i];
$supported_file = array(
'jpg',
'jpeg',
'png'
);
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
// print $image ."<br />";
$path = $image;
$path1 = DIR;
if (strpos($path, $path1) !== false) {
$path2 = $path;
}else{
$path2 = str_replace('../', '', $path);
$path2 = $path1.$path2;
}
$fn = basename($path);
$fn = basename($path, PATHINFO_EXTENSION);
if($fn!="aa.jpg"){
echo '<p class="imgdet">';
// echo '<span class="imglongpath">' . $path2 .'</span>';
echo '<img src="'.$image .'" alt="Random image" />';
echo '<span class="imgname">' . $fn .'</span>';
// echo '<span class="imgmesg">Now click Confirm / Set Choice</span>';
// "<br /><br />";
echo "</p>";
}
} else {
continue;
}
}
?>

Shell_Exec error for directory listing?

I found a useful php code which displays the photos in a folder directory as a image preview. The issue is my host provider blocks one of the script commands, "Shell_exec()", so the php code doesn't work.
Any way of getting the code to run without using shell_exec?
<?PHP
// filetypes to display
$imagetypes = array("image/jpeg", "image/gif");
?>
<?PHP
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
?>
<?PHP
// fetch image details
$images = getImages("images");
// display on page
foreach($images as $img) {
echo "<div class=\"photo\">";
echo "<img src=\"{$img['file']}\" {$img['size'][3]} alt=\"\"><br>\n";
// display image file name as link
echo "",basename($img['file']),"<br>\n";
// display image dimenstions
echo "({$img['size'][0]} x {$img['size'][1]} pixels)<br>\n";
// display mime_type
echo $img['size']['mime'];
echo "</div>\n";
}
?>
You can get the mime type of a file using the PHP function mime_content_type(). This way you can get rid of the shell_execute used to detect the mime type in your code.

PHP different locations for images and thumbs

I have found some solution that work mostly but none that do the trick 100% what I am looking for is code that will look in all my albums in one directory and pull the images and also pull my thumbs that are in another folder and echo out the a string like this.
echo '<img src="',$img,'" />';
The problem is that my href image is in my images folder and my src (thumbnails) are in another directory. I am using shadowbox and want the script to echo out a stirng that will allow both the directories to be scanned at the same time.
Below is what I am using that does scan the directorys but will not return the coresponding enter code herethumbnails that reside in another directory
//path to directory to scan. i have included a wildcard for a subdirectory
$directory = "gallery_uploads/*/";
//get all image files with a .jpg extension.
$images = glob("" . $directory . "*.jpg");
$imgs = '';
// create array
foreach($images as $image){ $imgs[] = "$image"; }
//display images
foreach ($imgs as $img) {
"<a href='$img' rel='shadowbox'><img src='$img' /> ";
echo'<img src="',$img,'" />';
This works for me. You would have to make sure your images have the same name in each directory though.
It is very simple to have your uploader save the original, then save a resized image of the same name in the thumbnail directory.
$gallery_up_dir = "gallery_uploads";
$gallery_thumb_dir = "gallery_thumbs";
$directory = "$gallery_up_dir/*/";
// or get all image files with a .jpg, .JPG, .png, .PNG extension.
$extensions_array = array('jpg', 'JPG', 'png', 'PNG');
$imageArray = array();
foreach($extensionsArray as $ext){
$images = glob("" . $directory . "*.$ext");
// fill up the array
foreach($images as $image){
$imageArray[] = "$image";
}
}
//display images
foreach ($imageArray as $img) {
echo '<a href="',$img,'" rel="shadowbox"><img src="',
str_replace($gallery_up_dir,$gallery_thumb_dir,$img) ,'" /></a>';
}

Displaying directories stored within a directory

I've just watched these videos on displaying images from a directory and would like some help modifiying the code.
http://www.youtube.com/watch?v=dHq1MNnhSzU - part 1
http://www.youtube.com/watch?v=aL-tOG8zGcQ -part 2
What the videos show is almost exactly what I wanted, but the system I have in mind is for photo galleries.
I plan on having a folder called galleries, which will contain other folders, one each for each different photo sets ie
Galleries
Album 1
Album 2
I would like some help to modify the code so that it can identify and display only the directories on one page. That way I can convert those directories into links that take you to the albums themselves, and use the orignal code to pull the images in from there.
For those that want the video code, here it is
$dir = 'galleries';
$file_display = array('bmp', 'gif', 'jpg', 'jpeg', 'png');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir , '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
You need to use a function like this to list all of the directories:
function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = #opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces $file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
echo "$spaces $file<br />";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
Then, pass the directory a user selected in as your $dir variable to the function you currently have.
I can't test any code right now but would love to see a solution here along the lines of:
$directory = new RecursiveDirectoryIterator('path/galleries');
$iterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($iterator, '/^.+\.(bmp|gif|jpg|jpeg|png)$/i', RecursiveRegexIterator::GET_MATCH);
SPL is powerful and should be used more.
The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.
http://www.php.net/manual/en/class.recursivedirectoryiterator.php

List images(01.png) and descriptions(01.txt) from directory

How can I display images from directory and get a corresponding description with each image, give the description exists.
in Directory //
01.png
01.txt
02.png
03.png
03.txt
etc.
to display as //
<img src="01.png"><br>This is the description from the text file named 01.txt
<img src="02.png"><br>
<img src="03.png"><br>This is the description from the text file named 03.txt
I've been searching and searching, but can't find anything, so if someone could point me in the right direction it would be greatly appreciated. Also this is a very useful thing to be able to do for people wanting to create very simple galleries or lists of images and names.
Thanks in advance!
This is what you're looking for, as the description must be dynamically captured from a corresponding .txt file:
$dir = './';
$files = glob( $dir . '*.png');
foreach( $files as $file) {
$filename = pathinfo( $file, PATHINFO_FILENAME) . '.txt';
$description = file_exists( $filename) ? file_get_contents( $filename) : '';
echo '<img src="' . $file . '"><br>' . $description;
}
What it does is grabs an array of *.png files using glob() from a given directory ($dir). Then, for each image, it gets the filename of the image (so 01.png would be 01), and appends .txt to get the name of the description file. Then, it loads the description file into the $description variable using file_get_contents() if the description file exists. It then outputs the desired HTML.
I assume you have the .php file in the same directory as the pictures and text files are.
You could use function glob() to read in all image-files as array from the directory, cut off the file extension (so '01.png' becomes '01') and append the file extension with string concatentation.
A working code example may look like this:
<?php
$path_to_directory = './';
$pics = glob($path_to_directory . '*.png');
foreach($pics as $pic)
{
$pic = basename($pic, '.png'); // remove file extension
echo '<img src=\"{$pic}.png\"><br>';
if(file_exists($pic . '.txt'))
{
echo file_get_contents("{$pic}.txt");
}
}
?>
So definitely have a look on these functions:
http://www.php.net/glob
http://www.php.net/basename
http://www.php.net/file_get_contents
Happy coding.
Your question is a bit confusing.
make an array with all information.
$pics = array('img' => '01.png', 'text' => 'This is the description');
foreach($pics as $pic) {
echo '<img src="'.$pic['name'].'" alt="">' . $pic['text'];
}
So you have to put your information in an array or a database otherwise you cannot map the desciption to your image.
When you want to read dynamicly the folder its a bit difficult.
You can look at readdir or glob then you can read all images get the name and load the textfile with file_get_contents but i think its not a really performant way.
Code Modified from here : http://php.net/manual/en/function.readdir.php
//path to directory to scan
$directory = "../images/team/harry/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
//print each file name
foreach($images as $image)
{
print "<img src=\"$image\"><br>This is the description from the text file named $image";
}
ok, so this won't print the contents of the text file, but I'm sure you can further modify the code above to figure that out
YEP
Updated version of ZnArKs code, as he missed that you wanted the content of the files
//path to directory to scan
$directory = "../images/team/harry/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.png");
//print each file name
foreach($images as $image)
{
$textfile = substr($image, 0, -3) . "txt";
echo "<img src='{$image}'><br/>";
if(file_exists($textfile))
{
echo file_get_contents($textfile) . "<br/>";
}
}

Categories