blob: a295d74275319cd4745b2afda3def29fe4db506d [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
8***********
9The Process
10***********
11
12Uploading a file involves the following general process:
13
14- An upload form is displayed, allowing a user to select a file and
15 upload it.
16- When the form is submitted, the file is uploaded to the destination
17 you specify.
18- Along the way, the file is validated to make sure it is allowed to be
19 uploaded based on the preferences you set.
20- Once uploaded, the user will be shown a success message.
21
22To demonstrate this process here is brief tutorial. Afterward you'll
23find reference information.
24
25Creating the Upload Form
26========================
27
28Using a text editor, create a form called upload_form.php. In it, place
Andrey Andreev05aa2d62012-12-03 16:06:55 +020029this code and save it to your **application/views/** directory::
Derek Jones8ede1a22011-10-05 13:34:52 -050030
Derek Jones07862512011-10-05 16:10:33 -050031 <html>
32 <head>
33 <title>Upload Form</title>
34 </head>
35 <body>
36
37 <?php echo $error;?>
38
39 <?php echo form_open_multipart('upload/do_upload');?>
40
41 <input type="file" name="userfile" size="20" />
42
43 <br /><br />
44
45 <input type="submit" value="upload" />
46
47 </form>
48
49 </body>
50 </html>
51
Derek Jones8ede1a22011-10-05 13:34:52 -050052You'll notice we are using a form helper to create the opening form tag.
53File uploads require a multipart form, so the helper creates the proper
54syntax for you. You'll also notice we have an $error variable. This is
55so we can show error messages in the event the user does something
56wrong.
57
58The Success Page
59================
60
61Using a text editor, create a form called upload_success.php. In it,
Andrey Andreev05aa2d62012-12-03 16:06:55 +020062place this code and save it to your **application/views/** directory::
Derek Jones8ede1a22011-10-05 13:34:52 -050063
Derek Jones07862512011-10-05 16:10:33 -050064 <html>
65 <head>
66 <title>Upload Form</title>
67 </head>
68 <body>
69
70 <h3>Your file was successfully uploaded!</h3>
71
72 <ul>
73 <?php foreach ($upload_data as $item => $value):?>
74 <li><?php echo $item;?>: <?php echo $value;?></li>
75 <?php endforeach; ?>
76 </ul>
77
78 <p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
79
80 </body>
81 </html>
82
Derek Jones8ede1a22011-10-05 13:34:52 -050083The Controller
84==============
85
Andrey Andreev20292312013-07-22 14:29:10 +030086Using a text editor, create a controller called Upload.php. In it, place
Andrey Andreev05aa2d62012-12-03 16:06:55 +020087this code and save it to your **application/controllers/** directory::
Derek Jones8ede1a22011-10-05 13:34:52 -050088
Derek Jones07862512011-10-05 16:10:33 -050089 <?php
90
91 class Upload extends CI_Controller {
92
Andrey Andreevd8e1ac72012-03-26 22:22:37 +030093 public function __construct()
Derek Jones07862512011-10-05 16:10:33 -050094 {
95 parent::__construct();
96 $this->load->helper(array('form', 'url'));
97 }
98
Andrey Andreevd8e1ac72012-03-26 22:22:37 +030099 public function index()
Derek Jones07862512011-10-05 16:10:33 -0500100 {
101 $this->load->view('upload_form', array('error' => ' ' ));
102 }
103
Andrey Andreevd8e1ac72012-03-26 22:22:37 +0300104 public function do_upload()
Derek Jones07862512011-10-05 16:10:33 -0500105 {
Andrey Andreevd8e1ac72012-03-26 22:22:37 +0300106 $config['upload_path'] = './uploads/';
107 $config['allowed_types'] = 'gif|jpg|png';
108 $config['max_size'] = 100;
109 $config['max_width'] = 1024;
110 $config['max_height'] = 768;
Derek Jones07862512011-10-05 16:10:33 -0500111
112 $this->load->library('upload', $config);
113
114 if ( ! $this->upload->do_upload())
115 {
116 $error = array('error' => $this->upload->display_errors());
117
118 $this->load->view('upload_form', $error);
119 }
120 else
121 {
122 $data = array('upload_data' => $this->upload->data());
123
124 $this->load->view('upload_success', $data);
125 }
126 }
127 }
128 ?>
Derek Jones8ede1a22011-10-05 13:34:52 -0500129
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200130The Upload Directory
131====================
Derek Jones8ede1a22011-10-05 13:34:52 -0500132
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200133You'll need a destination directory for your uploaded images. Create a
134directory at the root of your CodeIgniter installation called uploads
135and set its file permissions to 777.
Derek Jones8ede1a22011-10-05 13:34:52 -0500136
137Try it!
138=======
139
140To try your form, visit your site using a URL similar to this one::
141
142 example.com/index.php/upload/
143
144You should see an upload form. Try uploading an image file (either a
145jpg, gif, or png). If the path in your controller is correct it should
146work.
147
148***************
149Reference Guide
150***************
151
152Initializing the Upload Class
153=============================
154
155Like most other classes in CodeIgniter, the Upload class is initialized
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200156in your controller using the ``$this->load->library()`` method::
Derek Jones8ede1a22011-10-05 13:34:52 -0500157
158 $this->load->library('upload');
159
160Once the Upload class is loaded, the object will be available using:
161$this->upload
162
163Setting Preferences
164===================
165
166Similar to other libraries, you'll control what is allowed to be upload
167based on your preferences. In the controller you built above you set the
168following preferences::
169
Derek Jones07862512011-10-05 16:10:33 -0500170 $config['upload_path'] = './uploads/';
171 $config['allowed_types'] = 'gif|jpg|png';
172 $config['max_size'] = '100';
173 $config['max_width'] = '1024';
174 $config['max_height'] = '768';
175
176 $this->load->library('upload', $config);
177
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200178 // Alternately you can set preferences by calling the ``initialize()`` method. Useful if you auto-load the class:
Derek Jones07862512011-10-05 16:10:33 -0500179 $this->upload->initialize($config);
Derek Jones8ede1a22011-10-05 13:34:52 -0500180
181The above preferences should be fairly self-explanatory. Below is a
182table describing all available preferences.
183
184Preferences
185===========
186
187The following preferences are available. The default value indicates
188what will be used if you do not specify that preference.
189
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400190============================ ================= ======================= ======================================================================
191Preference Default Value Options Description
192============================ ================= ======================= ======================================================================
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200193**upload_path** None None The path to the directory where the upload should be placed. The
194 directory must be writable and the path can be absolute or relative.
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400195**allowed_types** None None The mime types corresponding to the types of files you allow to be
196 uploaded. Usually the file extension can be used as the mime type.
197 Separate multiple types with a pipe.
198**file_name** None Desired file name If set CodeIgniter will rename the uploaded file to this name. The
199 extension provided in the file name must also be an allowed file type.
Andrey Andreev6123b612012-10-05 15:54:43 +0300200 If no extension is provided in the original file_name will be used.
Adrianeac8b2f2013-06-28 13:54:40 +0200201**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 -0400202**overwrite** FALSE TRUE/FALSE (boolean) If set to true, if a file with the same name as the one you are
203 uploading exists, it will be overwritten. If set to false, a number will
204 be appended to the filename if another with the same name exists.
205**max_size** 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no
206 limit. Note: Most PHP installations have their own limit, as specified
207 in the php.ini file. Usually 2 MB (or 2048 KB) by default.
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200208**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 -0400209 limit.
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200210**max_height** 0 None The maximum height (in pixels) that the image can be. Set to zero for no
211 limit.
212**min_width** 0 None The minimum width (in pixels) that the image can be. Set to zero for no
213 limit.
214**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 -0400215 limit.
216**max_filename** 0 None The maximum length that a file name can be. Set to zero for no limit.
217**max_filename_increment** 100 None When overwrite is set to FALSE, use this to set the maximum filename
218 increment for CodeIgniter to append to the filename.
219**encrypt_name** FALSE TRUE/FALSE (boolean) If set to TRUE the file name will be converted to a random encrypted
220 string. This can be useful if you would like the file saved with a name
221 that can not be discerned by the person uploading it.
222**remove_spaces** TRUE TRUE/FALSE (boolean) If set to TRUE, any spaces in the file name will be converted to
223 underscores. This is recommended.
Andrey Andreevd60e7002012-06-17 00:03:03 +0300224**detect_mime** TRUE TRUE/FALSE (boolean) If set to TRUE, a server side detection of the file type will be
225 performed to avoid code injection attacks. DO NOT disable this option
226 unless you have no other option as that would cause a security risk.
Joseph Wensleyd87e5e62011-10-06 00:06:10 -0400227============================ ================= ======================= ======================================================================
Derek Jones8ede1a22011-10-05 13:34:52 -0500228
229Setting preferences in a config file
230====================================
231
232If you prefer not to set preferences using the above method, you can
233instead put them into a config file. Simply create a new file called the
234upload.php, add the $config array in that file. Then save the file in:
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200235**config/upload.php** and it will be used automatically. You will NOT
236need to use the ``$this->upload->initialize()`` method if you save your
Derek Jones8ede1a22011-10-05 13:34:52 -0500237preferences in a config file.
238
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200239***************
240Class Reference
241***************
Derek Jones8ede1a22011-10-05 13:34:52 -0500242
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200243The following methods are available:
Derek Jones8ede1a22011-10-05 13:34:52 -0500244
245$this->upload->do_upload()
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200246==========================
Derek Jones8ede1a22011-10-05 13:34:52 -0500247
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200248Performs the upload based on the preferences you've set.
249
250.. note:: By default the upload routine expects the file to come from
251 a form field called userfile, and the form must be of type
252 "multipart".
253
254::
Derek Jones8ede1a22011-10-05 13:34:52 -0500255
256 <form method="post" action="some_action" enctype="multipart/form-data" />
257
258If you would like to set your own field name simply pass its value to
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200259the ``do_upload()`` method::
Derek Jones8ede1a22011-10-05 13:34:52 -0500260
Derek Jones07862512011-10-05 16:10:33 -0500261 $field_name = "some_field_name";
262 $this->upload->do_upload($field_name);
Derek Jones8ede1a22011-10-05 13:34:52 -0500263
264$this->upload->display_errors()
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200265===============================
Derek Jones8ede1a22011-10-05 13:34:52 -0500266
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200267Retrieves any error messages if the ``do_upload()`` method returned
268false. The method does not echo automatically, it returns the data so
Derek Jones8ede1a22011-10-05 13:34:52 -0500269you can assign it however you need.
270
271Formatting Errors
272*****************
273
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200274By default the above method wraps any errors within <p> tags. You can
Derek Jones8ede1a22011-10-05 13:34:52 -0500275set your own delimiters like this::
276
277 $this->upload->display_errors('<p>', '</p>');
278
279$this->upload->data()
280=====================
281
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200282This is a helper method that returns an array containing all of the
Derek Jones8ede1a22011-10-05 13:34:52 -0500283data related to the file you uploaded. Here is the array prototype::
284
Derek Jones07862512011-10-05 16:10:33 -0500285 Array
286 (
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200287 [file_name] => mypic.jpg
288 [file_type] => image/jpeg
289 [file_path] => /path/to/your/upload/
290 [full_path] => /path/to/your/upload/jpg.jpg
291 [raw_name] => mypic
292 [orig_name] => mypic.jpg
293 [client_name] => mypic.jpg
294 [file_ext] => .jpg
295 [file_size] => 22.2
296 [is_image] => 1
297 [image_width] => 800
298 [image_height] => 600
299 [image_type] => jpeg
300 [image_size_str] => width="800" height="200"
Derek Jones07862512011-10-05 16:10:33 -0500301 )
Derek Jones8ede1a22011-10-05 13:34:52 -0500302
Michiel Vugteveen37ec30c2012-06-11 09:26:33 +0200303To return one element from the array::
304
305 $this->upload->data('file_name'); // Returns: mypic.jpg
306
Derek Jones8ede1a22011-10-05 13:34:52 -0500307Explanation
308***********
309
310Here is an explanation of the above array items.
311
312Item
313Description
314**file_name**
315The name of the file that was uploaded including the file extension.
316**file_type**
317The file's Mime type
318**file_path**
319The absolute server path to the file
320**full_path**
321The absolute server path including the file name
322**raw_name**
323The file name without the extension
324**orig_name**
325The original file name. This is only useful if you use the encrypted
326name option.
327**client_name**
328The file name as supplied by the client user agent, prior to any file
329name preparation or incrementing.
330**file_ext**
331The file extension with period
332**file_size**
333The file size in kilobytes
334**is_image**
335Whether the file is an image or not. 1 = image. 0 = not.
336**image_width**
337Image width.
338**image_height**
339Image height
340**image_type**
341Image type. Typically the file extension without the period.
342**image_size_str**
343A string containing the width and height. Useful to put into an image
Andrey Andreev05aa2d62012-12-03 16:06:55 +0200344tag.