In this PHP Codeigniter Tutorial, I am going to tell you how to upload image on the server and also you will know how to add validation rule to file upload in Codeigniter.
I need a multipart form to upload file and in Codeigniter, There is a helper method form_open_multipart
to open multipart form tag.
This is one of most common requirements for all the web application to have a file upload functionality.
For this example, I will have a simple HTML form with input field and a submit button as usually so that I can select the file and There are number of libraries with Codeigniter that reduce the development time and I am going to use upload
library to upload the files very easily on the server.
In this first step, I will add routes in our route file for uploading image.
application/config/routes.php<?php defined('BASEPATH') OR exit('No direct script access allowed'); $route['default_controller'] = 'welcome'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE; $route['upload-image'] = 'UploadImage'; $route['upload-image/post']['post'] = "UploadImage/uploadImage";
In this step, I will create a controller "UploadImage.php" and place the following code in it and save this file to application/controllers/
directory.
<?php class UploadImage extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('form', 'url')); } public function index() { $this->load->view('imageupload_view', array('error' => '' )); } /** * Method to upload image to the server * * @return Response */ public function uploadImage() { $config['upload_path'] = 'uploads/images/'; $config['allowed_types'] = 'gif|jpeg|jpg|png'; $config['max_size'] = 2048; $this->load->library('upload', $config); if ( ! $this->upload->do_upload('image')) { $error = array('error' => $this->upload->display_errors()); $this->load->view('imageupload_view', $error); }else { echo "Upload Successful"; exit; } } } ?>
In this step, I will create a view imageupload_view.php
file inside the application/views/ directory.
<!DOCTYPE html> <html> <head> <title>Image upload in Codeigniter with example</title> </head> <body> <?php echo $error;?> <?php echo form_open_multipart('upload-image/post');?> <input type="file" name="image" /> <input type="submit" name="submit" value="Upload" /> </form> </body> </html>
- Codeigniter - Upload image with preview using jQuery Ajax Form Plugin with example
- Ajax Image Upload using PHP and jQuery Example Without Page Refresh with Validation
- Laravel PHP : Upload image with validation using jquery ajax form plugin
- Upload Multiple Images With Image Preview Using jQuery,Ajax And PHP