Codeigniter file upload class code example
File upload class
CodeIgniter’s file upload class allows files to be uploaded. You can set up to upload files of a certain type and size.
Processing process
Common process for uploading files:
A form for uploading files, allowing the user to select a file and upload it.
When this form is submitted, the file is uploaded to the specified directory.
At the same time, the document will be verified to see if it meets the requirements you set.
Once the file is uploaded successfully, a confirmation window indicating successful upload will be returned.
Here is a short tutorial showing the process. Hereafter you will find relevant reference information.
Create upload form
Use a 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 helper function is used here to create the start tag of the form. File upload requires a multipart form, because this form helper function creates an appropriate statement for you. You will also see that we use an $error variable, which will display relevant error information when the user submits the form and an error occurs.
Successfully uploaded page
Use a text editor to create a file named upload_success.php. Copy the following code and save it in the applications/views/ directory:
Your file was successfully uploaded!
$value):?>
:
Controller
Using a text editor, 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'] = '100'; $config['max_width'] = '1024'; $config['max_height'] = '768'; $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 will also need a destination folder to store the uploaded images. Create a file named uploads in the root directory and set the file's attributes to 777. (i.e. read and write)
Submit form
To submit your form, enter a URL similar to the following:
Example.com/index.php/upload/
You will see an upload form, select any (jpg, gif, or png) image to submit. If the path you set in the controller is correct, it will start working.
Initialize file upload class
Similar to some other CodeIgniter classes, the file upload class is initialized in the controller using the $this->load->library function:
$this->load->library('upload');
Once the file upload class is loaded, the object will be referenced through the following method: $this->upload
Preferences
Similar to other libraries, you will control which files are uploaded based on your preferences. In the controller, you create the following preferences:
$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);
// Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class:
//[If you automatically loaded the upload class in the autoload.php file in the config folder, or loaded it in the constructor, you can call the initialization function initialize to load the settings. ————This bracket is translated by IT Tumbler, with my own understanding added】
$this->upload->initialize($config);
The above preferences will be fully implemented. Below are descriptions of all preference parameters.
Preference parameters
The following preference parameters are available. When you don't specify a preference parameter, the default value is as follows:
Preferences Default Value Option Description
upload_path None None File upload path. The path must be writable, both relative and absolute paths are acceptable.
allowed_types None None MIME types that allow uploading files; usually file extensions can be used as MIME types. Multiple types are allowed to be separated by vertical bars ‘|’
File_name None The file name you want to use
If this parameter is set, CodeIgniter will rename the uploaded file according to the file name set here. The extension in the file name must also be an allowed file type.
overwrite FALSE TRUE/FALSE (boolean) Whether to overwrite. When this parameter is TRUE, if a file with the same name is encountered when uploading a file, the original file will be overwritten; if this parameter is FALSE, when a file with the same name is uploaded, CI will add a number after the file name of the new file.
max_size 0 None The maximum allowed upload file size (in K). If this parameter is 0, there is no limit. Note: Usually PHP also has this restriction, which can be specified in the php.ini file. Usually the default is 2MB.
max_width 0 None The maximum width of the uploaded file (in pixels). 0 means no limit.
max_height 0 None The maximum height of the uploaded file (in pixels). 0 means no limit.
max_filename 0 None The maximum length of the file name. 0 means no limit.
encrypt_name FALSE TRUE/FALSE (boolean) Whether to rename the file. If this parameter is TRUE, the uploaded file will be renamed to a random encrypted string. This is very useful when you want the file uploader to be unable to distinguish the file names of the files they upload. This option only works when overwrite is FALSE.
remove_spaces TRUE TRUE/FALSE (boolean) When the parameter is TRUE, spaces in the file name will be replaced with underscores. Recommended.
Set preference parameters in the configuration file
If you don’t want to use the above method to set preferences, you can use a configuration file instead. Simply create a file called upload.php, add the $config array to the file, then save the file to: config/upload.php and it will be loaded automatically. When you save configuration parameters to this file, you do not need to manually load them using the $this->upload->initialize function.
Functions used
The following functions are used
$this->upload->do_upload()
Perform operations based on your preferred configuration parameters. Note: By default, the uploaded file comes from the file field named userfile in the submission form, and the form must be of type "multipart":
If you want to customize your own file domain name before executing the do_upload function, you can do so through the following methods:
$field_name = "some_field_name";
$this->upload->do_upload($field_name)
$this->upload->display_errors()
If do_upload() returns failure, an error message will be displayed. This function does not automatically output, but returns data, so you can arrange it however you want.
Formatting error
The above function uses
by defaultMark error messages. You can set your own separator like this.
$this->upload->display_errors('
, '
);
$this->upload->data()
This is a helper function that returns an array of all relevant information about the file you uploaded.
Array
(
[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] => 22.2
[is_image] => 1
[image_width] => 800
[image_height] => 600
[image_type] => jpeg
[image_size_str] => width="800" height="200"
)
Explanation
Here is an explanation of the above array items.
Item Description
file_name The name of the uploaded file (including extension)
file_type Mime type of the file
file_path The absolute path of the file excluding the file name
full_path The absolute path of the file including the file name
raw_name The part of the file name excluding the extension
orig_name The initial file name of the uploaded file. This only works if upload file rename (encrypt_name) is set.
Client_name is the file name of the uploaded file on the client.
file_ext file extension (including ‘.’)
file_size image size, unit is kb
Is_image whether it is an image. 1 = is an image. 0 = Not an image.
Image_width image width.
image_height image height
Image_type file type, that is, file extension (excluding ‘.’)
Image_size_str A string containing width and height. Used in an img tag.