I have this code that shows all the images inside 'images' directory but it is very annoying because all the images are showing on a single page :/
how could i split those images on multiple pages ?
here is the code
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<?php
$files = glob("images/*.*");
echo '<div id="design">';
for ($i=0; $i<count($files); $i++) {
$num = $files[$i];
if ($i%3==0){echo '<div class="Row">';}
echo '<img class="img" width="250px" height="250px" src="'.$num.'" alt="random image" />';
if ($i%3==0){echo '</div>';}
}
echo '</div>';
?>
Pagination! Here's a starting point:
// glob list of images
$files = glob('images/*');
// for consistency, you'll have to sort the resulting array...
natcasesort($files);
// get a page number from a query string e.g: ?page=1
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
// filter_input returns null if there is no page value in the qs,
// so let's check that and add a default value if we need to
$page = $page ?: 1;
// slice the array! get a subset of the files array based on
// an offset (page number) and length (results per page)
$resultsPerPage = 5;
$slice = array_slice($files, (($page - 1) * $resultsPerPage), $resultsPerPage);
You can now display your subset of results as normal. Of course you'll have to supply a series of links for each page... That's straightforward: get the length of your $files array, and use your $resultsPerPage value to figure out how many pages you need to display.
Hope this helps :)
First, try replacnig this line with something more rubust. This will return all files (image or anything else) unless you are sure that only image files are in the folder:
$files = glob("images/*.*");
The $files will result in an array with paths to the images, you can easily use this feature to display only the number of images you want in a page.
like this:
<?php
$imagesPerPage = 10;
if(!isset($_GET["start"]))
{
$start = 0;
}
else
{
$start = $_GET["start"];
}
$files = glob("images/*.*");
for($i = $start; $i < $start + $imagesPerPage; $i++)
{
if(isset($files[$i]))
{
echo "<img src=\"".$files[$i]."\" width=\"100\" height=\"100\" />\r\n";
}
}
$start = $start + $imagesPerPage;
echo "<br />\r\n";
echo "NEXT";
?>
You can follow the same rules and make a pervious link as well!
Please note, stopping (disabling) NEXT or Pervious links is up to yourself!
Related
I have a string that is for a blog, potentially it could have an unlimited number of images in this string, what I am trying to do is get all of the src="" and add a prefix to the url and use it as the hyperlink.
My string:
$test = 'Hello world
<img src="images/image1.jpg" />Line 2
<img src="images/image2.jpg" />Some text
<img src="images/image3.jpg" />';
I am able to prefix href. I am able to achieve this:
<img src="images/image1.jpg" />
<img src="images/image2.jpg" />
<img src="images/image3.jpg" />
This is my code so far:
$new = preg_replace('/(<img[^>]+src="([^\\"]+)"[^>]+\\/>)/','\\1',$test2);
echo $new;
I need to add foldername/as prefix in all the image src. What im trying to turn this into is the following:
<img src="foldername/images/image1.jpg" />
<img src="foldername/images/image2.jpg" />
<img src="foldername/images/image3.jpg" />
How can I do that?
To do this using DOMDocument rather than regex (a good reason is https://stackoverflow.com/a/1732454/1213708).
The code loads the HTML and then looks for all of the <img> tags. It first takes the value of src and adds the extra part to it. Then it creates a new <a> tag and also adds the (original) src value as the href attribute. It then replaces the <img> tag with the <a>, but adds the old value back into the <a>...
$dom = new DOMDocument();
$dom->loadHTML($test, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ( $dom->getElementsByTagName("img") as $image ) {
$src = $image->getAttribute("src");
$image->setAttribute("src", "foldername/".$src);
$anchor = $dom->createElement("a");
$anchor->setAttribute("href", $src);
$image->parentNode->replaceChild($anchor, $image);
$anchor->appendChild($image);
}
echo $dom->saveHTML();
Not that it matters now, but here is a parsing solution without regex. I prefer #NigelRen solution actually now that its posted. However, here is a way to build a list of image urls without regex that could be used for solving your issue and provide further exploration. I haven't tested the code but i'm pretty fair on it working.
<?php
$html = 'some html here';
$sentinel = '<img src="';
$quoteSentinel = '"';
$done = false;
$offset = 0;
$imageURLS = array();
while (!$done) {
$nextImageTagPos = strpos($html, $sentinel, $offset);
if ($nextImageTagPos !== false) {
//*** Parsing
// Find first quote
$quoteBegins = false;
for ($i = $nextImageTagPos; $i < $nextImageTagPos + 100; $i++) {
if (substr($html, $i, 1) == $quoteSentinel) {
$quoteBegins = $i;
break;
}
}
// Find ending quote
$quoteEnds = false;
if ($quoteBegins !== false) {
for ($i = $quoteBegins + 1; $i < $quoteBegins + 1000; $i++) {
if (substr($html, $i, 1) == $quoteSentinel) {
$quoteEnds = $i;
break;
}
}
if ($quoteEnds !== false) {
// Hooray! now we are getting somewhere
$imgUrlLength = ($quoteEnds - $quoteBegins) - 1;
$imgUrl = substr($html, $quoteBegins + 1, $imgUrlLength);
// ***Requirements
/*
I have a string that is for a blog, potentially it could have an unlimited number of images in this string, what i am trying to do is get all of the src="" and add a prefix to the url and use it as the hyperlink.
*/
// But for brevity lets skip requirements and build an array of URLs.
$imageURLS[] = $imgUrl;
$offset = $quoteEnds + 1;
}
}
// Extract url
}
else {
$done = true;
}
}
I'm trying to make this code insert a line break after 2 images when there are a total of 4 images. The Code listed below adds the line break after all images are displayed instead of after 2 images. Could someone please help me with this?
$images = "";
$i = 0;
while ($info = mysqli_fetch_array($imglist)) {
$style = $info['Style'];
$imgpath = $info['ImgPath'];
$standardimg = $info['StandardImg'];
$colorname = $info['ColorName'];
$smallimgwidth = $info['SmallImgWidth'];
$images = $images.
"<img src='$imgpath/$standardimg-Small.jpg'
alt = '$mill $style - $colorname'
title = '$mill $style - $colorname'
style = 'min-width:35px; max-width:$smallimgwidthpx;' / > ";
if (mysqli_num_rows($imglist) == 4) {
if ($i != 0 && $i % 2 == 1) {
echo '<br />';
}
}
$i++;
}
**Problem **
You are constructing the tags dynamically but in the process you are adding tags separately.
Solution
Add tag to your tags string being generated.
Code
$images = $images . '<br />';
In place of
echo '<br />';
Change
echo '<br />';
to
$images = $images . '<br />';
Just like that.
I little explanation: you're not 'grouping' br output with image output, since one goes into a variable (image) and the other is displayed immediately (br).
im trying to use a foreach loop with the plugin fotorama.
What im trying to do is load one half sized image for the main gallery image. Which i have working in a foreach, but i want to use a full image for the data-full tag but i cant get it to work.
This is the working code.
<div class="fotorama"
data-allowfullscreen="native"
data-nav="thumbs"
data-fit="scaledown"
data-width="100%"
data-height="100%"
data-arrows="true"
data-click="true"
data-swipe="true">
<?php
$dirname = "admin/image-upload/uploads/";
$images = glob($dirname."*.*");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
?>
</div>
this is what im trying to do.
<div class="fotorama"
data-allowfullscreen="native"
data-nav="thumbs"
data-fit="scaledown"
data-width="100%"
data-height="100%"
data-arrows="true"
data-click="true"
data-swipe="true">
<?php
$dirname = "admin/image-upload/uploads/";
$images = glob($dirname."*.*");
$dirname2 = "admin/image-upload/full/";
$images2 = glob($dirname2."*.*");
$fullImgs = "<img data-full=".$image2." src=".$image." /><br />";
foreach($fullImgs as $fullImg) {
echo $fullImg;
}
?>
</div>
thanks in advanced guys
Try this:
$dirname = "admin/image-upload/uploads/";
$images = glob($dirname."*.*");
$dirname2 = "admin/image-upload/full/";
$images2 = glob($dirname2."*.*");
$array = array_merge($images, $images2);
// Supossing both array have same length
$length = count($images);
for($i = 0; $j = $length; $i < $length; $i++, $j++) {
echo '<img data-full=".$images2[$j]." src=".$images[$i]." /><br />';
}
I think what you want is this:
<?php
$dirname = "admin/image-upload/uploads/";
$images = glob($dirname."*.*");
$dirname2 = "admin/image-upload/full/";
$images2 = glob($dirname2."*.*");
//assuming $images and $images2 are the same length...
foreach ($images as $k => $v) {
echo "<img data-full=".$images2[$k]." src=".$v." /><br />";
}
?>
Haven't tested, but should give the idea...
Your code won't work like this. If I understood you correctly you have the same image in big and small format in two different directories. To show them as pair you need to make a connection between those two files - because how should your script know which images belong together? You could use a database, but in your case I think it is easier to make a connection in the filename. For example, name the pictures in the directory for the small images
Image_7263.png
Image_0172.png
And so on. For the big images you simply append _BIG to the end of the name.
Then you use your foreach loop to loop through the directory for the small images. For each image in there, you append _BIG to the end of the filename and include it from the directory for the big ones.
$smallImages = glob ("/path/to/small/images/*.*");
foreach ($smallImages as $img)
{
$name = substr ($img, 0, strlen ($img)-4); //Remove the .png or .jpg
$bigImg = "/path/to/big/images/".name."_BIG.jpg"; // or whatever image type you are using
echo "<img data-full=\"".$bigImg."\" src=\"".$img."\" />
}
Asked this but still not getting the right code that fits in with this one. The reason why i don't want to change the code is because the pagination system works.
I've tried the arsort, rsort and many other sorting functions but the images still don't show the recent images that were in my directory.
<?php
$page = "";
$record_count = 100;
$dir = ('uploaded/');
$offset = ($page-1)*$record_count;
$files = glob("uploaded/*.*");
$files_filter = array(arsort($files,$record_count));//made sorting changes here
$images = array(arsort(glob($dir . '*.*', GLOB_BRACE)));
$latestimage = $images[0];
$large = '';
$allow = array('jpg','jpeg','gif','png', 'JPEG', 'JPG','GIF','PNG');
$i=0;
$open = opendir($dir);
// get each filename from directory
while (($file=readdir($open))!==false) {
// get extension
$ext=str_replace('.', '', strrchr($file, '.'));
// does it have a valid extension
if (in_array($ext, $allow))
$list[$i++]=$file; // store valid filename in array. use numerical indexing as makes it easier to display paginated images later
}
$perPage=20; // number of images to show per page
$total=count($list); // total number of images to show
$pages=ceil($total/$perPage); // number of pages is the number of images divided by how many per page
$thisPage=isset($_GET['pg'])?$_GET['pg']-1:0; // did user select a specific page? Note, pages on web are counted from 1 (not zero) so must subtract 1 for correct indexing
$start=$thisPage*$perPage; // calculate starting index into list of filenames
$perRow=2; // how many images to be shown on each row
// display quick index to pages. all pages except current page output as a link
print "Page ";
for ($i=0;$i<$pages;$i++)
if ($i==$thisPage)
print " ".($i+1);
else
print " <a href='?pg=".($i+1)."'>".($i+1)."</a>";
print "<tr>";
$imgCnt=0; // used to count number of images displayed and hence whether to wrap page. note, could use "for" index $i but this is computationally quicker
for ($i=$start;$i<$start+$perPage;$i++) {
// may be too few images to fill page, so check if we have a valid array index. if we don't output empty table cell so fussy browsers
// don't mis-display table due to missing cells
if (isset($list[$i]))
print "<td><a target='_new' href='$dir$large{$list[$i]}'><img style='height:180px;width:180px; border:2px solid black; margin:20px 0px 10px 10px; *margin:10px 0px 10px 20px;' style='border-color:#000000 ' border='1' src='$dir{$list[$i]}'></a></td>";
else
print "<td></td>";
$imgCnt+=1; // increment images shown
if ($imgCnt%$perRow==0) // if image count divided by number to show per row has no remainder than it's time to wrap
print "</tr><tr>";
}
print "</tr>";
closedir($open);
?>
You should index your list on modify time and slice your array when you want to show them.
Update: you should use krsort
// the paths
$dir = '/var/www/uploads/';
$urlPath = 'http://localhost/uploads/';
$allow = array('jpg','jpeg','gif','png', 'JPEG', 'JPG','GIF','PNG');
$open = opendir($dir);
while( $file = readdir( $open ) ){
$ext = strtoupper( pathinfo( $file, PATHINFO_EXTENSION ) );
if( in_array( $ext, $allow ) ){
$modifyTime = filemtime( $dir . $file );
$list[ $modifyTime ] = $file;
}
}
# reverse sort on key
krsort( $list );
$perPage = 20;
$total = count($list);
$pages = ceil($total/$perPage);
$thisPage = isset($_GET['pg'])?$_GET['pg']-1:0;
$start = $thisPage*$perPage;
echo "Page ";
// show pages
for ($i=0;$i<$pages;$i++):
if ($i==$thisPage) :
print " ".($i+1);
else :
print " <a href='?pg=".($i+1)."'>".($i+1)."</a>";
endif;
endfor;
// show images
$items = array_slice( $list, $start, $perPage );
foreach( $items as $image ){
echo "<br/> " . $image . "<br/>";
echo "<a target='blank' href='" . $urlPath . $image . "'><img width='100' height='100' src='" . $urlPath . $image . "'/></a>";
echo "<br/>";
}
closedir($open);
Read more on array_slice and krsort
Im using glob() to find any image files matching a rule.
I'm using the following code:
$photo = glob(($_SERVER['DOCUMENT_ROOT'] .'/stocklist/photo/'.$row['Scientific'].'*.jpg'));
print_r(glob(($_SERVER['DOCUMENT_ROOT'] .'/stocklist/photo/'.$row['Scientific'].'*.jpg')));
Which produces the following:
Array ( [0] => /var/www/web/stocklist/photo/Pituophis deppei jani.jpg
[1] => /var/www/web/stocklist/photo/Pituophis deppei jani1.jpg )
Then when i echo the images to the page using the code below, it displays 2 broken image icons...
$length = count($photo);
if($length) {
echo"<ul id='slide'>";
for ($i = 0; $i < $length; $i++) {
echo "<li><img src='".$photo[$i]."' alt='".$row['Name']."'></li>";}
echo "</ul><ul id='slide-pager'>";
for($i2 = 1; $i2 < $length+1; $i2++) {
echo "<li><a href='#".$i2."'>".$i2."</a></li>";
}
echo "</ul>";
}
else {
echo "<img src='/stocklist/photo/placeholder.jpg' class='img-right'><br clear='right'>";
}
Try changing to:
$photo = (glob('stocklist/photo/'.$row['Scientific'].'*.jpg'));
print_r(glob('stocklist/photo/'.$row['Scientific'].'*.jpg'));
That way your returned paths will already be relative to your public folder. You could also do a str_replace as #sergiu suggested, but why not just get rid of it entirely?