1. Code
  2. PHP
  3. CodeIgniter

How to Upload Files With CodeIgniter and AJAX

Scroll to top

Uploading files asynchronously can be a pain at the best of times, but when coupled with CodeIgniter, it can be a particularly frustrating experience. I finally found a way that not only works consistently, but keeps to the MVC pattern. Read on to find out how!

By the way, you can find some useful CodeIgniter plugins and code scripts on Envato Market, so have a browse to see what you can find for your next project.


Preface

In this tutorial, we'll be using the PHP framework CodeIgniter, the JavaScript framework jQuery, and the script AjaxFileUpload.

It's assumed you have a working knowledge of CodeIgniter and jQuery, but no prior knowledge of AjaxFileUpload is necessary. It is also assumed that you already have an install of CodeIgniter already set up.

For the sake of brevity, the loading in of certain libraries/models/helpers has been omitted. These can be found in the source code supplied, and is pretty standard stuff.

You'll also need a database, and a table, called files. The SQL to create said table is:

1
CREATE TABLE `files` (
2
  `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
3
  `filename` varchar(255) NOT NULL,
4
  `title` varchar(100) NOT NULL
5
);

By the end of the tutorial, your file structure should look similar to this (omitting unchaged folders/files):

public_html/
-- application/
---- controllers/
------ upload.php
---- models/
------ files_model.php
---- views/
------ upload.php
------ files.php
-- css/
---- style.css
-- files/
-- js/
---- AjaxFileUpload.js
---- site.js


Step 1 - Creating the Form

Set up the Controller

First, we need to create our upload form. Create a new Controller, called upload, and in the index method, render the view upload.

Your controller should look like this:

1
class Upload extends CI_Controller 
2
{
3
	public function __construct()
4
	{
5
		parent::__construct();
6
		$this->load->model('files_model');
7
		$this->load->database();
8
		$this->load->helper('url');
9
	}
10
11
	public function index()
12
	{
13
		$this->load->view('upload');
14
	}
15
}

We are also loading in the files model, so we can use it in our methods. A better alternative may be to autoload it in your actual project.

Create the Form

Create your view, upload.php. This view will contain our upload form.

1
<!doctype html>
2
<html>
3
<head>
4
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
5
	<script src="<?php echo base_url()?>js/site.js"></script>
6
	<script src="<?php echo base_url()?>js/ajaxfileupload.js"></script>
7
	<link href="<?php echo base_url()?>css/style.css" rel="stylesheet" />
8
</head>
9
<body>
10
	<h1>Upload File</h1>
11
	<form method="post" action="" id="upload_file">
12
		<label for="title">Title</label>
13
		<input type="text" name="title" id="title" value="" />
14
15
		<label for="userfile">File</label>
16
		<input type="file" name="userfile" id="userfile" size="20" />
17
18
		<input type="submit" name="submit" id="submit" />
19
	</form>
20
	<h2>Files</h2>
21
	<div id="files"></div>
22
</body>
23
</html>

Don't forget to place ajaxfileupload.js in js/.

As you can see, we are loading in our scripts at the top; jQuery, AjaxFileUpload, and our own js file. This will house our custom JavaScript.

Then, we are simply creating a standard HTML form. The empty #files div is where our list of uploaded files will be.

Some Simple CSS

Just so it doesn't look quite so bad, lets add some basic CSS to our file style.css in css/.

1
h1, h2 { font-family: Arial, sans-serif; font-size: 25px; }
2
h2 { font-size: 20px; }
3
4
label { font-family: Verdana, sans-serif; font-size: 12px; display: block; }
5
input { padding: 3px 5px; width: 250px; margin: 0 0 10px; }
6
input[type="file"] { padding-left: 0; }
7
input[type="submit"] { width: auto; }
8
9
#files { font-family: Verdana, sans-serif; font-size: 11px; }
10
#files strong { font-size: 13px; }
11
#files a { float: right; margin: 0 0 5px 10px; }
12
#files ul {	list-style: none; padding-left: 0; }
13
#files li { width: 280px; font-size: 12px; padding: 5px 0; border-bottom: 1px solid #CCC; }

Step 2 - The Javascript

Create and open site.js in js/. Place the following code:

1
$(function() {
2
	$('#upload_file').submit(function(e) {
3
		e.preventDefault();
4
		$.ajaxFileUpload({
5
			url 			:'./upload/upload_file/', 
6
			secureuri		:false,
7
			fileElementId	:'userfile',
8
			dataType		: 'json',
9
			data			: {
10
				'title'				: $('#title').val()
11
			},
12
			success	: function (data, status)
13
			{
14
				if(data.status != 'error')
15
				{
16
					$('#files').html('<p>Reloading files...</p>');
17
					refresh_files();
18
					$('#title').val('');
19
				}
20
				alert(data.msg);
21
			}
22
		});
23
		return false;
24
	});
25
});

The JavaScript hijacks the form submit and AjaxFileUpload takes over. In the background, it creates an iframe and submits the data via that.

We're passing across the title value in the data parameter of the AJAX call. If you had any more fields in the form, you'd pass them here.

We then check our return (which will be in JSON). If no error occured, we refresh the file list (see below), clear the title field. Regardless, we alert the response message.


Step 3 - Uploading the File

The Controller

Now on to uploading the file. The URL we are uploading to is /upload/upload_file/, so create a new method in the upload controller, and place the following code in it.

1
public function upload_file()
2
{
3
	$status = "";
4
	$msg = "";
5
	$file_element_name = 'userfile';
6
	
7
	if (empty($_POST['title']))
8
	{
9
		$status = "error";
10
		$msg = "Please enter a title";
11
	}
12
	
13
	if ($status != "error")
14
	{
15
		$config['upload_path'] = './files/';
16
		$config['allowed_types'] = 'gif|jpg|png|doc|txt';
17
		$config['max_size']	= 1024 * 8;
18
		$config['encrypt_name'] = TRUE;
19
20
		$this->load->library('upload', $config);
21
22
		if (!$this->upload->do_upload($file_element_name))
23
		{
24
			$status = 'error';
25
			$msg = $this->upload->display_errors('', '');
26
		}
27
		else
28
		{
29
			$data = $this->upload->data();
30
			$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
31
			if($file_id)
32
			{
33
				$status = "success";
34
				$msg = "File successfully uploaded";
35
			}
36
			else
37
			{
38
				unlink($data['full_path']);
39
				$status = "error";
40
				$msg = "Something went wrong when saving the file, please try again.";
41
			}
42
		}
43
		@unlink($_FILES[$file_element_name]);
44
	}
45
	echo json_encode(array('status' => $status, 'msg' => $msg));
46
}

This code loads in the CodeIgniter upload library with a custom config. For a full reference of it, check out the CodeIgniter docs.

We do a simple check to determine if the title is empty or not. If it isn't, we load in the CodeIgniter upload library. This library handles a lot of our file validation for us.

Next, we attempt to upload the file. if successful, we save the title and the filename (passed in via the returned data array).

Remember to delete the temp file off the server, and echo out the JSON so we know what happened.

The Model

In keeping with the MVC pattern, our DB interaction will be handled by a model.

Create files_model.php, and add the following code:

1
class Files_Model extends CI_Model {
2
3
	public function insert_file($filename, $title)
4
	{
5
		$data = array(
6
			'filename'		=> $filename,
7
			'title'			=> $title
8
		);
9
		$this->db->insert('files', $data);
10
		return $this->db->insert_id();
11
	}
12
13
}

Files Folder

We should also create the folder our files will be uploaded to. Create new file in your web root called files, making sure it is writable by the server.


Step 4 - The File List

Upon a successful upload, we need to refresh the files list to display the change.

The JavaScript

Open site.js and add the following code to the bottom of the file, below everything else.

1
function refresh_files()
2
{
3
	$.get('./upload/files/')
4
	.success(function (data){
5
		$('#files').html(data);
6
	});
7
}

This simply calls a url and inserts the returned data into a div with an id of files.

We need to call this function on the page load to initially show the file list. Add this in the document ready function at the top of the file:

1
refresh_files();

The Controller

The URL we are calling to get the file list is /upload/files/, so create a new method called files, and place in the following code:

1
public function files()
2
{
3
	$files = $this->files_model->get_files();
4
	$this->load->view('files', array('files' => $files));
5
}

Quite a small method, we use our model to load in the currently saved files and pass it off to a view.

The Model

Our model handles the retrieval of the file list. Open up files_model.php, and add in the get_files() function.

1
public function get_files()
2
{
3
	return $this->db->select()
4
			->from('files')
5
			->get()
6
			->result();
7
}

Quite simple really: select all the files stored in the database.

The View

We need to create a view to display the list of files. Create a new file, called files.php, and paste in the following code:

1
<?php

2
if (isset($files) && count($files))

3
{

4
	?>
5
		<ul>
6
			<?php

7
			foreach ($files as $file)

8
			{

9
				?>
10
				<li class="image_wrap">
11
					<a href="#" class="delete_file_link" data-file_id="<?php echo $file->id?>">Delete</a>
12
					<strong><?php echo $file->title?></strong>
13
					<br />
14
					<?php echo $file->filename?>
15
				</li>
16
				<?php

17
			}

18
			?>
19
		</ul>
20
	</form>
21
	<?php

22
}

23
else

24
{

25
	?>
26
	<p>No Files Uploaded</p>
27
	<?php

28
}

29
?>

This loops through the files and displays the title and filename of each. We also display a delete link, which include a data attribute of the file ID.


Deleting the File

To round off the tutorial, we'll add in the functionality to delete the file, also using AJAX.

The JavaScript

Add the following in the document ready function:

1
$('.delete_file_link').live('click', function(e) {
2
	e.preventDefault();
3
	if (confirm('Are you sure you want to delete this file?'))
4
	{
5
		var link = $(this);
6
		$.ajax({
7
			url			: './upload/delete_file/' + link.data('file_id'),
8
			dataType	: 'json',
9
			success		: function (data)
10
			{
11
				files = $(#files);
12
				if (data.status === "success")
13
				{
14
					link.parents('li').fadeOut('fast', function() {
15
						$(this).remove();
16
						if (files.find('li').length == 0)
17
						{
18
							files.html('<p>No Files Uploaded</p>');
19
						}
20
					});
21
				}
22
				else
23
				{
24
					alert(data.msg);
25
				}
26
			}
27
		});
28
	}
29
});

It's always a good idea to get a user confirmation when deleting information.

When a delete link is clicked, we display a confirm box asking if the user is sure. If they are, we make a call to /upload/delete_file, and if successful, we fade it from the list.

The Controller

Like above, the url we are calling is /upload/delete_file/, so create the method delete_file, and add the following code:

1
public function delete_file($file_id)
2
{
3
	if ($this->files_model->delete_file($file_id))
4
	{
5
		$status = 'success';
6
		$msg = 'File successfully deleted';
7
	}
8
	else
9
	{
10
		$status = 'error';
11
		$msg = 'Something went wrong when deleteing the file, please try again';
12
	}
13
	echo json_encode(array('status' => $status, 'msg' => $msg));
14
}

Again, we let the model do the heavy lifting, echoing out the output.

The Model

We're now at the final piece of the puzzle: our last two methods.

1
public function delete_file($file_id)
2
{
3
	$file = $this->get_file($file_id);
4
	if (!$this->db->where('id', $file_id)->delete('files'))
5
	{
6
		return FALSE;
7
	}
8
	unlink('./files/' . $file->filename);	
9
	return TRUE;
10
}
11
12
public function get_file($file_id)
13
{
14
	return $this->db->select()
15
			->from('files')
16
			->where('id', $file_id)
17
			->get()
18
			->row();
19
}

Because we only pass the ID, we need to get the filename, so we create a new method to load the file. Once loaded, we delete the record and remove the file from the server.

That's it, tutorial complete! If you run it, you should be able to upload a file, see it appear, and then delete it; all without leaving the page.


Final Thoughts

Obviously, the views can do with some prettying up, but this tutorial should have given you enough to be able to integrate this into your site.

There are a few shortcomings to this method, however:

  • You can only upload one file at a time, but this can rectified easily by using a service like Uploadify.
  • There is no progress bar built into the script.
  • We could reduce the SQL calls by updating the files div upon file upload, instead of fully replacing them.

Thanks for reading!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.