Codeigniter File Upload to Folder at Root Tutorial

 Codeigniter file upload example

Codeigniter is a light weight MVC based PHP framework. It is very popular in web development community. Codeigniter is widely used to perform different types of tasks. File upload in codeigniter is very easy and in this commodity we will run into codeigniter file upload instance.

codeigniter file upload example

Codeigniter tin can be downloaded from https://www.codeigniter.com/download.  Afterward downloading unzip the codeigniter folder, it volition be unzipped inside folder name like CodeIgniter-3.x.x. Rename it to a project name you want to utilize. We will rename this to uploadexample. copy this folder and paste information technology in to root folder ofXAMPP , WAMP or MAMP or what e'er software your are using. In XAMPP root binder is htdocs. Nosotros are going to see codeigniter file upload example.

Codeigniter folder structure

codeigniter folder structure

Every bit you can see the CI chief folder structure. In that location aresystem, awarding anduser_guide folders and index.php file. Arrangement folder contains the core CI files whileapplication folder contains the code for application.

Important folders in awarding directory

CI is based on Model-View-Controller or MVC design pattern. Every bit you tin can see in the pic below that inside application folder nosotros accept many folders farther but most of import ones areconfig, controller, model, views.

codeigniter application directory

Config has essential configuration for awarding like basic configurations,  database credentials, important libraries and helpers to load etc. Controller Contains application logic, receives user requests, sends to model and and then receives the consequence from model and sends back to user.Model contains the application logic and business organisation rules for application. Views contains the presentation or forepart end of awarding that is displayed to user.

1. Create a upload.php file inside Views folder

2. Create success.php file inside Views.

3. CreateUpload.php inside Controller folder.

4. Create a binder Uploads in project folder.

4. Upload an epitome file, validate it and salve it to a directory on server.

Create uploads directory

First become to projection folder  (Example: uploadexample ) and create a folder named Uploads, in this folder, files or images are going to be uploaded.

Create a form to upload file.

Open up Views binder then create a file namedupload.php and add together post-obit code.

<!DOCTYPE html>  <html>  <head>  <title>Codeigniter Upload Example</title>  </head>  <body>  <?php echo $error; ?>  <h3>Upload Case</h3>  <?php repeat form_open_multipart('upload/upload_file'); ?>  <input type="file" name="userfile" size="20" />  <br /><br />  <input type="submit" value="upload" />  </form>  </body>  </html>        

The above code create a minor form with Upload file input and an upload button. After <trunk> tag errors are displayed. Then we use the line beneath to create a form in codeigniter.

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

form_open_multipart('upload/upload_file') is codeigniter part, it is same is form_open.form_open_multipart add an extra attributeenctype="multipart/form-information". This attribute is required when you need to upload a file or image.  The above code  generates HTML like:

<grade action="http://localhost/uploadexample/alphabetize.php/upload/upload_file"         enctype="multipart/course-data" method="mail service" accept-charset="utf-8">        

After opening the form nosotros create a file input field, so a submit button and close the course tag.  The lawmaking higher up creates a form as shown below in the epitome.

Codeigniter file upload form

Add success file code

We will display bulletin after file is uploaded successfully. So add a file named success.php in Views directory and add following code.

<html>  <head>  <championship>Codeigniter File Upload Success</title>  </head>  <body>  <h3>File has been uploaded.</h3>  <ul>  <?php foreach ($upload_data every bit $item => $value): ?>  <li><?php echo $item;?>: <?php echo $value;?></li>  <?php endforeach; ?>  <li><?php repeat "<h3>Uploaded file:</h3>"; ?></li> <li>   <img src="<?php repeat base_url().'/uploads/'.$upload_data['file_name']; ?>" /></li>  </ul>  <p><?php repeat anchor('upload', 'Upload Another File!'); ?></p>  </trunk>  </html>

In the code above all the data of uploaded file is within $upload_data  variable.  nosotros run loop foreach ($upload_data as $detail=>$value) and $detail displays file data like File proper noun,  File type, File path, Size and Extension etc. While $value displays values of the parameters to a higher place. Afterwards end of loop uploaded image is displayed in img tag.

Changing default route in routes.php

In Applications binder, open routes.php in config folder and change

$route['default_controller']

to

$route['default_controller']  = 'upload';

Then this will change default controller to upload and http://localhost/uplaodexample/ URL volition display upload form.

Codeigniter Controller lawmaking to upload file to server.

At present let add together controller form. In Controller directory add Upload.php file and add together following code.

<?php   defined('BASEPATH') OR exit('No direct script access allowed');    class Upload extends CI_Controller {          public role __construct()         {             parent::__construct();             $this->load->helper(array('form', 'url'));             $this->load->library('form_validation');         }          public part index()         {         	$this->load->view('upload', array('mistake' => ' ' ));         }          public office upload_file()         {                 $config['upload_path']          = './uploads/';                 $config['allowed_types']        = 'gif|jpg|png|pdf|md';                 $config['max_size']             = 100;                 $config['max_width']            = 1024;                 $config['max_height']           = 768;                  $this->load->library('upload', $config);                  if ( ! $this->upload->do_upload('userfile'))                 {                                              $this->form_validation->set_error_delimiters('<p course="mistake">', '</p>');                      $error = array('error' => $this->upload->display_errors());                      $this->load->view('upload', $error);                 }                 else                 {                     $data = array('upload_data' => $this->upload->data());                      $this->load->view('success', $information);                 }         } }

 Controller explanation

Every bit y'all can see we added a class named Upload and this form  is a kid of CI_Controller.  And then Inside class we declared constructor __construct  and call parent class constructor.  And and then nosotros load codeigniter helpers form and url . Form helper contains functions that help in working with forms and URL helper contains functions that help in working with URLs.

Index Action explanation.

Next we are going to ascertain Index Action that displays Upload.php in Views folder.

upload_file Action explanation

The upload_file action volition upload file to server.

          $config['upload_path']          = './uploads/';                 $config['allowed_types']        = 'gif|jpg|png';                 $config['max_size']             = 100;                 $config['max_width']            = 1024;                 $config['max_height']           = 768;                  $this->load->library('upload', $config);

In the code snippet above basic configuration for upload is ready e.chiliad upload_path, allowed_types, max size, max width and max height. Then we load Codeigniter's Upload Library and pass the config parameter array to it. This library contains all the function that are used to validate and upload a file to server.

          if ( ! $this->upload->do_upload('userfile'))                 {                                               $error = assortment('error' => $this->upload->display_errors());                      $this->load->view('upload', $error);                 }                 else                 {                     $data = array('upload_data' => $this->upload->data());                      $this->load->view('success', $data);                 }

In lawmaking to a higher place the field userfile contains the uploaded file. In if status we cheque that if file is not uploaded and so $error contains whatsoever errors occurred. $this->upload->do_upload('userfile') part uploads file to server. We load theUpload view over again and assign$errorto it. In view nosotros display errors to user. In case of success nosotros save uploaded file to the destination binder.

$this->upload->data()

Above function will save uploaded file information to upload_data assortment element from upload->data array. and finally success view is loaded showing success bulletin and uploaded file information.

Codeigniter file upload

In conclusion, we have CodeIgniter file upload instance. Y'all can  clone or download source code of this tutorial  from GitHub repository.

souece code codeigniter file upload example on GitHub

Please leave your comment feedback below. Stay tuned for upcoming articles

Related Articles:

  • How to Zip, Salvage and Download a file in CodeIgniter

  • How to watermark images using CodeIgniter

  • Create Restful web services in CodeIgniter

  • Soap web services in php

  • PHP Mongodb tutorial

Next: How to Zero, Save, and Download a file in CodeIgniter

Previous:  Parse XML Using PHP

bradfordatmach.blogspot.com

Source: https://programmerblog.net/codeigniter-file-upload-example/

0 Response to "Codeigniter File Upload to Folder at Root Tutorial"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel