Foreach txt and image files with different code blocks - php

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

Related

Scan folder for folders, and get first image of folder

I've got multiple folders within a folder. I'm trying to make a type of gallery.
I want to scan the first folder (FolderA) for all the folders within it.
Next thing I want to do is get the first picture of that folder, ignoring everything that is not a image.
It need's to be a preview of the first image in each folder.
RecursiveDirectoryIterator can help for you to iterate a directory tree.
$path = '/path/to/FolderA';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$firsts = array();
foreach($iterator as $name => $item){
if (!$item->isDir()) {
if (!isset($firsts[$item->getPath()]) && exif_imagetype($item->getRealPath())) {
$firsts[$item->getPath()] = $item->getRealPath();
}
}
}
var_dump($firsts);
I've done some extra research and the following worked for me:
foreach(glob('cms/images/realisaties/*', GLOB_ONLYDIR) as $dir) {
$dirname = basename($dir);
$mappen[] = $dirname;
}
foreach($mappen as $map){
$search_dir = "cms/images/realisaties/".$map;
$images = glob("$search_dir/*");
sort($images);
if (count($images) > 0) {
$img = $images[0];
echo '
<!--product item-->
<div class="product_item hit w_xs_full">
<figure class="r_corners photoframe type_2 t_align_c tr_all_hover shadow relative">
<!--product preview-->
<a href="realisaties/40-realisaties/'.$map.'" class="d_block relative wrapper pp_wrap m_bottom_15" >
<img src="'.$img.'" class="tr_all_hover" alt="0" style="max-height:242px">
</a>
<!--description and price of product-->
<figcaption>
<h5 class="m_bottom_10">'.ucfirst($map).'</h5>
<button class="button_type_12 bg_scheme_color r_corners tr_all_hover color_light mw_0 m_bottom_15">Bekijk</button>
</figcaption>
</figure>
</div>
';
} else {
// possibly display a placeholder image?
}
}
}
The folder containing the folders that had the images is "realisaties". With GLOB I first went through them. After that I put all the folder names in an array.
With that array I made another loop. I used glob again to look what is inside that folder. After that I sorted the images, and set the preview image to be the last added.

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"

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

Using PHP to display a folders contents, but show a message when folder is empty

I'm creating a intranet for my workplace and have used a bit of php I found online to scan the contents of the folder it's in and display them as links. It does this fine, but when it's inside an empty folder I would like it to display a message such as "There are no records matching those criteria.".
Is there a way to add something to the php to specify if there are no folders listed print this?
I have next to no knowledge of php, but html and css are no problem.
Here's the php I'm using in the page:
<?php
$dir=opendir(".");
$files=array();
while (($file=readdir($dir)) !== false)
{
if ($file != "." and $file != ".." and $file != "A.php")
{
array_push($files, $file);
}
}
closedir($dir);
sort($files);
foreach ($files as $file)
print "<div class='fileicon'>
<a href='$file'>
<img src='../../../images/TR-Icon.png'>
<p class='filetext'>$file</p>
</a>
</div>";
?>
If you need anymore code such as the full page html or css just let me know.
Thanks in advance for any help.
EDIT:
After trying Josh's solution it pretty much nailed it, but I'm now getting "No files found" printing 3 times. Here's the code I'm using now:
<?php
$dir=opendir(".");
$files=array();
while (($file=readdir($dir)) !== false)
{
if( count($files) == 0 )
{
echo '<p>No files found</p>';
}
else
{
if ($file != "." and $file != ".." and $file != "A.php")
{
array_push($files, $file);
}
}
}
closedir($dir);
sort($files);
foreach ($files as $file)
print " <div class='fileicon'>
<a href='$file'>
<img src='../../../images/TR-Icon.png'>
<p class='filetext'>$file</p>
</a>
</div>";
?>
Just do an:
if( count($files) == 0 )
{
echo '<p>No files found</p>';
}
else
{
// you have files
}
You can use the count function to check if there are any files in your files array like this:
if(count($files) > 0) // check if there are any files in the files array
foreach ($files as $file) // print the files if condition is true
print " <a href='$file'>$file</a> <br />";
else
echo "ERROR!";
EDIT:
You can also use the scandir function. However, this function will return two extra entries for the current directory and directory up one level. You need to remove these entries from the files array. Your code will look like this:
<?php
$dir = "."; // the directory you want to check
$exclude = array(".", ".."); // you don't want these entries in your files array
$files = scandir($dir);
$files = array_diff($files, $exclude); // delete the entries in exclude array from your files array
if(!empty($files)) // check if the files array is not empty
{
foreach ($files as $file) // print every file in the files array
print " <div class='fileicon'>
<a href='$file'>
<img src='../../../images/TR-Icon.png'>
<p class='filetext'>$file</p>
</a>
</div>";
}
else
{
echo "There are no files in directory"; // print error message if there are noe files
}
?>
Try This:
<?php
$dir=opendir(".");
$files=array();
while (($file=readdir($dir)) !== false)
{
if ($file != "." and $file != ".." and $file != "A.php")
{
array_push($files, $file);
}
}
closedir($dir);
if(count($files) == 0){
die("There are no records matching those criteria.");
}else{
sort($files);
foreach ($files as $file)
print " <div class='fileicon'>
<a href='$file'>
<img src='../../../images/TR-Icon.png'>
<p class='filetext'>$file</p>
</a>
</div>";
}
?>
You can use a simple conditional using count on your file array.
// ...
closedir($dir);
if (count($files) > 0) {
// sort files and iterate through file array, printing html
} else {
echo "There are no records matching those criteria.";
}
// ...
I think you could let it print something else if($files.length == 0) and only print it normally if($files.length > 0) or something.
I have no knowledge of php, but I know java, html, css, and javascript.
I'm sure php has things like array.length (or something else to get the length of an array) in it
I hope this was helpful.
EDIT: I've seen others already answered thigs that are like 10x better than mine.
Also, php seems pretty cool, I might learn it

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

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

Categories