Using FilesystemIterator in a foreach loop to generate image library - php

I have this code inside a php file:
<?php
function convertToReadableSize($size){
$base = log($size) / log(1024);
$suffix = array("", "KB", "MB", "GB", "TB");
$f_base = floor($base);
return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}
$file_path = 'online_assets/images/';
?>
With a repeating loop displaying every entry:
<?php
$fileSystemIterator = new FilesystemIterator('online_assets/images/');
foreach ($fileSystemIterator as $fileInfo){
$entries[] = $fileInfo->getFilename();
?>
<div class="row">
<div class="col-md-7">
<a href="<?php echo $file_path;?>Room.jpg" target="new">
<img src="/slir/w320-h180-c320x180/<?php echo $file_path;?>Room.jpg" class="img-responsive"/></a>
</div>
<div class="col-md-5">
<h4 class="red"><?php $filename;?></h4>
<p>Filesize: <?php echo convertToReadableSize(filesize($cannery_file_path . 'Room.jpg'));?><br>Format: jpg<br>Quality: <?php list($width, $height) = getimagesize($file_path . 'Room.jpg'); echo ($width) . " x " . ($height); ?></p>
<a href="<?php echo $file_path;?>Room.jpg" target="new">
<button type="button" class="btn btn-primary btn-sm">Download Here</button></a>
</div>
</div>
<?php } ?>
What I am trying to accomplish here is a loop that will return a value essentially foreach image inside the /images/ folder - so all the client has to do is upload images to that folder and they appear, with a thumbnail, file information and a link to download.
I have the rest working, but the loop is giving me some troubles. What am I missing for this?
I picked the code for the FileSystemIterator from the php online manual.

Related

PHP import images from directory into 2 column HTML row

I have found some PHP that I am trying to adapt onto my page but can not seem to get it to work. Here is the code:
<?php
$pagetitle = "Test Gallery";
$dirname = "img/folder_1/";
$images = glob($dirname."*.jpg");
?>
<?php $i=0; foreach($images as $image): ?>
<?php if($i%2 === 0) echo '<div class="row">' ?>
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
<?php if($i%2 === 0) echo '</div>' ?>
<?php $i++; endforeach ?>
I am trying to get the images to be pulled from a directory and each image is wrapped in a .col-sm-6 div then each 2 are wrapped in a .row div, then if there is an odd number of the files the last one would just be one .col-sm-6 div on its own. Below is the structure that I am trying to achieve:
<div class="row">
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
</div>
The IMAGE_NAME I would add something to pull through the imported filename so it can be displayed on the page and the IMAGE_SOURCE would be the images URL so for now please ignore those bits of text as I don't think it will affect this?
I am new to PHP and just can't seem to find why nothing is showing on the page unless this code is not suited to my needs?
P.s. if any of my syntax's are incorrect I apologies in advance.
$images will be filled by your golb
So basically you just edit the line
<?php if($i%2 === 0) echo '</div>' ?>
To
<?php if($i%2 === 1) echo '</div>' ?>
Here a more readable example:
<?php
$images = [
'https://via.placeholder.com/10x50','https://via.placeholder.com/20x50','https://via.placeholder.com/30x50','https://via.placeholder.com/40x50',
'https://via.placeholder.com/50x50','https://via.placeholder.com/60x50','https://via.placeholder.com/70x50',
];
?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"/>
<?php
$cols = 2; // dividable by 12 please
for( $i = 0; $i < count($images) && $image = $images[$i]; $i++) {
if( $i%$cols == 0 ) { echo '<div class="row">'; }
echo '<div class="col-sm-' . 12/$cols . '">';
echo '<img class="lazy store-img" src="' . $image . '" alt="" title="">';
echo '<h3>IMAGE_NAME</h3>';
echo '<button href="#" class="btn btn-primary">Purchase Image</button>';
echo '</div>';
if( $i%$cols == $cols-1 ) { echo '</div>'; } /* here comes the magic :) */
}
if( count( $images )%$cols > 0 ) {
echo '</div>';
}
?>

Adding a unique class to items in a PHP foreach loop

I've got a bunch of images in a folder called img and am trying to do a foreach loop to loop over them and output them to the screen, but then adding a unique class to each image.
Here's what I have so far but it says $i is undefined, so I'm not sure I'm on the right track. I'm very new to this.
$dir = "img/gallery/*.jpg";
$classes = array('promotional', 'beaches', 'volunteers');
$images = glob( $dir );
foreach ( $images as $image ):
$class = $classes[$i++ % 3];
echo '
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix ' . $class . '">
<div class="portfolio-item">
<div class="shot-item">
<a class="overlay lightbox" href="' . $image . '">;
<img src="' . $image . '" />;
<i class="lnr lnr-plus-circle item-icon"></i>
</a>
</div>
</div>
</div>
';
endforeach;
Thanks for any help!
I would modify the foreach a little bit like so:
$dir = "img/gallery/*.jpg";
$classes = array('promotional', 'beaches', 'volunteers');
$images = glob( $dir );
$i = 0;
foreach ( $images as $x => $image ):
$class = $classes[$i++ % 6];
echo '
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix ' . $class . '-' . $x . '">
<div class="portfolio-item">
<div class="shot-item">
<a class="overlay lightbox" href="' . $image . '">;
<img src="' . $image . '" />;
<i class="lnr lnr-plus-circle item-icon"></i>
</a>
</div>
</div>
</div>
';
endforeach;
I think best way would be using two class rather than one unique.
First class will be use to detect item/content type,
and second will be unique to identify uniquely.
By doing this it will give you more control over content.
Here is little bit modification.
$dir = "img/gallery/*.jpg";
$classes = array('promotional', 'beaches', 'volunteers');
$images = glob( $dir );
foreach ( $images as $index => $image ):
$class = $classes[$i++ % 6];
echo "
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix my-list-item-{$class} image-id-{$index}">
<div class="portfolio-item">
<div class="shot-item">
<a class="overlay lightbox" href="' . $image . '">;
<img src="' . $image . '" />;
<i class="lnr lnr-plus-circle item-icon"></i>
</a>
</div>
</div>
</div>
";
endforeach;
What changes:
Changes single quote(') to double quote(") to be able to parse variable inside string, like this {$class} or simply like this $class
added class to identify type of item, my-list-item-{$class} : will result like this this my-list-item-promotional
added class to identify as a unique item, image-id-{$index} : will result like this image-id-5
Use in css or js
CSS:
.my-list-item-promotional{background: green;}
.my-list-item-promotional.image-id-2{background: yellow;}
This will provide all promotional type content background green except item number 2
You can use jQuery to select element like CSS does.
Thank you.
You don't need to define your own $i; it already exists as the index of the $images array.
After you do $images = glob( $dir );, $images will be a numerically indexed array. So instead of explicitly incrementing a counter variable like this:
foreach ( $images as $image ):
$class = $classes[$i++ % 3];
You can just use the index from the array like this:
foreach ( $images as $i => image ):
$class = $classes[$i % 3];

display a image that starts with a # in <img> tag

<?php
$imageDir = "";
$images = glob($imageDir . '*.jpg');
foreach ($images as $image) {
?>
<div class="col-lg-3 col-md-4 col-xs-6">
<?php
$name = chop($image, '.jpg');
$filename = $image;
if (file_exists($filename)) {
$taken = "Screenshot Taken: " . date("F d Y H:i:s", filemtime($filename));
}
?>
<a data-gallery="example-gallery" style="text-decoration:none" href="<?php echo $image; ?>" class="d-block mb-4 h-100" data-toggle="lightbox" data-title="Player Name: <?php echo $name; ?>" data-footer="<?php echo $taken; ?>" data-max-width="800" >
<img class="img-fluid img-thumbnail" src="<?php echo $image; ?>" alt="">
<p><?php echo $name; ?></p>
</a>
</div><?php}?>
Hi . i created a image gallery with php . using glob function. but some images wont display , because those images starts with a #(hash) . EX: www.mysite.com/ss/#insta.jpg
iam using tags . is there any other way to view images like this in a
< img> tag
.
Encode the # in your URL
Replacing it with %23 should work

Every loop an unique variable

Is there any way I can use an unique variable for every time the code runs a foreach loop? Maybe there is an other way to fix this. If I have more than one project in the directory it will count both of the projects.
Everytime I use the carousel the counter will count through all of the directories. It need to be unique for every project.
Here is the code:
<?php
$directory = "./public/img/portfolio/". $row['naam_project'] ."/";
$images = glob($directory . "*.jpg");
$i = 0;
foreach($images as $image)
{
?>
<div class="mySlides fade">
<img src="<?php echo $image ?>" style="width:100%">
</div>
<?php
}
?>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br>
<div style="text-align:center">
<?php
foreach($images as $image)
{
$i++;
?>
<span class="dot" onclick="currentSlide(<?php echo $i; ?>)"></span>
<?php
}
?>
use foreach key value key is unique for array
{foreach($images as $key->$value)
{
?>
<span class="dot" onclick="currentSlide(<?php echo $key; ?>)"></span>
<?php
}}

PHP link not working - cannot find the mistake

I built a CMS system using CKEditor and KCFinder that store information od a databse via textarea/php. So far so good!
The issue comes to when I want to store and display images that link to themselves. The way I am storing images is exactly the same: There is a textarea where I insert an image via KCFinder/CKEditor. The image is uploaded to the server and the path stored at the database. Later I try to pick up that path from the database to display the image (that part also works) and because I want the image to link to itself, I try to use the same method to insert the url on the link. Problem? The link is missing.
Can anyone point me the error and suggest any solution? I would be so thankful!
Code:
<?php
$sql = "SELECT * FROM php_maskiner ORDER BY timestamp DESC";
$result = mysql_query($sql) or print ('<div class="alert alert-standard fade in">
<a class="close" data-dismiss="alert" href="#">×</a>
<strong>Can't read the database!</strong>
</div>' . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$title = stripslashes($row['title']);
$entry = stripslashes($row['entry']);
$images = html_entity_decode($row['images']);
$img_url = $row['images'];
$img_pack = '<div class="mask3 span3">
<a rel="prettyPhoto" href="' . $img_url . '">' . $images . '</a>
</div>';
?>
<article class="span12 post">
<?php echo $img_pack; ?>
<div class="inside">
<div class="span8 entry-content">
<div class="span12">
<h2><?php echo $title; ?></h2>
<p><?php echo $entry; ?></p>
</div>
</div>
</div>
</article>
<?php
}
?>
UPDATE:
I think that this might be a problem caused by CKEditor. In the database the image path is store as: . This is in my understanding what is being outputted. How do I do to output only "/nysida/admin/kcfinder/upload/images/1307594_10243178.jpg"?
Your first mistake is still using the mysql_ extensions to access your databases. You must use PDO (if available):
Example (for mysql):
try {
$DBH = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8', 'user', 'password');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->prepare('SELECT * FROM php_maskiner ORDER BY timestamp DESC');
$STH->execute();
$STH->setFetchMode(PDO::FETCH_OBJ);
while($row = $STH->fetch()) {
$title = $row->title;
$entry = $row->entry;
$images = $row->images;
$img_url = $row->images;
$img_pack =
'<div class="mask3 span3">
<a rel="prettyPhoto" href="'.$img_url.'"><img src="'.$images.'"></a>
</div>';
}
$DBH = null;
} catch (PDOException $e) {
echo '<div class="alert alert-standard fade in">
<a class="close" data-dismiss="alert" href="#">×</a>
<strong>Can\'t read the database!</strong>
</div><br />'.$e;
}
And later in your code:
<?php echo
'<article class="span12 post">
'.$img_pack.'
<div class="inside">
<div class="span8 entry-content">
<div class="span12">
<h2>'.$title.'</h2>
<p>'.$entry.'</p>
</div>
</div>
</div>
</article>';
?>
And regarding the original question: make sure $img_url is not null.

Categories