blob: d679d8aa28890a879bc89800ed7aabe16725a225 [file] [log] [blame]
Derek Jones8ede1a22011-10-05 13:34:52 -05001####################
2File Uploading Class
3####################
4
5CodeIgniter's File Uploading Class permits files to be uploaded. You can
6set various preferences, restricting the type and size of the files.
7
Derek Jonesc9bf3032013-07-24 18:01:27 -07008.. contents::
9 :local:
10
11.. raw:: html
12
13 <div class="custom-index container"></div>
14
Derek Jones8ede1a22011-10-05 13:34:52 -050015***********
16The Process
17***********
18
19Uploading a file involves the following general process:
20
21- An upload form is displayed, allowing a user to select a file and
22 upload it.
23- When the form is submitted, the file is uploaded to the destination
24 you specify.
25- Along the way, the file is validated to make sure it is allowed to be
26 uploaded based on the preferences you set.
27- Once uploaded, the user will be shown a success message.
28
29To demonstrate this process here is brief tutorial. Afterward you'll
30find reference information.
31
32Creating the Upload Form
33========================
34
35Using a text editor, create a form called upload_form.php. In it, place
Andrey Andreev05aa2d62012-12-03 16:06:55 +020036this code and save it to your **application/views/** directory::
Derek Jones8ede1a22011-10-05 13:34:52 -050037
Derek Jones07862512011-10-05 16:10:33 -050038 <html>
39 <head>
40 <title>Upload Form</title>
41 </head>
42 <body>
43
44 <?php echo $error;?>
45
46 <?php echo form_open_multipart('upload/do_upload');?>
47
48 <input type="file" name="userfile" size="20" />
49
50 <br /><br />
51
52 <input type="submit" value="upload" />
53
54 </form>
55
56 </body>
57 </html>
58
Derek Jones8ede1a22011-10-05 13:34:52 -050059You'll notice we are using a form helper to create the opening form tag.
60File uploads require a multipart form, so the helper creates the proper
61syntax for you. You'll also notice we have an $error variable. This is
62so we can show error messages in the event the user does something
63wrong.
64
65The Success Page
66================
67
68Using a text editor, create a form called upload_success.php. In it,
Andrey Andreev05aa2d62012-12-03 16:06:55 +020069place this code and save it to your **application/views/** directory::
Derek Jones8ede1a22011-10-05 13:34:52 -050070
Derek Jones07862512011-10-05 16:10:33 -050071 <html>
72 <head>
73 <title>Upload Form</title>
74 </head>
75 <body>
76
77 <h3>Your file was successfully uploaded!</h3>
78
79 <ul>
80 <?php foreach ($upload_data as $item => $value):?>
81 <li><?php echo $item;?>: <?php echo $value;?></li>
82 <?php endforeach; ?>
83 </ul>
84
85 <p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
86
87 </body>
88 </html>
89
Derek Jones8ede1a22011-10-05 13:34:52 -050090The Controller
91==============
92
Andrey Andreev20292312013-07-22 14:29:10 +030093Using a text editor, create a controller called Upload.php. In it, place
Andrey Andreev05aa2d62012-12-03 16:06:55 +020094this code and save it to your **application/controllers/** directory::
Derek Jones8ede1a22011-10-05 13:34:52 -050095
Derek Jones07862512011-10-05 16:10:33 -050096 <?php
97
98 class Upload extends CI_Controller {
99
Andrey Andreevd8e1ac72012-03-26 22:22:37 +0300100 public function __construct()
Derek Jones07862512011-10-05 16:10:33 -0500101 {
102 parent::__construct();
103 $this->load->helper(array('form', 'url'));
104 }
105
Andrey Andreevd8e1ac72012-03-26 22:22:37 +0300106 public function index()
Derek Jones07862512011-10-05 16:10:33 -0500107 {
108 $this->load->view('upload_form', array('error' => ' ' ));
109 }
110
Andrey Andreevd8e1ac72012-03-26 22:22:37 +0300111 public function do_upload()
Derek Jones07862512011-10-05 16:10:33 -0500112 {
Andrey Andreevd8e1ac72012-03-26 22:22:37 +0300113 $config['upload_path'] = './uploads/';
114 $config['allowed_types'] = 'gif|jpg|png';
115 $config['max_size'] = 100;
116 $config['max_width'] = 1024;
117 $config['max_height'] = 768;
Derek Jones07862512011-10-05 16:10:33 -0500118
119 $this->load->library('upload', $config);
120
121 if ( ! $this->upload->do_upload())
122 {
123 $error = array('error' => $this->upload->display_errors());
124
125 $this->load->view('upload_form', $error);
126 }
127 else
128 {
129 $data = array('upload_data' => $this->upload->data());
130
131 $this->load->view('upload_success', $data);
132 }
133 }
134 }
135 ?>
Derek Jones8ede1a22011-10-05 13:34:52 -0500136
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200137The Upload Directory
138====================
Derek Jones8ede1a22011-10-05 13:34:52 -0500139
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200140You'll need a destination directory for your uploaded images. Create a
141directory at the root of your CodeIgniter installation called uploads
142and set its file permissions to 777.
Derek Jones8ede1a22011-10-05 13:34:52 -0500143
144Try it!
145=======
146
147To try your form, visit your site using a URL similar to this one::
148
149 example.com/index.php/upload/
150
151You should see an upload form. Try uploading an image file (either a
152jpg, gif, or png). If the path in your controller is correct it should
153work.
154
155***************
156Reference Guide
157***************
158
159Initializing the Upload Class
160=============================
161
162Like most other classes in CodeIgniter, the Upload class is initialized
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200163in your controller using the ``$this->load->library()`` method::
Derek Jones8ede1a22011-10-05 13:34:52 -0500164
165 $this->load->library('upload');
166
167Once the Upload class is loaded, the object will be available using:
168$this->upload
169
170Setting Preferences
171===================
172
173Similar to other libraries, you'll control what is allowed to be upload
174based on your preferences. In the controller you built above you set the
175following preferences::
176
Derek Jones07862512011-10-05 16:10:33 -0500177 $config['upload_path'] = './uploads/';
178 $config['allowed_types'] = 'gif|jpg|png';
179 $config['max_size'] = '100';
180 $config['max_width'] = '1024';
181 $config['max_height'] = '768';
182
183 $this->load->library('upload', $config);
184
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200185 // Alternately you can set preferences by calling the ``initialize()`` method. Useful if you auto-load the class:
Derek Jones07862512011-10-05 16:10:33 -0500186 $this->upload->initialize($config);
Derek Jones8ede1a22011-10-05 13:34:52 -0500187
188The above preferences should be fairly self-explanatory. Below is a
189table describing all available preferences.
190
191Preferences
192===========
193
194The following preferences are available. The default value indicates
195what will be used if you do not specify that preference.
196
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400197============================ ================= ======================= ======================================================================
198Preference Default Value Options Description
199============================ ================= ======================= ======================================================================
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200200**upload_path** None None The path to the directory where the upload should be placed. The
201 directory must be writable and the path can be absolute or relative.
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400202**allowed_types** None None The mime types corresponding to the types of files you allow to be
203 uploaded. Usually the file extension can be used as the mime type.
204 Separate multiple types with a pipe.
205**file_name** None Desired file name If set CodeIgniter will rename the uploaded file to this name. The
206 extension provided in the file name must also be an allowed file type.
Andrey Andreev6123b612012-10-05 15:54:43 +0300207 If no extension is provided in the original file_name will be used.
Adrianeac8b2f2013-06-28 13:54:40 +0200208**file_ext_tolower** FALSE TRUE/FALSE (boolean) If set to TRUE, the file extension will be forced to lower case
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400209**overwrite** FALSE TRUE/FALSE (boolean) If set to true, if a file with the same name as the one you are
210 uploading exists, it will be overwritten. If set to false, a number will
211 be appended to the filename if another with the same name exists.
212**max_size** 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no
213 limit. Note: Most PHP installations have their own limit, as specified
214 in the php.ini file. Usually 2 MB (or 2048 KB) by default.
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200215**max_width** 0 None The maximum width (in pixels) that the image can be. Set to zero for no
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400216 limit.
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200217**max_height** 0 None The maximum height (in pixels) that the image can be. Set to zero for no
218 limit.
219**min_width** 0 None The minimum width (in pixels) that the image can be. Set to zero for no
220 limit.
221**min_height** 0 None The minimum height (in pixels) that the image can be. Set to zero for no
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400222 limit.
223**max_filename** 0 None The maximum length that a file name can be. Set to zero for no limit.
224**max_filename_increment** 100 None When overwrite is set to FALSE, use this to set the maximum filename
225 increment for CodeIgniter to append to the filename.
226**encrypt_name** FALSE TRUE/FALSE (boolean) If set to TRUE the file name will be converted to a random encrypted
227 string. This can be useful if you would like the file saved with a name
228 that can not be discerned by the person uploading it.
229**remove_spaces** TRUE TRUE/FALSE (boolean) If set to TRUE, any spaces in the file name will be converted to
230 underscores. This is recommended.
Andrey Andreevd60e7002012-06-17 00:03:03 +0300231**detect_mime** TRUE TRUE/FALSE (boolean) If set to TRUE, a server side detection of the file type will be
232 performed to avoid code injection attacks. DO NOT disable this option
233 unless you have no other option as that would cause a security risk.
Andrey Andreev32c72122013-10-21 15:35:05 +0300234**mod_mime_fix** TRUE TRUE/FALSE (boolean) If set to TRUE, multiple filename extensions will be suffixed with an
235 underscore in order to avoid triggering `Apache mod_mime
236 <http://httpd.apache.org/docs/2.0/mod/mod_mime.html#multipleext>`_.
237 DO NOT turn off this option if your upload directory is public, as this
238 is a security risk.
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400239============================ ================= ======================= ======================================================================
Derek Jones8ede1a22011-10-05 13:34:52 -0500240
241Setting preferences in a config file
242====================================
243
244If you prefer not to set preferences using the above method, you can
245instead put them into a config file. Simply create a new file called the
246upload.php, add the $config array in that file. Then save the file in:
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200247**config/upload.php** and it will be used automatically. You will NOT
248need to use the ``$this->upload->initialize()`` method if you save your
Derek Jones8ede1a22011-10-05 13:34:52 -0500249preferences in a config file.
250
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200251***************
252Class Reference
253***************
Derek Jones8ede1a22011-10-05 13:34:52 -0500254
Derek Jonesc9bf3032013-07-24 18:01:27 -0700255.. class:: CI_Upload
Derek Jones8ede1a22011-10-05 13:34:52 -0500256
Derek Jonesc9bf3032013-07-24 18:01:27 -0700257 .. method:: do_upload([$field = 'userfile'])
Derek Jones8ede1a22011-10-05 13:34:52 -0500258
Derek Jonesc9bf3032013-07-24 18:01:27 -0700259 :param string $field: name of the form field
260 :returns: bool
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200261
Derek Jonesc9bf3032013-07-24 18:01:27 -0700262 Performs the upload based on the preferences you've set.
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200263
Derek Jonesc9bf3032013-07-24 18:01:27 -0700264 .. note:: By default the upload routine expects the file to come from
265 a form field called userfile, and the form must be of type
266 "multipart".
Derek Jones8ede1a22011-10-05 13:34:52 -0500267
Derek Jonesc9bf3032013-07-24 18:01:27 -0700268 ::
Derek Jones8ede1a22011-10-05 13:34:52 -0500269
Derek Jonesc9bf3032013-07-24 18:01:27 -0700270 <form method="post" action="some_action" enctype="multipart/form-data" />
Derek Jones8ede1a22011-10-05 13:34:52 -0500271
Derek Jonesc9bf3032013-07-24 18:01:27 -0700272 If you would like to set your own field name simply pass its value to
273 the ``do_upload()`` method::
Derek Jones8ede1a22011-10-05 13:34:52 -0500274
Derek Jonesc9bf3032013-07-24 18:01:27 -0700275 $field_name = "some_field_name";
276 $this->upload->do_upload($field_name);
Derek Jones8ede1a22011-10-05 13:34:52 -0500277
Derek Jones8ede1a22011-10-05 13:34:52 -0500278
Derek Jonesc9bf3032013-07-24 18:01:27 -0700279 .. method:: display_errors([$open = '<p>'[, $close = '</p>']])
Derek Jones8ede1a22011-10-05 13:34:52 -0500280
Derek Jonesc9bf3032013-07-24 18:01:27 -0700281 :param string $open: Opening markup
282 :param string $close: Closing markup
283 :returns: string
Derek Jones8ede1a22011-10-05 13:34:52 -0500284
Derek Jonesc9bf3032013-07-24 18:01:27 -0700285 Retrieves any error messages if the ``do_upload()`` method returned
286 false. The method does not echo automatically, it returns the data so
287 you can assign it however you need.
Derek Jones8ede1a22011-10-05 13:34:52 -0500288
Derek Jonesc9bf3032013-07-24 18:01:27 -0700289 **Formatting Errors**
Derek Jones8ede1a22011-10-05 13:34:52 -0500290
Derek Jonesc9bf3032013-07-24 18:01:27 -0700291 By default the above method wraps any errors within <p> tags. You can
292 set your own delimiters like this::
Derek Jones8ede1a22011-10-05 13:34:52 -0500293
Derek Jonesc9bf3032013-07-24 18:01:27 -0700294 $this->upload->display_errors('<p>', '</p>');
Derek Jones8ede1a22011-10-05 13:34:52 -0500295
Michiel Vugteveen37ec30c2012-06-11 09:26:33 +0200296
Derek Jonesc9bf3032013-07-24 18:01:27 -0700297 .. method:: data([$index = NULL])
Michiel Vugteveen37ec30c2012-06-11 09:26:33 +0200298
Derek Jonesc9bf3032013-07-24 18:01:27 -0700299 :param string $data: element to return instead of the full array
300 :returns: mixed
Derek Jones8ede1a22011-10-05 13:34:52 -0500301
Derek Jonesc9bf3032013-07-24 18:01:27 -0700302 This is a helper method that returns an array containing all of the
303 data related to the file you uploaded. Here is the array prototype::
Derek Jones8ede1a22011-10-05 13:34:52 -0500304
Derek Jonesc9bf3032013-07-24 18:01:27 -0700305 Array
306 (
307 [file_name] => mypic.jpg
308 [file_type] => image/jpeg
309 [file_path] => /path/to/your/upload/
310 [full_path] => /path/to/your/upload/jpg.jpg
311 [raw_name] => mypic
312 [orig_name] => mypic.jpg
313 [client_name] => mypic.jpg
314 [file_ext] => .jpg
315 [file_size] => 22.2
316 [is_image] => 1
317 [image_width] => 800
318 [image_height] => 600
319 [image_type] => jpeg
320 [image_size_str] => width="800" height="200"
321 )
322
323 To return one element from the array::
324
325 $this->upload->data('file_name'); // Returns: mypic.jpg
326
327 **Explanation**
328
329 Here is an explanation of the above array items.
330
331 ================ ================================================
332 Item Description
333 ================ ================================================
334 file_name The name of the file that was uploaded including the file extension.
335 file_type The file's Mime type
336 file_path The absolute server path to the file
337 full_path The absolute server path including the file name
338 raw_name The file name without the extension
339 orig_name The original file name. This is only useful if you use the encrypted name option.
340 client_name The file name as supplied by the client user agent, prior to any file name preparation or incrementing.
341 file_ext The file extension with period
342 file_size The file size in kilobytes
343 is_image Whether the file is an image or not. 1 = image. 0 = not.
344 image_width Image width.
345 image_height Image height
346 image_type Image type. Typically the file extension without the period.
347 image_size_str A string containing the width and height. Useful to put into an image tag.
Andrey Andreevea801ab2014-01-20 15:03:43 +0200348 ================ ================================================