Sort image files in recent order - php

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

Related

How to display all images if they exist in a folder PHP?

I have a PHP script that scans a specified Movie directory then displays it styled on a webpage using for loop and php. The code is below. I tried using glob but once I have all the images in an array how do I compare them to the array with all of the movies then if the image and the movie folder match to display the image with the correct name?
<?php
// set dir to the directiry you want to index
$dir = 'Movies/';
// scanning the directory you set
$scan = scandir($dir);
// I have this value at 11 because the first movie shows up
// in the 11th file in the array
$file = 11;
// This then removes the first useless files from our array
$scanned = array_slice($scan, $file);
// gets the amount of files
$FileNum = count($scanned);
// display all images and fanart
$images = glob('*.jpg');
// for loop that goes through the array
for ($i = 0; $i <= $FileNum; $i++) {
// gives the class for styling
echo '<li class="image">';
this is problem bit
// check if there is fanart/images in the folders
if (file_exists($dir . $scanned[$i] . $images)) {
// if there is images display them styled
echo '<img id="box1" src="' . $dir . $scanned[$i] . '*.jpg' . '" width="280" height="150" />';
} else {
// if not then display default image
echo '<img id="box1" src="http://placehold.it/280x150" width="280" height="150" />';
}
// make the box clickable to where the folder is located
echo '<a href="'. $dir . $scanned[$i] .'">';
// display the name of the movie and some JS
echo '<span class="text-content"><span>' . $scanned[$i] .'<br><br><i class="fa fa-4x fa-play-circle-o"></i><br><br><i class="fa fa-chevron-down" onclick="openNav()" aria-hidden="true"></i></span></span> </a>';
}
The file structure is as follows
`MOVIES---
\--random movies
\--mp4 and .jpg files`
To clarify my question is - Is there a way to check if a file exists, and if it does then put it in an array? I've tried using glob but that can't check if the file exists.
Well there is an * in your echo i don't think it needs to be there.
And if your movie directory gets updated, or the images. Then your script does not work anymore. Because of the hard slicing (11th file).
Maybe this will work for you:
<?php
// movies
$dir = "movies/";
$files = scandir($dir);
$movies = array();
$images = array();
foreach ($files as $file) {
// check for the mime type:
$mime = mime_content_type($dir . $file);
$type = substr($mime, 0,5);
$filename = pathinfo($dir . $file, PATHINFO_FILENAME);
if ($type == "video") $movies[] = $file;
if ($type == "image") $images[] = $filename;
}
foreach ($movies as $movie) {
$placeholder = true;
foreach($images as $image) {
if (strpos($movie, $image) !== false) {
$placeholder = false;
continue;
}
}
if ($placeholder) {
echo $movie . " - placeholder<br>";
} else {
echo $movie . " - image<br>";
}
}
It works with the mime-type.

php count files from multiple folders and echo total

I have a php code that will display the amount of files that i have in a folder.
Code: This will echo this on my page, "There are a total of 119 Articles"
$directory = "../health/";
if (glob($directory . "*.php") != false) /* change php to the file you require either html php jpg png. */ {
$filecount = count(glob($directory . "*.php")); /* change php to the file you require either html php jpg png. */
echo "<p>There are a total of";
echo " $filecount ";
echo "Articles</p>";
} else {
echo 0;
}
Question:
I am wanting to count the files from 27 or more folders and echo the total amount of files.
Is there away i can add a list of folders to open such as:
$directory = "../health/","../food/","../sport/";
then it will count all the files and display the total "There are a total of 394 Articles"
Thanks
Yes you can:
glob('../{health,food,sport}/*.php', GLOB_BRACE);
Undoubtedly, this is less efficient than clover's answer:
$count = 0;
$dirs = array("../health/","../food/","../sport/");
foreach($dirs as $dir){
if($files = glob($dir."*.php")){
$count += count($files);
}
}
echo "There are a total of $count Articles";
A simple answer is to just use an array and a loop. It is something you could have figured out yourself.
$directories = array('../health/', '../food/', '../sport/');
$count = 0;
foreach ($directories as $dir) {
$files = glob("{$dir}*.php") ?: array();
$count += count($files);
}
echo "<p>There are a total of {$count} articles</p>";
But #clover's answer is better.
As usual, it's often much better to divide your problem. E.g.:
Obtain the files (See glob).
Count the files of a glob result (Write a function that takes care of two the FALSE and Array cases.).
Do the output (don't do the output inside the other code, do it at the end, use variables (as you already do, just separate the output)).
Some Example Code:
/**
* #param array|FALSE $mixed
* #return int
* #throws InvalidArgumentException
*/
function array_count($mixed) {
if (false === $mixed) {
return 0;
}
if (!is_array($mixed)) {
throw new InvalidArgumentException('Parameter must be FALSE or an array.');
}
return count($mixed);
}
$directories = array("health", "food", "string");
$pattern = sprintf('../{%s}/*.php', implode(',', $directories));
$files = glob($pattern, GLOB_BRACE);
$filecount = array_count($files);
echo "<p>There are a total of ", $filecount, " Article(s)</p>";
You could use the opendir command explained here:
http://www.php.net/manual/en/function.opendir.php
combined with the example shown on previous link:
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
Basically opening the folder you first go through and in a loop count every singel item that is not a folder.
Edit:
Seems like someone has given a simpler solution than this.

Pagination Filtered XML file

I want to paginate the following filtered results from xml file:
<?php
//load up the XML file as the variable $xml (which is now an array)
$xml = simplexml_load_file('inventory.xml');
//create the function xmlfilter, and tell it which arguments it will be handling
function xmlfilter ($xml, $color, $weight, $maxprice)
{
$res = array();
foreach ($xml->widget as $w)
{
//initially keep all elements in the array by setting keep to 1
$keep = 1;
//now start checking to see if these variables have been set
if ($color!='')
{
//if color has been set, and the element's color does not match, don't keep this element
if ((string)$w->color != $color) $keep = 0;
}
//if the max weight has been set, ensure the elements weight is less, or don't keep this element
if ($weight)
{
if ((int)$w->weight > $weight) $keep = 0;
}
//same goes for max price
if ($maxprice)
{
if ((int)$w->price > $maxprice) $keep = 0;
}
if ($keep) $res[] = $w;
}
return $res;
}
//check to see if the form was submitted (the url will have '?sub=Submit' at the end)
if (isset($_GET['sub']))
{
//$color will equal whatever value was chosen in the form (url will show '?color=Blue')
$color = isset($_GET['color'])? $_GET['color'] : '';
//same goes for these fellas
$weight = $_GET['weight'];
$price = $_GET['price'];
//now pass all the variables through the filter and create a new array called $filtered
$filtered = xmlfilter($xml ,$color, $weight, $price);
//finally, echo out each element from $filtered, along with its properties in neat little spans
foreach ($filtered as $widget) {
echo "<div class='widget'>";
echo "<span class='name'>" . $widget->name . "</span>";
echo "<span class='color'>" . $widget->color . "</span>";
echo "<span class='weight'>" . $widget->weight . "</span>";
echo "<span class='price'>" . $widget->price . "</span>";
echo "</div>";
}
}
Where $xml->widget represents the following xml:
<hotels xmlns="">
<hotels>
<hotel>
<noofrooms>10</noofrooms>
<website></website>
<imageref>oias-sunset-2.jpg|villas-agios-nikolaos-1.jpg|villas-agios-nikolaos-24​.jpg|villas-agios-nikolaos-41.jpg</imageref>
<descr>blah blah blah</descr>
<hotelid>119</hotelid>
</hotel>
</hotels>
</hotels>
Any good ideas?
Honestly if you're already using XML and want to do Pagination then use XSL. It'll allow for formatting of the results and for pagination with ease. PHP has a built in XSL transformer iirc
See http://www.codeproject.com/Articles/11277/Pagination-using-XSL for a decent example.

Splitting image result into Pages

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!

Random image picker PHP

$images = array();
$images[0][0] = "boxes/blue.jpg";
$images[0][1] = "blah.html";
$images[1][0] = "boxes/green.jpg";
$images[1][1] = "blah.html";
$images[2][0] = "boxes/orange.jpg";
$images[2][1] = "blah.html";
$images[3][0] = "boxes/pink.jpg";
$images[3][1] = "blah.html";
$images[4][0] = "boxes/purple.jpg";
$images[4][1] = "blah.html";
$images[5][0] = "boxes/red.jpg";
$images[5][1] = "blah.html";
$images[6][0] = "boxes/yellow.jpg";
$images[6][1] = "blah.html";
$i = 0;
*echo "<a href='" . $images[0][1] . "'><img src='" . $images[0][0] . "' /></a>";
$boxes = array();
while($i<5)
{
$rand = rand(0,(sizeof($images)-1));
//echo $rand;
$slice = array_splice($images, $rand);
$boxes[$i] = $slice;
$i++;
}*
I am trying to get a random image picker to choose from a list of images provided by the $images array. However, I am unable to fill the $boxes array with anything other than "Array". Can anyone tell me why? Any help is much appreciated
UPDATE
I am now using the code below and it breaks whenever it comes across an empty element. Unless i am very much mistaken, shouldn't splice patch up holes like that?
$rand = rand(0,(sizeof($images)));
array_splice($images, $rand);
$i = 0;
while($i<5)
{
echo "<a href='" . $images[$i][1] . "'><img src='" . $images[$i][0] . "' /></a>";
$i++;
}
This might be a nicer way of doing it:
foreach (array_rand($images, 5) as $key) {
$boxes[] = $images[$key];
}
Slightly off topic, but wouldn't it be easier in this case (picking 5 items from a list of 6) just to pick one element and discard it from the original array, and then use the original? This will also ensure you do not get duplicates in the resultant array.
I realise that you may have more than 6 items in the original, and may want less than 5 from it, but I'm talking specifically about the example posted.
array_splice() returns an array.
You can try something like this:
while($i<5)
{
$rand = rand(0,(sizeof($images)-1));
$boxes[$i] = $images[$rand];
$i++;
}

Categories