Code example for codeigniter file upload in PHP

Source: Internet
Author: User
Tags codeigniter

Codeigniter file upload code example

File Upload class

CodeIgniter's file upload class allows files to be uploaded. You can specify the file type to be uploaded and the file size to be specified.

Handling process

The general process of uploading files:

A form used to upload a file. You can select a file and upload it.

When this form is submitted, the file is uploaded to the specified directory.

At the same time, the file will be verified to meet your set requirements.

Once the file is uploaded successfully, a confirmation window is returned.

Here is a short tutorial to show this process. Then you will find the relevant reference information.

Create upload form

Use the text editor to create a file named upload_form.php, copy the following code and save it in the applications/views/directory:

You will see that a form auxiliary function is used to create the form's start tag, and a multipart form is required for file upload, because this form auxiliary function creates an appropriate statement for you. You will also see that we use a $ error variable. When the user submits this form, an error message is displayed.

Successfully uploaded page

Use the text editor to create a file named upload_success.php. Copy the following code and save it to the applications/views/directory:

Your file was successfully uploaded!

$ Value):?>



Use the text editor to create a controller named upload. php. Copy the following code and save it to the applications/controllers/directory:

Load-> helper (array ('form', 'url');} function index () {$ this-> load-> view ('upload _ Form ', array ('error' => '');} function do_upload () {$ config ['upload _ path'] = '. /uploads/'; $ config ['allowed _ types'] = 'gif | jpg | png '; $ config ['max _ size'] = '123 '; $ config ['max _ width'] = '000000'; $ config ['max _ height'] = '20140901 '; $ this-> load-> library ('upload', $ config); if (! $ This-> upload-> do_upload () {$ error = array ('error' => $ this-> upload-> display_errors ()); $ this-> load-> view ('upload _ Form', $ error );} else {$ data = array ('upload _ data' => $ this-> upload-> data ()); $ this-> load-> view ('upload _ success ', $ data) ;}}}?>

Upload File directory

You also need a destination folder to store uploaded images. Create a file named uploads in the root directory and set the file attribute to 777. (Read and write)

Submit Form

To submit your form, enter a URL similar to the following:

You will see an upload form, select one (jpg, gif, or png) image for submission. If the path you set in the controller is correct, it will start to work.

Initialize File Upload class

Similar to other CodeIgniter classes, the file upload class uses the $ this-> load-> library function for initialization in the Controller:

$ This-> load-> library ('upload ');

Once the file upload class is loaded, the object will be referenced using the following method: $ this-> upload

Preference settings

Similar to other libraries, you will control the files to be uploaded based on your preference settings. In the controller, you have set the following preference settings:

$ Config ['upload _ path'] = './uploads /';

$ Config ['allowed _ types'] = 'gif | jpg | png ';

$ Config ['max _ size'] = '000000 ';

$ Config ['max _ width'] = '000000 ';

$ Config ['max _ height'] = '20140901 ';

$ This-> load-> library ('upload', $ config );

// Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class:

// [If you automatically load the upload class in the autoload. php file in the config folder or load it in the constructor, you can call the initialization function initialize to load the settings. ---- The IT tumbler translation in the brackets adds your understanding]

$ This-> upload-> initialize ($ config );

The preceding preference settings are fully executed. The following describes all preference parameters.

Preference Parameters

The following preference parameters are available. When you do not specify a preference parameter, the default value is as follows:

Preference setting default value option description

Upload_path None File Upload path. The path must be writable. The relative path and absolute path can both be used.

Allowed_types None the MIME type of the file to be uploaded. Generally, the file extension can be used as the MIME type. Multiple types can be separated by vertical bars '| '.

File_name None

If this parameter is set, CodeIgniter will rename the uploaded file based on the file name set here. The file name extension must also be of the allowed file type.

Overwrite false true/FALSE (boolean) Whether to overwrite. If this parameter is set to TRUE, the original file will be overwritten if the file is uploaded with a duplicate name. If this parameter is set to FALSE, CI adds a number to the name of the new file.

Max_size 0 None the maximum file size allowed to be uploaded (in K ). If this parameter is set to 0, no restriction is imposed. Note: PHP also has this restriction, which can be specified in the php. ini file. The default value is 2 MB.

Max_width 0 None the maximum width of the uploaded file (in pixels ). 0 is unlimited.

Max_height 0 None the maximum height of the uploaded file (in pixels ). 0 is unlimited.

The maximum length of the max_filename 0 None file name. 0 is unlimited.

Encrypt_name false true/FALSE (boolean) Whether to rename the file. If this parameter is set to TRUE, the uploaded file is renamed as a random encrypted string. It is useful when you want the File Uploader not to distinguish the file name uploaded by himself. This option takes effect only when overwrite is FALSE.

When the remove_spaces TRUE/FALSE (boolean) parameter is TRUE, spaces in the file name are replaced with underscores. Recommended.

Set preference parameters in the configuration file

If you do not want to apply the above method for preference settings, you can replace it with a configuration file. Create a file named upload. php, add the $ config array to the file, and save the file to: config/upload. php, which will be automatically loaded. When you save the configuration parameters to this file, you do not need to use the $ this-> upload-> initialize function for manual loading.

Functions used

The following functions are used:

$ This-> upload-> do_upload ()

Configure parameters according to your preference to perform the operation. Note: by default, the uploaded file is from the file field named userfile in the submitted form, and the form must be of the "multipart" type:

If you want to customize your file domain name before executing the do_upload function, you can use the following methods:

$ Field_name = "some_field_name ";

$ This-> upload-> do_upload ($ field_name)

$ This-> upload-> display_errors ()

If do_upload () fails to return, an error message is displayed. This function does not automatically output but returns data, so you can arrange it as required.

Formatting error

The above functions are used by default.

Mark the error message. You can set your own separator like this.

$ This-> upload-> display_errors ('



$ This-> upload-> data ()

This is an auxiliary function that returns an array of all the information about the uploaded file.



[File_name] => mypic.jpg

[File_type] => image/jpeg

[File_path] =>/path/to/your/upload/

[Full_path] =>/path/to/your/upload/jpg.jpg

[Raw_name] => mypic

[Orig_name] => mypic.jpg

[Client_name] => mypic.jpg

[File_ext] =>. jpg

[File_size] = & gt; 22.2

[Is_image] => 1

[Image_width] = & gt; 800

[Image_height] = & gt; 600

[Image_type] => jpeg

[Image_size_str] => width = "800" height = "200"



Here is an explanation of the preceding array items.

Item Description

File_name uploaded file names (including file extensions)

Mime Type of the file_type File

File_path: the absolute path of the file that does not contain the file name

Full_path: absolute path of the file including the file name

Raw_name file name section excluding the extension

The initial file name of the File Uploaded By orig_name. This is only valid when you set the Upload File Rename (encrypt_name.

The name of the File Uploaded By client_name on the client.

File_ext file extension (including '.')

File_size: The image size, in kb.

Whether is_image is an image. 1 = is the image. 0 = not an image.

Image_width: image width.

Image_height Image Height

Image_type file type, that is, file extension (not including '.')

Image_size_str: a string containing width and height. It is used in an img label.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.