CodeIgniter File Upload And Email Example

On September 18, 2010, in Articles, CodeIgniter, by Michael

One of the benefits of using CodeIgniter is how it allows you to simplify tasks that used to be fairly complicated to code on their own. Why reinvent the wheel when you don’t have to.

In this example, I’ll use the following CodeIgniter Libraries & Helpers to display a file upload form that sends the uploaded file to a user via email.

  • File Uploading Library
  • Email Library
  • Form Validation Library
  • Form Helper

Step 1: Load all the libraries & helpers in your controller.

// Load upload library & set config preferences
$config = array(
	'upload_path' 	=> '/tmp',
	'allowed_types' => 'gif|jpg|png'
);
$this->load->library('upload', $config);

// Load email library & set config preferences
$config = array(
	'protocol' => 'mail'
);
$this->load->library('email', $config);

// Load form validation library
$this->load->library('form_validation');

// Load form helper
$this->load->helper('form');

Step 2: Combine form validation, file uploading, & email libraries together seamlessly.

// Set form validation rules
$this->form_validation->set_rules('contact', 	'Contact', 	'trim|required|xss_clean');
$this->form_validation->set_rules('email', 		'Email', 	'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('userfile', 	'File', 	'trim');
$this->form_validation->set_error_delimiters('', '
');

// Run form validation
if ($this->form_validation->run() === FALSE) {		

// Form validation failed based on validation rules set above

// Show form
$this->_tpl('uploadexample');

} else {

// Form validation success

// Use PHP's internal $_FILES superglobal to test for valid
if ($_FILES["userfile"]["name"]) {

	// Do the file upload
	$this->upload->do_upload();

	// Get upload errors
	$errors = $this->upload->display_errors();

	// There was an error uploading the files. Since this is
	// just an example, die.
	if ($errors) {
		die($errors);
	}

	// Get upload data assuming no errors
	$upload_data = $this->upload->data();

}

// Set email data from the form submission
$email    = set_value('email');
$contact  = set_value('contact');

// Set the email subject
$subject  = 'Form Submission';

// Set the email message
$message  = "From: $contact <$email>\n";
$message .= "Datetime: ".date("Y/m/d h:m:s A")."\n\n";
$message .= "-------------------------------\n\n";
$message .= "contact : ".set_value('contact') ."\n";
$message .= "email : ".set_value('email') ."\n";
$message .= "-------------------------------\n\n";

// Add file data to the message if it is set
if ($upload_data) {
	$message .= "file name : ".$upload_data['file_name'] ."\n";
	$message .= "file type : ".$upload_data['file_type'] ."\n";
}

// Configure the email message
$to = ""; ## DEFINE ME
$cc = "";
$bcc = "";
$this->email->to($to);
$this->email->cc($cc);
$this->email->bcc($bcc);
$this->email->from($email);
$this->email->reply_to($email, $contact);
$this->email->subject($subject);
$this->email->message($message);

// Attach the uploaded file if it is set
if ($upload_data) {
	$this->email->attach($upload_data["full_path"]);
}

// Send the email
$this->email->send();		

// Show the internal email debugger if you experience errors.
echo $this->email->print_debugger();

// Redirect on success
//redirect('uploadexample/thankyou', 'location');

Step 3: Lastly, use the form helper in your template to easily render your file upload form.

< ?=form_open_multipart('uploadexample')?>

<table cellpadding="2">
<tr>
	<td>Contact Name:</td>
	<td>
		<?php
		$data = array
			(
				'name'        => 'contact',
				'id'          => 'contact',
				'value'       => (set_value('contact')) ? set_value('contact') : $contact,
				'maxlength'   => '255',
				'size'        => '25',
		    );				
		echo form_error('contact');
		echo form_input($data);	
		?>
	</td>
</tr>

<tr>
	<td>Email:</td>
	<td>
		<?php
		$data = array
			(
				'name'        => 'email',
				'id'          => 'email',
				'value'       => (set_value('email')) ? set_value('email') : $email,
				'maxlength'   => '255',
				'size'        => '50',
		    );				
		echo form_error('email');
		echo form_input($data);	
		?>
	</td>
</tr>

<tr>
	<td>Upload Image:</td>
	<td>
		<?php
		$data = array
			(
				'type'        => 'file',
				'name'        => 'userfile',
				'id'          => 'userfile',
				'value'       => (set_value('userfile')) ? set_value('userfile') : $userfile,
				'size'        => '50',
		    );				
		echo form_error('userfile');
		echo form_input($data);	
		?>
		<br />
		Supported files: .gif. jpg. png
	</td>
</tr>

<tr>
	<td colspan="2">< ?=form_submit('submit', 'Submit')?></td>
</tr>
</table>

< ?=form_close()?>

Download the files and test it out.

If you found this article useful, please share your comments below.

14 Responses to CodeIgniter File Upload And Email Example

  1. marcia says:

    I'm having an issue with this code. I have a form for the user to add info and upload a file. This information is sent to the client via email, with the file attached. When there is a file attached to the email, then nothing appears at all in the message area.

  2. marcia says:

    I downloaded the code. Where is the code on this webpage in the folder?

  3. marcia says:

    I get the error "Message: Undefined variable: contact" and "Message: Undefined variable: userfile" when I submit the form. Where are the variables $contact and $userfile defined?

  4. marcia says:

    I decided to put all the code on the same page (not separated in "view" and "controller"). Now I get this message"Message: Undefined property: CI_Loader::$form_validation". I checked in the system/libraries/ and Form_validation.php is there. Any suggestions?

  5. marcia says:

    Michael,
    After days of working with it, I finally got it to work. I'm new to php, so I'm not sure what the problem way. If you would like to see it, the link is http://www.test.mwilkinsondesign.com/index.php/qu…. I'm still working on the site.
    Thank you for your code. It's what I was looking for.

  6. marcia says:

    There is just one issue I still have to resolve. If I choose a file to upload and submit the form, but the form doesn't pass validation and it returns to the form view, all the fields are reloaded, except the upload field. It is empty. I have the code just as you have it. Any ideas about that?
    Thanks again.

  7. [...] If you found this article useful, please share your comments below. Related posts:CodeIgniter File Upload And Email Example [...]

  8. [...] If you found this article useful, please share your comments below. Related posts:CodeIgniter File Upload And Email Example [...]

  9. [...] If you found this article useful, please share your comments below. Related posts:CodeIgniter File Upload And Email Example [...]

  10. Guest says:

    // There was an error uploading the files. Since this is just an example, die.This worries me… not good practice, especially on a tutorial post.

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...