Basic Image Gallery With CodeIgniter

June 27th, 2010 by aditia rahman / 34 Comments  


CodeIgniter is quite mature framework to creating web application, the built in libraries and helper very helpful to creating most feature in web application, this post I want to create very basic image gallery using CodeIgniter, the the built in libraries that I used are File Uploading, Image Manipulation and Pagination, whereas the used helper is URL Helper, and here’s we go

First open the config.php in folder system/application/config/ and set the CodeIgniter base_url

$config['base_url'] = "http://localhost/ci_gallery/";

Next load the URL Helper in autoload.php in the same folder as above file

$autoload['helper'] = array('url');

Now create the image controller in file image.php inside folder system/application/controller and add this attribute inside the image class

private $data = array(
    'dir' => array(
        'original' => 'assets/uploads/original/',
        'thumb' => 'assets/uploads/thumbs/'
    'total' => 0,
    'images' => array(),
    'error' => ''

The varible above created to store the default directory path, total images inside the folder, and error message while uploading the image, the value of those variables will set in the next function. Add the function index inside the Image class

public function index($start = 0)
    if ($this->input->post('btn_upload')) {


    $c_paginate['base_url'] = site_url('image/index');
    $c_paginate['per_page'] = '9';
    $finish = $start + $c_paginate['per_page'];

    if (is_dir($this->data['dir']['thumb']))
        $i = 0;
        if ($dh = opendir($this->data['dir']['thumb'])) {
            while (($file = readdir($dh)) !== false) {
                // get file extension
                $ext = strrev(strstr(strrev($file), ".", TRUE));
                if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png') {
                    if ($start <= $this->data['total'] && $this->data['total'] < $finish) {
                        $this->data['images'][$i]['thumb'] = $file;
                        $this->data['images'][$i]['original'] = str_replace('thumb_', '', $file);

    $c_paginate['total_rows'] = $this->data['total'];


    $this->load->view('images/index', $this->data);

Inside the index function it called the upload function when upload button clicked by the user, and the pagination class is configured, the script is looping through the folder find whether the file is image or not, and now the upload function

private function upload()
    $c_upload['upload_path']    = $this->data['dir']['original'];
    $c_upload['allowed_types']  = 'gif|jpg|png|jpeg|x-png';
    $c_upload['max_size']       = '500';
    $c_upload['max_width']      = '1600';
    $c_upload['max_height']     = '1200';
    $c_upload['remove_spaces']  = TRUE;

    $this->load->library('upload', $c_upload);

    if ($this->upload->do_upload()) {

        $img = $this->upload->data();

        // create thumbnail
        $new_image = $this->data['dir']['thumb'].'thumb_'.$img['file_name'];

        $c_img_lib = array(
            'image_library'     => 'gd2',
            'source_image'      => $img['full_path'],
            'maintain_ratio'    => TRUE,
            'width'             => 100,
            'height'            => 100,
            'new_image'         => $new_image

        $this->load->library('image_lib', $c_img_lib);
    } else {
        $this->data['error'] = $this->upload->display_errors();

You can see on the code above, thumbnail is created every time image is uploaded to maximum size 100 x 100 pixels, and putted in the different folder , the last function is delete image

public function delete($ori_img)

The function getting the parameter as image name and deleted the orginal and thumbnail image, and now the view file index.php inside folder system/application/views/images/

<!-- the javascript code to load clicked image and changing the class-->
<script type="text/javascript">
    function changepic(img_src, obj) {
        document["img_tag"].src = img_src;
        var thumbs = document.getElementsByName("thumb");
        for (var i = 0; i < thumbs.length; i++) {
            var tmp_id = "thumb_" + i;
            document.getElementById(tmp_id).setAttribute("class", "thumb");
        document.getElementById(obj).setAttribute("class", "thumbclick");
        var ori_img = img_src.replace("thumb_", "");
        document.getElementById("detimglink").setAttribute("href", ori_img);

<!-- the view file -->
<div id="container">
    <div id="imgshow">
        <?php if (isset($images[0])) { ?>
        <a href="<?php echo base_url().$dir['original'].$images[0]['original']; ?>" target="_blank" id="detimglink">
            <img class="imgdet" name="img_tag" src="<?php echo base_url().$dir['original'].$images[0]['original']; ?>" width="500"/>
        <?php } ?>

    <div id="imglist">
        <form enctype="multipart/form-data" id="fupload" method="post" action="<?php echo site_url('image/'); ?>">
            <input name="userfile" type="file" size="20"/>
            <input type="submit" name="btn_upload" value="Upload &uarr;" class="btnupload"/>
            <?php if (isset ($error)) { ?>
            <div class="error"><?php echo $error; ?></div>
            <?php } ?>

        <div class="clear"></div>

        <div class="imgfor">
        <!-- Looping Array Image -->
        <?php foreach($images as $key => $img) { ?>
        <div class="imgbox">
                <a href="javascript:" onclick="changepic('<?php echo base_url().$dir['original'].$img['original']; ?>', 'thumb_<?php echo $key; ?>');">
                <img class="thumb" name="thumb" id="thumb_<?php echo $key; ?>" src="<?php echo base_url().$dir['thumb'].$img['thumb']; ?>"/>
            <div class="dadel">
            <a class="adel" href="<?php echo site_url('image/delete/'.$img['original']); ?>">
        <?php } ?>
        <div class="clear"></div>
        <div class="clear"></div>

        <div class="bottom">
            <?php echo $total; ?> Image(s)

        <div class="bottom">
            <?php echo $this->pagination->create_links(); ?>

    <div class="clear"></div>

</div> <!-- end div container -->

The result is like the image below, i’m not posting the css code in here but you can see on the demo (sorry, the upload and delete feature disabled) or the downloadable source code, and the code included some sample image so the size is bigger than fresh copy CodeIgniter.


        submit to reddit Delicious

34 Comments Leave a Comment Subscribe RSS

  • suresh.katiki says:

    Thanks for sharing this. It was really great.

  • lely says:

    when i try download and run it, i found this error
    A PHP Error was encountered

    Severity: Warning

    Message: Wrong parameter count for strstr()

    Filename: controllers/image.php

    Line Number: 38

    how to fixed it
    thanks for sharing

    • I’m creating this using php 5.3, if you using the older php function it will become error like that

      or if you still want to use the older php version you can replace the code in controllers/image.php line 38 with this code
      $ext = substr_replace(strstr($file, “.”), “”, 0, 1);

      basically this line of code is to get the extension of the image file, or you can create your own version to get this

      • lely says:

        thanks for fast reply,
        after i change the code and appear new error, like this…
        A PHP Error was encountered

        Severity: Notice

        Message: Use of undefined constant � – assumed ‘�’

        Filename: controllers/image.php

        Line Number: 38
        A PHP Error was encountered

        Severity: Notice

        Message: Use of undefined constant �� – assumed ‘��’

        Filename: controllers/image.php

        Line Number: 38

        • have you write the correct code??
          I have tested error like that will appear if I forgot put the $ sign in file variable

          the error part is something like this
          Message: Use of undefined constant file – assumed ‘file’

          • lely says:

            `Ok thanks, i found the problem in here similiar but different anyway thanks for sharing the source code, it is helpful for my assignment.

  • sb says:

    Grazie per il prezioso tutorial , molto utile per chi alle prime armi con questo fantastico framework.

  • guest says:

    Hi can you please upload this source code again ? Because, not working any more =(

  • guest says:

    Also, how do you create more complex gallery like folders/categories for example ?

    • first come in my mind is using the database, adding the table like categories, tag, album, user, etc.

      otherwise just exploring the folder some kind file manager but filter only the images file

  • Simon says:

    Big thanks.
    Hey the delete function doesn’t work for me. I copied your code well and everything works fine except for the delete. It displays the right link when im over the delete function(image/delete/blabla.jpg) but when i click it just reload the page(as i set it) and image and thumbnail both still there :(

    • Simon says:

      A PHP Error was encountered

      Severity: Warning

      Message: unlink(_/uploads/original/hello_jpg)
      [function.unlink]: No such file or directory

      Filename: controllers/image.php

      Line Number: 95

      _ is my assets folder

  • Simon says:

    No js errors. well i checked them . exists.

    When i click on [function.unlink] ->
    Severity: Warning

    Message: unlink(_/uploads/original/function_unlink) [function.unlink]: No such file or directory

    Filename: controllers/image.php

    Line Number: 108


  • Richard says:

    Nice one!
    It works perfectly, except I want to be able to upload multiple files at once. I tried several options but “print_r(array_values($this->upload->data())); ” always got me the last one of my selection…
    Please help!

  • dan says:

    I was trying to move this to CI 2.0 but i’m not familiar enough with CI.
    has anyone done this?

  • dan says:

    never mind i just needed the assets

  • Herta Debose says:

    I want to gain more followers by submitting my pictures to blogs. Like when people click through, they will link to my blog.

  • matipa says:


    I’ll try your image gallery. Thanks!

  • yus says:

    how to insert in the database the file name?

  • abc says:

    delete function is not working propely,When uploaded image is deleted and again upload so its appears twice or more times
    please tell me solution to avoid this sort of bug as soon as possible.any help would be highly appreciable.looking forward to your reply

  • abc says:

    please reply quickly its on urgent basis

  • abc says:

    problem solved:-)

  • arvind says:

    for me pagination is not working i copied ur code and changed into codeigniter 2.0 everything is working fine except the pagination it doesn’t show any error the link is not working

    • Arol says:


      I have the same problem. I’m working with CI 2 and the pagination not work. When I click on next page just add in the url /9. The “/9″ is the count of image for page.

      Any idea about this?

      I’m sorry for my english

  • Jhonny says:

    I have the following problems:

    Severity: Warning

    Message: Invalid argument supplied for foreach()

    Filename: views/galeriaingresado.php

    Line Number: 158

    // $img){ ?>


    Severity: Notice

    Message: Undefined property: CI_Loader::$pagination

    Filename: views/galeriaingresado.php

    Line Number: 185

    //pagination->create_links(); ?>


    Fatal error: Call to a member function create_links() on a non-object in C:\xampp\htdocs\Age\application\views\galeriaingresado.php on line 185

    I wanted to integrate it into my project but has been a fiasco since no how.

    I do not speak English, helped me with Sorry

  • casualcases says:

    Thanks a lot .This really saved my time.You re great

  • Mohit Bumb says:

    Thanks you saved my 60% time.

  • udaya says:

    hi , can you extend this using ajax. i mean sending post data to the upload function via ajax.

Leave a Comment