blob: babdc04f9748924de90f2cf9b65239ea37f542ec [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
Ticemad90a65c2015-05-17 18:29:21 -0300121 if ( ! $this->upload->do_upload('userfile'))
Derek Jones07862512011-10-05 16:10:33 -0500122 {
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.
Andrey Andreev2cf4c9b2014-02-21 15:01:48 +0200204 Can be either an array or a pipe-separated string.
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400205**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
Andrey Andreevcd3d9db2015-02-02 13:41:01 +0200255.. php:class:: CI_Upload
Derek Jones8ede1a22011-10-05 13:34:52 -0500256
Andrey Andreevcd3d9db2015-02-02 13:41:01 +0200257 .. php:method:: initialize([array $config = array()[, $reset = TRUE]])
Andrey Andreev2cf4c9b2014-02-21 15:01:48 +0200258
259 :param array $config: Preferences
260 :param bool $reset: Whether to reset preferences (that are not provided in $config) to their defaults
261 :returns: CI_Upload instance (method chaining)
262 :rtype: CI_Upload
263
Andrey Andreevcd3d9db2015-02-02 13:41:01 +0200264 .. php:method:: do_upload([$field = 'userfile'])
Derek Jones8ede1a22011-10-05 13:34:52 -0500265
Andrey Andreev28c2c972014-02-08 04:27:48 +0200266 :param string $field: Name of the form field
267 :returns: TRUE on success, FALSE on failure
268 :rtype: bool
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200269
Derek Jonesc9bf3032013-07-24 18:01:27 -0700270 Performs the upload based on the preferences you've set.
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200271
Derek Jonesc9bf3032013-07-24 18:01:27 -0700272 .. note:: By default the upload routine expects the file to come from
273 a form field called userfile, and the form must be of type
274 "multipart".
Derek Jones8ede1a22011-10-05 13:34:52 -0500275
Derek Jonesc9bf3032013-07-24 18:01:27 -0700276 ::
Derek Jones8ede1a22011-10-05 13:34:52 -0500277
Derek Jonesc9bf3032013-07-24 18:01:27 -0700278 <form method="post" action="some_action" enctype="multipart/form-data" />
Derek Jones8ede1a22011-10-05 13:34:52 -0500279
Derek Jonesc9bf3032013-07-24 18:01:27 -0700280 If you would like to set your own field name simply pass its value to
281 the ``do_upload()`` method::
Derek Jones8ede1a22011-10-05 13:34:52 -0500282
Derek Jonesc9bf3032013-07-24 18:01:27 -0700283 $field_name = "some_field_name";
284 $this->upload->do_upload($field_name);
Derek Jones8ede1a22011-10-05 13:34:52 -0500285
Andrey Andreevcd3d9db2015-02-02 13:41:01 +0200286 .. php:method:: display_errors([$open = '<p>'[, $close = '</p>']])
Derek Jones8ede1a22011-10-05 13:34:52 -0500287
Andrey Andreev28c2c972014-02-08 04:27:48 +0200288 :param string $open: Opening markup
289 :param string $close: Closing markup
290 :returns: Formatted error message(s)
291 :rtype: string
Derek Jones8ede1a22011-10-05 13:34:52 -0500292
Derek Jonesc9bf3032013-07-24 18:01:27 -0700293 Retrieves any error messages if the ``do_upload()`` method returned
294 false. The method does not echo automatically, it returns the data so
295 you can assign it however you need.
Derek Jones8ede1a22011-10-05 13:34:52 -0500296
Derek Jonesc9bf3032013-07-24 18:01:27 -0700297 **Formatting Errors**
Derek Jones8ede1a22011-10-05 13:34:52 -0500298
Derek Jonesc9bf3032013-07-24 18:01:27 -0700299 By default the above method wraps any errors within <p> tags. You can
300 set your own delimiters like this::
Derek Jones8ede1a22011-10-05 13:34:52 -0500301
Derek Jonesc9bf3032013-07-24 18:01:27 -0700302 $this->upload->display_errors('<p>', '</p>');
Derek Jones8ede1a22011-10-05 13:34:52 -0500303
Michiel Vugteveen37ec30c2012-06-11 09:26:33 +0200304
Andrey Andreevcd3d9db2015-02-02 13:41:01 +0200305 .. php:method:: data([$index = NULL])
Michiel Vugteveen37ec30c2012-06-11 09:26:33 +0200306
Andrey Andreev28c2c972014-02-08 04:27:48 +0200307 :param string $data: Element to return instead of the full array
308 :returns: Information about the uploaded file
309 :rtype: mixed
Derek Jones8ede1a22011-10-05 13:34:52 -0500310
Derek Jonesc9bf3032013-07-24 18:01:27 -0700311 This is a helper method that returns an array containing all of the
312 data related to the file you uploaded. Here is the array prototype::
Derek Jones8ede1a22011-10-05 13:34:52 -0500313
Derek Jonesc9bf3032013-07-24 18:01:27 -0700314 Array
315 (
316 [file_name] => mypic.jpg
317 [file_type] => image/jpeg
318 [file_path] => /path/to/your/upload/
319 [full_path] => /path/to/your/upload/jpg.jpg
320 [raw_name] => mypic
321 [orig_name] => mypic.jpg
322 [client_name] => mypic.jpg
323 [file_ext] => .jpg
324 [file_size] => 22.2
325 [is_image] => 1
326 [image_width] => 800
327 [image_height] => 600
328 [image_type] => jpeg
329 [image_size_str] => width="800" height="200"
330 )
331
332 To return one element from the array::
333
334 $this->upload->data('file_name'); // Returns: mypic.jpg
335
Andrey Andreev28c2c972014-02-08 04:27:48 +0200336 Here's a table explaining the above-displayed array items:
Derek Jonesc9bf3032013-07-24 18:01:27 -0700337
Andrey Andreev28c2c972014-02-08 04:27:48 +0200338 ================ ====================================================================================================
339 Item Description
340 ================ ====================================================================================================
341 file_name Name of the file that was uploaded, including the filename extension
342 file_type File MIME type identifier
343 file_path Absolute server path to the file
344 full_path Absolute server path, including the file name
345 raw_name File name, without the extension
346 orig_name Original file name. This is only useful if you use the encrypted name option.
Andrey Andreev11c25e12018-03-26 20:16:15 +0300347 client_name File name supplied by the client user agent, but possibly sanitized
Andrey Andreev28c2c972014-02-08 04:27:48 +0200348 file_ext Filename extension, period included
349 file_size File size in kilobytes
350 is_image Whether the file is an image or not. 1 = image. 0 = not.
351 image_width Image width
352 image_height Image height
353 image_type Image type (usually the file name extension without the period)
354 image_size_str A string containing the width and height (useful to put into an image tag)
Ticemad90a65c2015-05-17 18:29:21 -0300355 ================ ====================================================================================================