Jump to content

Sort images by newest to oldest


cobusbo

Recommended Posts

Hi I have the following script to show images from a directory and make thumbs , but I would like to know how to sort the images from newest to oldest and how to implement it in this script

I'm a rookie at this...

Many Thanks in Advance!

<?php
    # SETTINGS
    $max_width = 800;
    $max_height = 600;
    $per_page = 10;

    $page = $_GET['page'];

    $has_previous = false;
    $has_next = false;

    function getPictures() {
        global $page, $per_page, $has_previous, $has_next;
        if ( $handle = opendir(".") ) {
            $lightbox = rand();
            echo '<ul id="pictures">';

            $count = 0;
            $skip = $page * $per_page;

            if ( $skip != 0 )
                $has_previous = true;

            while ( $count < $skip && ($file = readdir($handle)) !== false ) {
                if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
                    $count++;
            }
            $count = 0;
            while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
    if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {

        // make the thumbs directory if it doesn't already exist
        if ( ! is_dir('thumbs') ) {
            mkdir('thumbs');
        }
        // make a thumbnail if it doesn't already exist
        if ( ! file_exists('thumbs/'.$file) ) {
            makeThumb( $file, $type );
        }

        // create a link to $file, add the thumbnail
        echo '<li><a href="' . $file . '">';
        echo '<img src="thumbs/'.$file.'" alt="" /></a></li>';
        $count++;
echo substr($file,strlen($folder),strpos($file, '.')-strlen($folder));

    }
}

            echo '</ul>';

            while ( ($file = readdir($handle)) !== false ) {
                if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
                    $has_next = true;
                    break;
                }
            }
        }
    }

    function getPictureType($file) {
        $split = explode('.', $file); 
        $ext = $split[count($split) - 1];
        if ( preg_match('/jpg|jpeg/i', $ext) ) {
            return 'jpg';
        } else if ( preg_match('/png/i', $ext) ) {
            return 'png';
        } else if ( preg_match('/gif/i', $ext) ) {
            return 'gif';
        } else {
            return '';
        }
    }

    function makeThumb( $file, $type ) {
        global $max_width, $max_height;
        if ( $type == 'jpg' ) {
            $src = imagecreatefromjpeg($file);
        } else if ( $type == 'png' ) {
            $src = imagecreatefrompng($file);
        } else if ( $type == 'gif' ) {
            $src = imagecreatefromgif($file);
        }
        if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
            $newW = $oldW * ($max_width / $oldH);
            $newH = $max_height;
        } else {
            $newW = $max_width;
            $newH = $oldH * ($max_height / $oldW);
        }
        $new = imagecreatetruecolor($newW, $newH);
        imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
        if ( $type == 'jpg' ) {
            imagejpeg($new, 'thumbs/'.$file);
        } else if ( $type == 'png' ) {
            imagepng($new, 'thumbs/'.$file);
        } else if ( $type == 'gif' ) {
            imagegif($new, 'thumbs/'.$file);
        }
        imagedestroy($new);
        imagedestroy($src);
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UFT-8" />
<title>Pictures</title>
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
<style type="text/css">
body {
    width:780px;
    margin:0 auto;
}
#pictures li {
    float:left;
    height:<?php echo ($max_height + 10); ?>px;
    list-style:none outside;
    width:<?php echo ($max_width + 10); ?>px;
    text-align:center;
}
img {
    border:0;
    outline:none;
}
.prev {
    float:left;
}
.next {
    float:right;
}
</style>
</head>
<body>

<?php getPictures(); ?>

<div style="clear:both"></div>

<?php
    if ( $has_previous )
        echo '<p class="prev"><a href="?page='.($page - 1).'">← Previous Page</a></p>';

    if ( $has_next )
        echo '<p class="next"><a href="?page='.($page + 1).'">Next Page →</a></p>';
?>

<div style="clear:both"></div>

<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
</body>
</html>
Link to comment
Share on other sites

You will need to rewrite your code so you are fetching the images and also generate their thumbnail. Then you can sort them in the order your require. Once you have sorted the images you can then begin to show them

 

You'd being first by fetching the images (I prefer to use glob for specifically returning certain files by their file extension by using the GLOB_BRACE flag).

 

I'd Then add the filename and the filemtime (returns the timestamp the image was created/last modified) into separate arrays. The array containing the filemtime values will be used to sort the files oldest to newest later using array_multisort.

 

At this point the thumbnails can be generated

$images = array();
$times = array();
// read the images folder for jpg, jpeg, png and gif images using glob() - see http://php.net/glob for info
foreach(glob('images/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $image)
{
    // add the file to the images array
    $images[] = $image;

    // get the files creation/last modification timestamp add it to the times array. 
    // This array will be used later to sort the images array
    $times[] = filemtime($image);

   // generate the image thumbnail if needed
   if(!file_exists('thumbs/' . $image))
   {
       // calling your makeThumb function, pass it the file extension for the image
       makeThumb(basename($image), pathinfo($image, PATHINFO_EXTENSION));
   }
}

After the images have been gathered, use array_multisort to sort the $times array in descending order. This will cause the $images array to also be sorted newest to oldest too.

// using the times array, to sort the images newest to oldest
array_multisort($times , SORT_DESC, 
                $images);

Now the images can be listed  showing the newest images first

echo '<ul>';
foreach($images as $image)
{
    echo '<li><a href="' . $image. '">';
    echo '<img src="thumbs/'.$image.'" alt="" /></a></li>';
}
echo '</ul>';

NOTE: I have cut a lot of your original code out. You will need to modify your getPicutres function in order for the above code to work

Edited by Ch0cu3r
Link to comment
Share on other sites

Hello cobusbo! Did you write the script you posted or did you find it somewhere? What you should do is to create a couple of files in a directory and just create small, standalone PHP file. In this file, try to list all the name of the files in this directory. Then, try to do it by date. You should be able to do it with what Ch0cu3r said. 

 

Tell me if you're able to do that or not. :)

Link to comment
Share on other sites

Hello cobusbo! Did you write the script you posted or did you find it somewhere? What you should do is to create a couple of files in a directory and just create small, standalone PHP file. In this file, try to list all the name of the files in this directory. Then, try to do it by date. You should be able to do it with what Ch0cu3r said. 

 

Tell me if you're able to do that or not. :)

Hi I found it http://www.lateralcode.com/simple-php-gallery-pagination/

 

I made a few changes to display names etc... already the only thing that is keeping me back from publishing is the sort function. The reason I chosen this file is because it plain and simple, and I don't want to add any fancy styles etc.. and Im planning on launching it via a mobi portal on an IM called "mxit" so I need to keep everything simple since not all functions are supported.

I tried adding the above code into my original code. but it didn't work. I'm a beginner coder and most of the things are totally new for me. By looking at the PHP manual they show you the functions but not good examples.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.