Hi all..

I am working on a website which require me to handle the image uploading and retrieval.
This website is some kind like an image gallery.

Straight to the point, i am having trouble in retrieving the last image to be displayed on my view.Clearly to be said, i capable of retrieving the first image from my image directory file, but when i want to retrieve the last image, my code fails to works.

This is the code of my controller :

<?php

class Gallery extends CI_Controller{

    function index(){

        $this->load->model('Gallery_model');


        if($this->input->post('upload')){
                $this->Gallery_model->do_upload();
        }

        $data['images'] = $this->Gallery_model->get_images();

        $this->load->view('gallery',$data);
}
}

This is my model for retrieving data from database :

<?php

class Gallery_model extends CI_Model{

    var $galery_path;
    var $gallery_path_url;

    function Gallery_model(){
        parent::__construct();
        $this->gallery_path = realpath(APPPATH . '../events_images');
    
        $this->gallery_path_url = base_url().'events_images/';
    }

    function do_upload() {

        $config = array(
          'allowed_types' => 'jpg|jpeg|gif|png',
          'upload_path' => $this->gallery_path,
          'max_size' => 2000
        );

        $this->load->library('upload',$config);
        $this->upload->do_upload();
        $image_data = $this->upload->data();
        
        $config = array(
          'source_image' => $image_data['full_path'],
          'new_image' => $this->gallery_path . '/thumbs',
          'maintain_ration' => true,
          'width' => 150,
          'height' => 100
        );

        $this->load->library('image_lib', $config);
        $this->image_lib->resize();

    }

    function get_images(){

        $files = scandir($this->gallery_path);
        $files = array_diff($files, array('.','..','thumbs'));

        $images = array();

        foreach ($files as $file) {
            $images [] = array(
                  'url' => $this->gallery_path_url . $file,
                  'thumb_url' => $this->gallery_path_url . 'thumbs/' . $file,
                );
        }
        return $images;
      }

}

And this is the view where i need to display the latest image uploaded by user:

<div id="gallery">

            <?php if (isset($images) && count($images)): ;
                 $count = count($images); // i try to get the last image
            ?>
            <div class="thumb">
              <a href="<?php echo $images[$count]['url']; ?>"> // and this is my problem
                  <img src="<?php echo $images[$count]['thumb_url']; ?>" />
              </a>
            </div>
            
            <?php else: ?>
              <div id="blank_gallery">Please Upload an Image</div >
            <?php endif; ?>

 </div`>

If you noticed, i am using $count = count($images); to get the number of image so that i could use it to retrieve the last image by writing this :

<img src="<?php echo $images[$count]['thumb_url']; ?>" />

but it turns out to be an error, why is that?
and how could i correct this?

Help me please.
Thank you in advance :)

Dani AI

Generated

Quick diagnosis: the view is indexing into an array in a way that can go out of bounds, and the array order produced by a directory scan is alphabetical — not necessarily upload order. That explains the occasional broken/incorrect thumbnail. Instead of trying to rely on index arithmetic, pick the newest file by its modification time (or ensure uploads get unique, time-based names) and guard every link you print.

A robust way to get the most-recent image (server-side) is to list only image files, sort them by filemtime descending, then take the first result. Example:

function get_latest_image($dir) {
  $files = glob($dir . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
  $files = array_filter($files, 'is_file');
  usort($files, function($a, $b) { return filemtime($b) - filemtime($a); });
  return $files ? basename($files[0]) : false;
}

In the view, check that the returned filename exists before echoing an <img> and escape the URL (e.g. htmlspecialchars). If you keep thumbnails, verify the thumb file exists and fall back to the original image if it doesn't.

Other practical tips that fixed similar problems:

  • Print the array you get from the model (var_dump/print_r) to confirm order and keys while debugging. this will show whether the model or view is at fault.
  • Check upload/image-lib errors ($this->upload->display_errors() and $this->image_lib->display_errors()); a failed resize can leave missing thumbnails.
  • Watch for typos in config keys (e.g. maintain_ratio) and ensure correct file permissions on the images/thumbs folders.
  • Avoid filename collisions by giving uploaded files unique names (timestamp or uniqid).

As noted, reversing the array can work sometimes, but sorting by modification time or using unique filenames is a more reliable, long‑term fix.

Recommended Answers

All 4 Replies

Hi!
Try next:

<img src="<?php echo $images[$count-1]['thumb_url'];?>" />

Hi!
Try next:

<img src="<?php echo $images[$count-1]['thumb_url'];?>" />

Hi there, its working great!!
but how you know it'll be working?

anyway , thank you so much :)

eh wait..but its not always working...at he some point, there is no image display at all (like it is the broken image link) and sometimes the images being displayed, its also not the last image being uploaded.

why is that happens?whats wrong with the array here?

Hi again!
Try next method: reverse your array using array_reverse() function, then just call first element in you reversed array like echo $reversed_array[0] <- There you will get the first element in reversed array that same as the last element in your previous non-reversed array.
f/e,

$array = array(0 => "first", 1 => "second");
echo "First element is " . $array[0] . "<br />";
$reversed_array = array_reverse($array);
echo "First element is " . $reversed_array[0];

output:

first
second

P.S.: it's really hard to explain in second language :)

commented: +++++++++++++ +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.