New Website

I've made a new website, as lynx.io is dead. You can find it here: http://macr.ae/—it's similar in format to lynx.io, but has better articles, and they're all written by me.

JavaScript disabled

While it will still mostly work, a lot of this site's functionality relies on JavaScript - please enable it for the best experience.

Creating a (very) basic image upload script using Codeigniter

In this article I will show you a very basic image upload script I wrote using Codeigniter. I will also show you how it works, and suggest how it could be improved. Feel free to take the code from here and adapt it for your own website.

Codeigniter is an open source web application framework written in PHP. You can find its website here, with a summary of its features and why you should use it. I've been using it because I want to compare all the major PHP frameworks, such as CakePHP, Symfony etc. I've started with Codeigniter, and I will be writing about my experience with other frameworks. The first script I wrote in Codeigniter was a very basic script, an image upload script. The aim was to create a script that could be easily adapted to include, for example, a login script. At the moment all it does it upload the image, encrypt the filename, and put it in a directory of your choice. It then inserts a row into the database with the image information, and send the user a link to their image.

The SQL Table

First, we need to create a table.

CREATE TABLE upload (
  id int(11) NOT NULL AUTO_INCREMENT,
  title varchar(100) NOT NULL,
  file varchar(100) NOT NULL,
  width int(11) NOT NULL,
  height int(11) NOT NULL,
  type varchar(100) NOT NULL,
  size int(11) NOT NULL,
  date int(11) NOT NULL,
  PRIMARY KEY (id)
);

It may need some minor adjustment, but it does the job.

/system/application/controller/upload.php

<?php

class Upload extends Controller {
    function __construct() {
        parent::Controller();
        $this->load->helper(array('form', 'url'));
    }

    function index() {
        $this->load->view('upload_form', array('error' => ' ' ));
    }

    function do_upload() {
        $config = array(
            'upload_path'   => './uploads/',
            'allowed_types' => 'gif|jpg|png',
            'max_size'      => '100',
            'max_width'     => '1024',
            'max_height'    => '768',
            'encrypt_name'  => true,
        );

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

        if (!$this->upload->do_upload()) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('upload_form', $error);
        } else {
            $upload_data = $this->upload->data();
            $data_ary = array(
                'title'     => $upload_data['client_name'],
                'file'      => $upload_data['file_name'],
                'width'     => $upload_data['image_width'],
                'height'    => $upload_data['image_height'],
                'type'      => $upload_data['image_type'],
                'size'      => $upload_data['file_size'],
                'date'      => time(),
            );

            $this->load->database();
            $this->db->insert('upload', $data_ary);

            $data = array('upload_data' => $upload_data);
            $this->load->view('upload_success', $data);
        }
    }
}

/system/applications/views/upload_form.php

<!DOCTYPE html>
<html>
<head>
    <title>Upload Form</title>
    <style type="text/css">
        body {
            text-align: center;
        }
    </style>
</head>
<body>
    <?php echo $error;?>
    <?php echo form_open_multipart('upload/do_upload'); ?>
        <input type="file" name="userfile" size="20" />
        <br />
        <input type="submit" value="upload" />
    </form>
</body>
</html>

/system/applications/views/upload_success.php

<!DOCTYPE html>
<html>
<head>
    <title>Successfully Uploaded</title>
    <style type="text/css">
        body {
            text-align: center;
        }
    </style>
</head>
<body>
    <h2>Your file was successfully uploaded</h2>
    <p>
        <?php echo anchor('uploads/' . $upload_data['file_name'], 'Click here to view your upload') ?>
        <br />
        <?php echo anchor('upload', 'Upload Another File!'); ?>
    </p>
</body>
</html>

You will also need to create a directory in the root Codeigniter directory called "uploads" with permissions 777, as this is where the images will be stored (by default - you can change it).

 

I will now work through all the code, showing you what everything does and how it works. I will assume you have a basic knowledge of how Codeigniter works; if you don't, I would suggest that you go read a tutorial!

/system/application/controller/upload.php

<?php

class Upload extends Controller {
    function __construct() {
        parent::Controller();
        $this->load->helper(array('form', 'url'));
    }

    function index() {
        $this->load->view('upload_form', array('error' => ' ' ));
    }

The contents of the __construct() function is standard Codeigniter code - it just calls the parent constructor (giving it stuff like the load object) and loads the form and url helpers. index() is the default code - if no other function is specified, index() is ran. index() just displays the upload form.

    function do_upload() {
        $config = array(
            'upload_path'   => './uploads/',
            'allowed_types' => 'gif|jpg|png',
            'max_size'      => '100',
            'max_width'     => '1024',
            'max_height'    => '768',
            'encrypt_name'  => true,
        );

The default configuration settings for the image upload script.

Load the upload library using the config settings defined above.

        if (!$this->upload->do_upload()) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('upload_form', $error);
        }

Attempt to upload the image. If the upload fails, it gets the error and displays it to the user. If it succeeds...

        else {
            $upload_data = $this->upload->data();
            $data_ary = array(
                'title'     => $upload_data['client_name'],
                'file'      => $upload_data['file_name'],
                'width'     => $upload_data['image_width'],
                'height'    => $upload_data['image_height'],
                'type'      => $upload_data['image_type'],
                'size'      => $upload_data['file_size'],
                'date'      => time(),
            );

            $this->load->database();
            $this->db->insert('upload', $data_ary);

            $data = array('upload_data' => $upload_data);
            $this->load->view('upload_success', $data);
        }
    }
}

If the upload succeeds, it works out what data it wants to insert into the database, then inserts it. It then loads the upload_success template file.

The view files

The view files are both simple HTML, with a couple of Codeigniters features:

anchor()

anchor() creates an anchor element based on the local site URL. It has three parameters:

anchor($url, $text, $attributes)

The first parameter, $url, will be appended to the base url to produce the final url. It can either be an array or a string, so both of these examples would produce the same thing:

<?php

anchor('path/to/file.php');
anchor(array('path', 'to', 'file.php'));

The second segment is the text of the link. If you leave it blank, the URL will be used.

<?php

anchor('file.php', 'Click here!');

This will produce <a href="example.com/file.php">Click here!</a>.

The third parameter can contain a list of attributes you would like added to the link. The attributes can be a simple string or an associative array:

<?php

anchor('file.php', 'Click here!', array('style' => 'color: red'));

That would produce <a href="example.com/file.php" style="color: red">Click here!</a>.

form_open_multipart()

form_open_multipart is exactly the same as form_open, except it adds a multipart attribute, which is necessary to upload files with. form_open creates an opening form tag with your base url, and will also let you add form attributes and hidden fields. For example:

<?php echo form_open_multipart('upload/do_upload'); ?>

This would print:

<form method="post" action="http:/example.com/upload/do_upload">

Find out more about the form helper here.

What you could add to this script

The script I demonstrated to you is very basic, so here is a list of a few things you could do to it to improve it.

That's all for today, please share where you have used this code in a comment :)

About Callum Macrae:

Callum Macrae is the founder of lynx.io and a JavaScript developer from the United Kingdom. He is currently writing his first book, to be published by O'Reilly Media.

You can view more articles by this author here.

Tags: php scripts codeigniter image upload

Comments

sakshi kalia says:

Nice tut.. Help me a lot….ThanQQQ!!!

Richa Agrawal says:

this tutorial make me out of the trouble.

Thanks…………..

Ashok says:

Very nice work… Explained in a simple and easy way… have to appreciate the hard work behind this… thanks a lot !

Zulkifli says:

thanks guys… this post solve my problem…

chandra says:

this post help me lot, thanks for uploading and Explained in a simple way.

ranggadablues says:

wow great tutorial..

but how to display all images from database

thank you

Callum Macrae says:

You'd need an extra page for that.

sandeep says:

i am getting error in view page <?php echo anchor('uploads/' . $uploaddata['filename'], 'Click here to view your upload') ?> undefined variable $uploaded_data

ByeWebster says:

Thanks This Tutorial Helpfull.. Uhmmmm how to rename filename image.. ^^

cripton says:

Nice tut :)

vijay kumar says:

hii this is working fine thanks

could u five me the link for captcha use in codeigniter,,

Bhuvan says:

tis is working.. thanks for the code.. keep it up.. its very much useful for begineers in codeigniter........ thanks again....

ananymous says:

sir, u didn't tell abt model.. how can i display images from database.. can u explain me as soon as possible

ananymous says:

sir, u didn't tell abt model.. how can i display images from database.. can u explain me as soon as possible

Joan says:

Hi, this doesn't work entirely seeing that you left out the model part..its incomplete..

ananymous says:

i too need to display images.. can u help me.. pls..

Yus Syeaful says:

Thank's for the tuts, i have fix all my bug for upload image and stored to database with user_id. thank's so much :)

Yus Syeaful says:

Thank's for the tuts, i have fix all my bug for upload image and stored to database with user_id. thank's so much :)

Yus Syeaful says:

Thank's for the tuts, i have fix all my bug for upload image and stored to database with user_id. thank's so much :)

Kieran Anderson says:

Codeigniter is an open source web application framework written in PHP.In Codeigniter image upload script is kindly work and I try it.

mayur says:

hi dear..... your idea is great for sratch level and so thnx.

mayur says:

how to delete image in root folder in codeingiter.

pls repl me.

pooja says:

Mayur You Try this

$this->load->helper("url"); deletefiles(baseurl("uploads/" . $file_name));

pawan says:

'title' => $uploaddata['clientname'], in controller. when i would change client_name display the undefined index. Please help me what does happen this.

says:

Add comment

 

You can use markdown in comments (press "m" for a cheatsheet).

Enable JavaScript to post a comment

Markdown Cheat Sheet

# This is an <h1> tag
## This an <h2> tag
###### This is an <h6> tag

Inline markup: _this text is italic_, **this is bold**, and `code()`.

[Link text](link URL "Optional title")
[Google](http://google.com/ "Google!")

![Alt text](image URL)

![This is a fish](images/fish.jpg)

1. Ordered list item 1
2. Ordered list item 2

* Unordered list item 1
* Unordered list item 2
* Item 2a
* Item 2b

And some code:

// Code is indented by one tab
echo 'Hello world!';

Horizontal rules are done using four or more hyphens:

----

> This is a blockquote

This is an <h1> tag

This an <h2> tag

This is an <h6> tag

Inline markup: this text is italic, this is bold, and code().

Link text Google

This is a fish

  1. Ordered list item 1
  2. Ordered list item 2
  • Unordered list item 1
  • Unordered list item 2
    • Item 2a
    • Item 2b

And some code:

// Code is indented by one tab
echo 'Hello world!';

Horizontal rules are done using four or more hyphens:


This is a blockquote

Toggle MarkDown / HTML (t), full reference or close this