How can I add captions to this auto-create php gallery? - php

<?php
/* settings */
$image_dir = 'gallery/';
$per_column = 3;
$count=0;
if ($handle = opendir($image_dir)) {
while (false !== ($file = readdir($handle)))
{
if ($file != '.' && $file != '..')
{
if(strstr($file,'-thumb'))
{
$files[] = $file;
}
}
}
closedir($handle);
}
if(count($files))
{
foreach($files as $file)
{
$count++;
echo '<a class="thumbnail" rel="one-big-group" href="',$image_dir,str_replace('-thumb','',$file),'"><img src="',$image_dir,$file,'" width="100" height="100" /></a>';
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}
}
else
{
echo '<p>There are no images in this gallery.</p>';
}
?>
How can I add captions to each of the images?
Thank you very much for the answer!

Your code is traversing the files within the specified directory looking for files containing ...-thumb... in the filename, appending them to an array, and then looping over the array to generate HTML for displaying the thumbnail image gallery.
Adding additional information to something like this, given the very limited code you've provided, can be done in any number of ways
You could implement a database with a column for each filename and a
related column containing captions/descriptions. This might be more
trouble than it's worth depending on what you're trying to achieve.
You could use a flat file which you could parse line by line (instead of traversing the
folder for ...-thumb... images), containing some format like
file1-thumb.png|some caption here
file2-thumb.png|some caption here
file3-thumb.png|some caption here
...
You could includ a small caption in the filename itself, and parse/format the caption from the filenames. This would probably be the quickest route, but most limiting in terms of flexibility in the length/characters allowed for the captions.
- file1-thumb--some_caption_here.png
- file2-thumb--some_caption_here.png
- file3-thumb--some_caption_here.png
To actually add the caption to the generated HTML, you can use a title attribute as #rockerest suggested, however I'd personally add such a caption to to the image itself, as that is what the caption is describing (not the link)
<img src="..." title="..." ... />
UPDATE
To answer your comment (this provides better formatting for code), Let's say we have a file with name file1-thumb--some_description_here.jpg, you can parse and format the caption with preg_replace
$filename = 'file1-thumb--some_description_here.jpg';
$caption = preg_replace(array('/^.+-thumb--/', '/\.(jpg|jpeg|gif|png|bmp)$/', '/_/'), array('','',' '), $filename);
$caption is now some description here

The html title offers a "caption" when the mouse is hovered over the image.
foreach($files as $file)
{
$count++;
echo '<a title="',$caption,'" class="thumbnail" rel="one-big-group" href="',$image_dir,str_replace('-thumb','',$file),'"><img src="',$image_dir,$file,'" width="100" height="100" /></a>';
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}

Related

Foreach txt and image files with different code blocks

I have a gallery. I would like to glob files into. It works fine for jpg, png etc.
Directory:
1.jpg
2.png
3.jpg
...
Code :
foreach ($gallery as $u)
{
echo'<div class="section active" id="">';
foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif,txt}", GLOB_BRACE) as $filename) {
echo '<div class="slide"><img class="" src="https://onlinegallery.online/'.$filename.'" /></div>'; //slide
}
echo('</div>');
}
I would like to put a txt file to directory and create foreach for txt and image files (Some slides should be a txt files). I don't know how to do that because txt file can't be used in img src tag. It should looks something like this.
Directory:
1.png
2.img
3.txt
4.jpg
$images = '<img class="" src="https://onlinegallery.online/'.$filename.'" />';
$txt = '<div><p>fopen("'.$filename.'", "r");
echo fread($txt,filesize("'.$filename.'"));
fclose($txt); </p></div>';
foreach ($gallery as $u)
{
echo'<div class="section active" id="">';
foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif,txt}", GLOB_BRACE) as $filename) {
echo '<div class="slide">
//$images or $txt files
//i need txt and images files here
</div>'; //slide
}
echo('</div>');
}
I suppose I'm completely out, but thank you for your advice anyway.
You'll need to read the contents of your text files and output them. Be careful to sanitize the text contents - you don't want to accidentally emit something that's treated as html, especially if the contents are coming from an unknown source (read more).
You'll also need to add an if inside the for loop to determine if you're outputting an image or text. For images, you can keep using your existing code.
For text, something like this might work:
echo htmlentities(file_get_contents($filepath));
foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif,txt}", GLOB_BRACE) as $filename) {
$imgFileType = pathinfo($filename,PATHINFO_EXTENSION);
$title = basename("$meno/$new/$filename", ".jpg").PHP_EOL;
if(($imgFileType == 'jpg') || ($imgFileType == 'png') || ($imgFileType == 'jpeg') || ($imgFileType == 'gif')) {
echo '<div class="slide"><img class="" onclick="fullscreen()" src="https://onlinegallery.online/'.$filename.'" alt="'.$title.'"/><p class="imagetitle">'.$title.'</p></div>';
}
if(($imgFileType == 'txt')) {
echo '<div class="slide"><p class="txtslide" onclick="fullscreen()">';
echo filter_var(file_get_contents($filename), FILTER_SANITIZE_STRING);
echo '</p><p class="imagetitle">'.$title.'</p></div>';
}
}
echo('</div>');

PHP to post links to sub directories & php to display images

I'm very basic when it comes to PHP.
With my website, I have a directory called "uploads"
Within "uploads" I have 3 folders "Example1" "Example2" and "Example3"
Within each of the folders, they contain images.
I need to know how to use php to create a navigation for every sub directory.
So that if I add a new folder "Example4" it will give a navigation like:
Select what section you're looking for:
Example1 | Example2 | Example3
and if I later add new folders add them to the navigation.
EX:
Example1 | Example2 | Example3 | Example4 | Example5
Then once they click the link to go into the folder, have a code that displays all the images in that folder.
So far I have:
<?php
$files = glob("uploads/*.*");
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="/'.$num.'">'."<p>";
}
?>
but it will only display the images in the upload directory, not the images in Example1 and so on.
How on earth would I go about doing this? I'm doing it for a school project and have two weeks to complete it, but I am so lost. I only have knowledge with CSS, HTML, and the only PHP I know is php includes, so any help would be appreciated.
Since it seems that you are familiar with globs a bit, here is an example using the "glob" function. You can see a basic working example of what you are looking for here:
http://newwebinnovations.com/glob-images/
Here is how I have the example set up:
There are two PHP files, one is index.php and the other is list-images.php.
There is also a folder for images two subfolders that have images inside of them.
index.php is the file that finds the folders in the images folder and places them in a list with links list-images.php which will display the images inside of the folder:
$path = 'images';
$folders = glob($path.'/*');
echo '<ul>';
foreach ($folders as $folder) {
echo '<li>'.$folder.'</li>';
}
echo '</ul>';
The links created above have a dynamic variable created that will pass in the link to the list-images.php page.
Here is the list-images.php code:
if (isset($_GET['folder'])) {
$folder = $_GET['folder'];
}
$singleImages = array();
foreach (glob($folder . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $image) {
$imageElements = array();
$imageElements['source'] = $image;
$singleImages[$image] = $imageElements;
}
echo '<ul>';
foreach ($singleImages as $image) {
echo '<li><img src="'.$image['source'].'" width="400" height="auto"></li>';
}
echo '</ul>';
The links created here will link you to the individual images.
To get files of every specific folder ,pass it throw a get variable that contains folder's name,an then scan this folder an show images ,url should be like this :
listImages.php?folderName=example1
To have menu like what you want :
<?php
$path = 'uploads/' ;
$results = scandir($path);
for ($i=0;$i<count($results);$i++ ) {
$result=$results[$i];
if ($result === '.' or $result === '..') continue;
if (is_dir($path . '/' . $result)) {
echo "<a href='imgs.php?folderName=$result'>$result</a> ";
}
if($i!=count($results)-1) echo '|'; //to avoid showing | in the last element
}
?>
And here is PHP page listImages that scan images of a specific folder :
<?php
if (isset($_GET['folderName'])) $folder=$_GET['folderName'];
$path = 'uploads/'.$folder.'/' ;
$images = glob($path . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach ($images as $image) {
echo "<img src='$image' />";
}
?>
First of all, do read more PHP manual, for directory related: opendir, for files related: fopen
The following code is basically re-arranging the example code provided in opendir. What it does:
A scan_directory function to simply check if directory path is valid and is a directory, then proceed to do a recursive call if there's a child directory else just print out the file name.
The first if/else condition is just to ensure the base directory is valid.
I'll added ul and li to make it slightly more presentable.
$base_dir = 'upload';
if (is_dir($base_dir))
scan_directory($base_dir);
else
echo 'Invalid base directory. Please check your setting.';
// recursive function to check all dir
function scan_directory($path) {
if (is_dir($path)) {
if ($dir_handle = opendir($path)) {
echo '<ul>';
while (($file = readdir($dir_handle)) !== false) {
if ($file != '.' && $file != '..') {
if (is_dir($path . '/' . $file)) {
echo '<li>';
echo $file;
scan_directory($path . '/' . $file);
echo '</li>';
}
else
echo "<li>{$file}</li>";
}
}
echo '</ul>';
}
}
}
create image as subdirectory name with image name and save it in database
example:
subdirectory name: example2
image name: image.jpg
store image name in db as "example2/image.jpg"

Showing link of which random swf was opened

I'm new to PHP and this seems like I'm just asking for code but in reality I want to know how to implement a link along with the random selector.
My code:
<?php
$imglist='';
//$img_folder is the variable that holds the path to the swf files.
// see that you dont forget about the "/" at the end
$img_folder = "../files/flash/";
mt_srand((double)microtime()*1000);
//use the directory class
$imgs = dir($img_folder);
//read all files from the directory, ad them to a list
while ($file = $imgs->read()) {
if (preg_match("/\.swf$/i", $file))
$imglist .= "$file ";
} closedir($imgs->handle);
//put all images into an array
$imglist = explode(" ", $imglist);
$no = sizeof($imglist)-2;
//generate a random number between 0 and the number of images
$random = mt_rand(0, $no);
$image = $imglist[$random];
//display random swf
echo '<embed src="'.$img_folder.$image.'" quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash" width="650"
height="450"></embed>';
?>
This basically grabs a random flash file from my site's directory. Since it won't affect the URL bar, they won't be able to send something they like to someone (which is an unintentional security feature). I want them to be able to send a link or possibly direct click to download.
Also, I was thinking of as well as the random generator, to make a left and right arrow that they can scroll through all the .swf's in the chosen directory, if possible.
the site is www.nsgaming.us and it's the 'Random' button under the text logo.
What you are asking for is reading parameters from the URL so people can link their friends to this SWF embed, you can do that by using $_GET
Look at this example I coded.
$swfs = array();
$swf_location = '../files/flash/';
if($handle = opendir($swf_location)) {
while(false !== ($entry = readdir($handle))) {
if(strtolower(pathinfo($path, PATHINFO_EXTENSION)) == 'swf') {
$swfs[] = $entry;
}
}
closedir($handle);
}
if(isset($_GET['swf']) && in_array($_GET['swf'], $swfs)) {
$swf = $_GET['swf'];
} else {
$swf = $swfs[rand(0, count($swfs))];
}
echo '<embed src="' . $swf_location . $swf . '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="650" height="450"></embed><br />Send this to a friend: <input type="text" value="http://yourwebsite.com/thisfilesname.php?swf=' . $swf . '" length="55">';
You're previous script was very messy and did a lot of useless stuff, this is secure and faster

if folder is empty echo message, if not show all jpg files

im trying to echo all jpg image files in a folder.
it works, but i dont have the line to show an error that the folder is empty written properly. it shows a php script error instead,
another problem is that i have one .txt file in the directory, this
one will read the text for the certain page. the rest of the script
will echo the jpg files. it might not echo zero files because of that
text file
folder = cat the gategory name/title .txt file = the text for the page
.jpg files = are the categories pictures
error is:
Warning: Invalid argument supplied for foreach() in /home/ranshow/domains/show.webking.co.il/public_html/modules/attractions.php on line 67
Gallery is empty, no pics to show
0
<div style="text-align: center;margin-top:25px;margin-bottom: 50px;">
<?
$count = "0";
foreach (glob("attractions/$cat/*.jpg") as $filename) {
$count++;
$files[] = $filename;
$filename = urlencode($filename);
}
if($count == "0") { echo "Gallery is empty, no pics to show"; }
else {
?>
<?
foreach ($files as $filename) {
?>
<a id="thumb1" href="img.php?img=<?=$filename;?>" class="highslide" onclick="return hs.expand(this)">
<img src="img.php?img=<?=$filename;?>" width="167" height="150" style="margin: 2px;d0b28c;padding:1px;border: 1px solid #c1c1c1;">
</a>
<?
}
?>
<?
}
?>
<br />
<i><?=$count;?> <?=$lang['attractions']['totalimages'];?></i>
<br />
</div>
how can i fix this? thanks :)
Check count before entering foreach:
$globs = glob("attractions/$cat/*.jpg");
if( $globs ){
foreach ($globs as $filename) {
$count++;
$files[] = $filename;
$filename = urlencode($filename);
}
}
It seems that you need scandir instead of glob, as glob can't see unix hidden files.
<?php
$pid = basename($_GET["prodref"]); //let's sanitize it a bit
$dir = "/assets/$pid/v";
if (is_dir_empty($dir)) {
echo "the folder is empty";
}else{
echo "the folder is NOT empty";
}
function is_dir_empty($dir) {
if (!is_readable($dir)) return NULL;
return (count(scandir($dir)) == 2);
}
?>
Note that this code is not the summit of efficiency, as it's unnecessary to read all the files only to tell if directory is empty. So, the better version would be
function is_dir_empty($dir) {
if (!is_readable($dir)) return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An
a === b
expression already returns Empty or Non Empty in terms of programming language, FALSE or TRUE respectively - so, you can use the very result in control structures like IF() without any intermediate values
Please check this answer of Your Common Sense for more details

echoing thumbnails that link to the larger image

I have a script that scans a directory of thumbnails and echoes them to the page. It works nicely, but the thumbnails are not clickable, and i would really like this to be the case. echo "<img src='$thumbnail' class='resizesmall'>"; is the line where the thumbnails are echoed. I'm not sure how to write the path to the larger image inside the php without breaking it. Maybe this should be done inside the foreach statement? thanks for your help?
$dir = "../mysite/thumbnails/";
$dh = opendir($dir);
// echo "$dh";
$gallery = array();
while($filename = readdir($dh))
{
$filepath = $dir.$filename;
//pregmatch used to be ereg
if (is_file($filepath) and preg_match("/\.png/",$filename))
{
$gallery[] = $filepath;
}
}
sort($gallery);
foreach($gallery as $thumbnail)
{
echo "<img src='$thumbnail' class='resizesmall'>";
}
?>
</div>
<??>
The easiest way would be to setup a situation where your thumbs and your full size images were named the same. So you may have thumbs/image1.png and full/image1.png. Then instead of using $thumbnail use a variable $image, or something similar just so the code reads better. You'll also want to leave the $filepath out of the mix so that $image ends up as just the file name.
foreach($gallery as $image)
{
echo "<a href='full/$image'><img src='thumb/$image' class='resizesmall'></a>";
}
You may want to throw in some checks to make sure there is a matching image just to prevent errors or bad UX. However, the code above should work.

Categories