blob: 695998d73dd50f525b0a75976646a6d9a578c821 [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
93Using 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.
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400234============================ ================= ======================= ======================================================================
Derek Jones8ede1a22011-10-05 13:34:52 -0500235
236Setting preferences in a config file
237====================================
238
239If you prefer not to set preferences using the above method, you can
240instead put them into a config file. Simply create a new file called the
241upload.php, add the $config array in that file. Then save the file in:
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200242**config/upload.php** and it will be used automatically. You will NOT
243need to use the ``$this->upload->initialize()`` method if you save your
Derek Jones8ede1a22011-10-05 13:34:52 -0500244preferences in a config file.
245
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200246***************
247Class Reference
248***************
Derek Jones8ede1a22011-10-05 13:34:52 -0500249
Derek Jonesc9bf3032013-07-24 18:01:27 -0700250.. class:: CI_Upload
Derek Jones8ede1a22011-10-05 13:34:52 -0500251
Derek Jonesc9bf3032013-07-24 18:01:27 -0700252 .. method:: do_upload([$field = 'userfile'])
Derek Jones8ede1a22011-10-05 13:34:52 -0500253
Derek Jonesc9bf3032013-07-24 18:01:27 -0700254 :param string $field: name of the form field
255 :returns: bool
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200256
Derek Jonesc9bf3032013-07-24 18:01:27 -0700257 Performs the upload based on the preferences you've set.
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200258
Derek Jonesc9bf3032013-07-24 18:01:27 -0700259 .. note:: By default the upload routine expects the file to come from
260 a form field called userfile, and the form must be of type
261 "multipart".
Derek Jones8ede1a22011-10-05 13:34:52 -0500262
Derek Jonesc9bf3032013-07-24 18:01:27 -0700263 ::
Derek Jones8ede1a22011-10-05 13:34:52 -0500264
Derek Jonesc9bf3032013-07-24 18:01:27 -0700265 <form method="post" action="some_action" enctype="multipart/form-data" />
Derek Jones8ede1a22011-10-05 13:34:52 -0500266
Derek Jonesc9bf3032013-07-24 18:01:27 -0700267 If you would like to set your own field name simply pass its value to
268 the ``do_upload()`` method::
Derek Jones8ede1a22011-10-05 13:34:52 -0500269
Derek Jonesc9bf3032013-07-24 18:01:27 -0700270 $field_name = "some_field_name";
271 $this->upload->do_upload($field_name);
Derek Jones8ede1a22011-10-05 13:34:52 -0500272
Derek Jones8ede1a22011-10-05 13:34:52 -0500273
Derek Jonesc9bf3032013-07-24 18:01:27 -0700274 .. method:: display_errors([$open = '<p>'[, $close = '</p>']])
Derek Jones8ede1a22011-10-05 13:34:52 -0500275
Derek Jonesc9bf3032013-07-24 18:01:27 -0700276 :param string $open: Opening markup
277 :param string $close: Closing markup
278 :returns: string
Derek Jones8ede1a22011-10-05 13:34:52 -0500279
Derek Jonesc9bf3032013-07-24 18:01:27 -0700280 Retrieves any error messages if the ``do_upload()`` method returned
281 false. The method does not echo automatically, it returns the data so
282 you can assign it however you need.
Derek Jones8ede1a22011-10-05 13:34:52 -0500283
Derek Jonesc9bf3032013-07-24 18:01:27 -0700284 **Formatting Errors**
Derek Jones8ede1a22011-10-05 13:34:52 -0500285
Derek Jonesc9bf3032013-07-24 18:01:27 -0700286 By default the above method wraps any errors within <p> tags. You can
287 set your own delimiters like this::
Derek Jones8ede1a22011-10-05 13:34:52 -0500288
Derek Jonesc9bf3032013-07-24 18:01:27 -0700289 $this->upload->display_errors('<p>', '</p>');
Derek Jones8ede1a22011-10-05 13:34:52 -0500290
Michiel Vugteveen37ec30c2012-06-11 09:26:33 +0200291
Derek Jonesc9bf3032013-07-24 18:01:27 -0700292 .. method:: data([$index = NULL])
Michiel Vugteveen37ec30c2012-06-11 09:26:33 +0200293
Derek Jonesc9bf3032013-07-24 18:01:27 -0700294 :param string $data: element to return instead of the full array
295 :returns: mixed
Derek Jones8ede1a22011-10-05 13:34:52 -0500296
Derek Jonesc9bf3032013-07-24 18:01:27 -0700297 This is a helper method that returns an array containing all of the
298 data related to the file you uploaded. Here is the array prototype::
Derek Jones8ede1a22011-10-05 13:34:52 -0500299
Derek Jonesc9bf3032013-07-24 18:01:27 -0700300 Array
301 (
302 [file_name] => mypic.jpg
303 [file_type] => image/jpeg
304 [file_path] => /path/to/your/upload/
305 [full_path] => /path/to/your/upload/jpg.jpg
306 [raw_name] => mypic
307 [orig_name] => mypic.jpg
308 [client_name] => mypic.jpg
309 [file_ext] => .jpg
310 [file_size] => 22.2
311 [is_image] => 1
312 [image_width] => 800
313 [image_height] => 600
314 [image_type] => jpeg
315 [image_size_str] => width="800" height="200"
316 )
317
318 To return one element from the array::
319
320 $this->upload->data('file_name'); // Returns: mypic.jpg
321
322 **Explanation**
323
324 Here is an explanation of the above array items.
325
326 ================ ================================================
327 Item Description
328 ================ ================================================
329 file_name The name of the file that was uploaded including the file extension.
330 file_type The file's Mime type
331 file_path The absolute server path to the file
332 full_path The absolute server path including the file name
333 raw_name The file name without the extension
334 orig_name The original file name. This is only useful if you use the encrypted name option.
335 client_name The file name as supplied by the client user agent, prior to any file name preparation or incrementing.
336 file_ext The file extension with period
337 file_size The file size in kilobytes
338 is_image Whether the file is an image or not. 1 = image. 0 = not.
339 image_width Image width.
340 image_height Image height
341 image_type Image type. Typically the file extension without the period.
342 image_size_str A string containing the width and height. Useful to put into an image tag.
343 ================ ================================================