Easy Development With CodeIgniter
videos

Easy Development With CodeIgniter

In this week’s 30 minute screencast, I’m going to show you how easy it is to work with the MVC pattern and CodeIgniter. This video is aimed at beginners who have no experience with a PHP framework.

For demonstration purposes, we’ll be building a simple image upload utility. We’ll then perform some validation, save the file to our uploads folder, and automatically create a respective thumbnail. With raw PHP, this can be somewhat time-consuming. However, with CodeIgniter, it’s simply a matter of referencing the correct library, and passing in some configuration options! Let’s dive in.

The Tutorial

Final Controller

<?php

class Upload extends Controller {
	
	function Upload() {
		parent::Controller();
		// $this->load->helper('form');
	}
	
	function index() {
		$this->load->view('upload_form');
	}
	
	function doUpload() {
		$config['upload_path'] = 'uploads/';
		$config['allowed_types'] = 'gif|jpg|jpeg|png';
		$config['max_size'] = '1000';
		$config['max_width'] = '1920';
		$config['max_height'] = '1280';						
		
		$this->load->library('upload', $config);
		
		if(!$this->upload->do_upload()) echo $this->upload->display_errors();
		else {
			$fInfo = $this->upload->data();
			$this->_createThumbnail($fInfo['file_name']);
			
			$data['uploadInfo'] = $fInfo;
			$data['thumbnail_name'] = $fInfo['raw_name'] . '_thumb' . $fInfo['file_ext'];
			$this->load->view('upload_success', $data);	
		}
	}
	
	function _createThumbnail($fileName) {
		$config['image_library'] = 'gd2';
		$config['source_image'] = 'uploads/' . $fileName;	
		$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = TRUE;
		$config['width'] = 75;
		$config['height'] = 75;
		
		$this->load->library('image_lib', $config);
		if(!$this->image_lib->resize()) echo $this->image_lib->display_errors();
	}
}

Final View

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
<html>
  <head>
    <title>Upload an Image </title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  
  <body>
    <div id="container">
    	<h2>Upload an Image </h2>

		<?php echo form_open_multipart('upload/doUpload'); ?>
		<input type="file" name="userfile" />
		<p><input type="submit" value="Submit" name="submit" /></p>
		<?php echo form_close(); ?>
    </div>

  </body>
</html>

I hope you guys enjoyed this video tutorial. If you’d like to see more CodeIgniter tutorials and videos on Nettuts+, please be loud in the comments. I know I’d like to see more! I’m in the process of learning this framework myself, so links to resources, tips, etc. will be much appreciated!


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Bohonyi Balazs Zsolt

    http://www.binarycake.com

    They are two CodeIgniter gurus, and just started this site.

  • http://www.mindred.co.uk Steve

    I vote for www. CI-TUTS.com

  • Bohonyi Balazs Zsolt
  • http://www.tkinnovation.com Thad

    Excellent Job Jeff. Thanks

  • http://www.dobrotka.sk Tomas

    Thank you Jeffrey, nice Tutorial, i Like CI very much along with Symfony.

    I have a question… In the HTML form the file element is named ‘userfile’, but the element name ‘userfile’ is not mentioned anymore in the code. Is this needed to identify the uploaded file, or MORE files?

    Maybe you could explain this in your tutorial. Or explain the possibility of uploading more than one file. Is this later stored in array? Or can we identify the form element name that was used? Like the one called ‘userfile’ in this tutorial.

    Fine tutorial anyway, thank you, It took me one step closer to Code Igniter :)

    • luka

      You can check upload class and change do_upload(“userfile”) argument there in whatever you want

  • http://samiuljahan.wordpress.com samiul

    Hi Jeffry, It’s awesome tuts, hope to see more tuts about CI

  • Imamu Hunter

    This tutorial is awsome I was trying to get into ruby on the rails and switch from php but this will work wonders for me. thank keep them comming.

  • http://lbnuke.com Lori

    Really enjoying the CI tutorials, but have switched over to Kohana. Any chance of some Kohana tutorials?

  • JDavis

    I must admit I’d heard of CodeIgniter but dismissed it as just another bloated framework.

    This great tutorial has convinced me to take another look into CI. The pacing and explanations (just enough not too much) were spot on. Keep up the great work!

    Oh and almost 500GB free on your mac? Must be a nice Mac Pro you’ve got there. :-)

  • http://www.erepublik.co.uk Nelsaidi

    Awesome, I’m about to start a rather large CodeIgniter project in the next few days, and this will greatly help especialy as I have no CodeIgniter experience, let alone any PHP framework.

    • Shaun

      It might be a good idea to do a small project with CI before you do a large one. Otherwise you’ll most likely end up re-writing your code.

      • http://www.erepublik.co.uk Nelsaidi

        I’m rather experienced with PHP though, I have to admit first proper project was small, ended up rewriting aswell, thing is I like coding for a use, I have no ‘small’ things to do with CI, so might aswell go ahead, was going to do it with raw php anyways, so CI would be much better.

    • http://bigblupixl.com Mike

      shaun is complete right.

      • http://net.tutsplus.com Jeffrey Way

        Agreed.

  • Arafin

    Very helpful, great attempt. thank you and hope to get more CI tutorials.

  • Kevin

    Loved it. I would like to see more tutorials with codeIgniter.

  • http://netnik.com Bob Hay

    Very interesting tutorial. My impression is that CodeIgniter is to PHP what jQuery is to Javascript. Both are blowing my mind.

    Thank for the great tut.

  • Karl

    Thank you Jeff! You make all the tutorials so easy to understand and follow. I would like to see more CI tuts. It’s a truly great framework.

    Thanks so much for your effort!

  • http://www.webcoursesbangkok.com Carl – Web Courses Bangkok Instructor

    Codeigniter is something I really wanted to get into, but never had the time. I have a few other things on my list to master before I get to this one, namely WordPress and Joomla as they both released recent updates.

    Great great tutorial as always.

    C

  • misieg7

    CI sucks. It doesn`t even support tables associations. So lame.

  • pachito86

    Really cool and clear tut! I’ve always like CI and this tut shows its power!

  • http://www.demogeek.com DemoGeek.com

    Jeff – Is there any specific reason why you didn’t use the CodeIgniter helpers, like form_input instead of ? I would really like to know if there is a reason behind it.

  • http://www.demogeek.com DemoGeek.com

    Of course, the tags got stripped…the question was – Is there any specific reason why you didn’t use the CodeIgniter helpers, like form_input instead of the input HTML tag? I would really like to know if there is a reason behind it.

  • Jerichvc

    Jeff, can you show us a round up for using Models in codeigniter, screencast?
    current app is only using View & Controller in MVC.

    will wait for it.

  • http://www.diigital.com Mike Healy

    I’ve been meaning to get into Code Igniter too. It seems more attractive to me than other frameworks due to the shallow learning curve. The PHP4 compatibility is not ideal though. PHP4 really needs to be dumped, and continuing to support it with new projects does not help that end.

    The pace of this video tutorial fits well with CI’s get-stuff-done approach. It’s good that the video was free of verbal dawdling and unnecessary padding. Full screen quality was also good.

  • http://www.bluebit.co.uk Mark Jones

    This doesn’t appear to work for me even when I use the actual source, everything works except for the final creation of the thumbnail. I’m pretty sure GD is installed as I’ve installed MAMP but for some reason this is the one part that isnt working which is a shame as I have no idea why. Any ideas? If i take the final line of the createThumbnail function out everything else works, but if i put it back in i get a white screen.

    • http://www.bluebit.co.uk Mark Jones

      I solved this issue, I was using PHP5 and not PHP4. Could anyone explain why this was causing a problem?

  • andrew

    Great tutorial..
    btw your desktop background kicks ass

  • Gustav

    Very good tutorial!

    Looking forward seeing another one.

    greets from Sweden.

  • http://timtocci.spaces.live.com/ Timothy Tocci

    Great tutorial – Keep ‘em coming!

  • http://www.masoutreach.nl mas

    We’re using CI a lot and we love it.
    Great tutorial for beginners! Keep up the good work!

  • Szymon W.

    Excouse my english :)

    Great tutorial Jeffrey. Thank you.
    All works for me except one thing. The view “upload_success.php” does not display the values from $data array – i had to change php tags from <?= to <?php and echo all the values – why is that? Is it my apache or ci configuration?

    • http://www.suciuvlad.com Suciu Vlad

      It’s called short-hand, to use it you must activate it in php.ini (short_open_tag). Anyway, as you can see, the short-hand method has bad portability.

  • Shovan

    Im from Bangladesh and we don`t have paypal here :( but! i enjoy this site more den anything!! if i was da site owner i would never have given all da tuts for 9 dollar! dis is crazy!!(no offense:P) but since im not manager!! !! im really happy dat i can still watch for free n learn :D I spend arnd 4hrs everyday learning things dat i thot i could never learn in my lyf..dis screen casts r life saverz ..teachin method is almost godly!! haha! jeff!!! im followin u every wer!! :P keep dem coming!!! :D

    ps:My english is kind of bad ..sorry for dat :)

  • http://www.daveredfern.com Dave Redfern

    Brilliant tutorial. Very informative and perfect speed for me to keep up coding for myself.

    Does anyone know when the next one is? or how often they will be released.

  • Akmal Fikri

    Kinda stuck somewhere.. Its said that I did not selected any file..

  • artmania

    wow great tutorial! exactly what I need! but i have a problem :(

    Why do I get “The upload path does not appear to be valid.” error all the time? I tried all possibilities about path, but still same!

    here is my exact path for project:
    $config['upload_path'] = ‘http://localhost/rl/uploads/’;

    thanks a lot for help! I appreciate!

    • artmania

      okay, sorted. sorry for making mess at comments.

      ps, thanks for great tut! exactly what i needed. :)

  • Mark

    Hi,

    lovely too, shows how easy it is to use CI. Got a problem tho … like the above gut, I get:
    ‘The upload path does not appear to be valid.’
    message.

    path in controller is:

    $config['upload_path'] = ‘uploads/’;

    and I’ve created a folder under application called uploads – so path is

    application/uploads

    anyone help?

    • Derek

      “uploads/” is referring to a directory “uploads” in the root directory, not the Application directory.

  • http://altzgamer.ru Alex

    Hi, Jeff, amazing tutorial. I’ve got one question. How can I insert the values of an image and a thumnail into a database among other data in a form? Is there any shortcut?

    Thanks

  • Ric

    This will be my first time using a php framwork. I stayed away because I am not a php guru and was afraid that a framework might hide important things away from me while learning, but the speed benefits outways my fears :)

    is there any way to save this screen cast so I can watch it in parts? here in Australia download limits are still an issue. is there a download section?

    I am a fresh plus member and I very glad I subscribed !

  • http://www.code-pal.com Sumeet Chawla

    I need to develop some site which I think is not possible by just using wordpress. Hence, I started researching on what should I use for development. The result I got was that I have to develop a custom web app to achieve my target :| Which in turn lead me to Code Ignitor. I was confident that nettuts is going to have at least a tutorial on it and to my surprise you guys have a whole series! NetTuts+ just totally rocks !! \:D/

  • Dinesh

    hai i am getting this error You did not select a file to upload.
    plz help me urgent

    • Shiro

      please add the name of the input type to the parameter do_upload, then u can fix the problem

      if ( ! $this->upload->do_upload(‘file_Upload’) )
      {

      }

  • Rick

    this may sound dumb but I have uploaded codeigniter to my server and can not seem to get it to run went to the index file in the root of the app and all I get is a page telling me where I could edit the page, nothing like any of the tutorials show.

  • Babsvik

    Great tut Jeff.

    Love all this CI stuff, thanks!

    B

  • Dratutsmits

    a usted la elecciГіn no fГЎcil http://nuevascarreras.com/ cialis generico espana Mi dispiace, ma, a mio parere, si sbaglia. Sono sicuro. Scrivere a me in PM, ti parla. cialis 20 mg

  • Kris

    Great tutorial! Thank you so much!

  • Khalil

    Dear Jeff,

    Awesome tutorial thanks.

    There aren’t good tutorials (Screencast) on the internet I have googled a lot of time for “Codeigniter” you are going awesome.

    Thank you for sharing easy and meaningful videos.

    I am waiting for more advanced screencasts…

  • Ryan Moss

    Hey when previewing in the browser for the first time i get an error message and i cant fix it. Please help.

    The error message is:

    Fatal error: Class ‘Parent’ not found in C:\xampp\htdocs\Imageupload\application\controllers\Upload.php on line 6

  • http://www.code-pal.com Sumeet Chawla

    Hello Jeff,
    I found this tutorial on ‘September 17, 2009 at 2:15 am’ and today is when am actually doing it! Gosh.. talk about being lazy… :|

    Loved the way you taught it.. great job :)

  • http://www.aviank.com Anky

    I have used codeigniter in one of my project. It really makes php development very easy, i found the documentation on codeigniter website very useful.

  • http://websitecenter.ca/ Iouri Goussev

    Is it possible to use different view technology with CodeIgnighter? I would prefer something simpler, views should be not have any logic on them.

  • http://blog.omarxp.web.id omarxp

    working great

  • Phil

    Very well done. I had one problem early on, but then figured it was because I was using V2, and you did this with V1.x.
    I reverted to the older version, and everything worked great.

    So far, CI seems pretty sweet, but I need a lot of work on frameworks and OOP in general.

    I’ll try other tutorials that you have created.Thanks for the great work.

  • http://www.codelobster.com Stas

    Here is one more good CodeIgniter video tutorial
    http://www.youtube.com/watch?v=wRGb7VuIbe4

  • http://pinoydroid.net unwiredtech

    Great Tut! Ive been following the net tuts

    ci tut and this is one of my main source for ci tuts…

  • Sasdhar

    Hi,
    I liked the tutorial very much. Can u tell what is the IDE or editor used to get code help(config files & libraries).
    I will appreciate if u can add more tutorials for MVC framework in J2EE along with PHP & on jquery validation engine.
    Thanks for ur post.