blob: c2de598658063468c16d36d6927520b64930cb4c [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
29this code and save it to your applications/views/ folder:
30
31<html> <head> <title>Upload Form</title> </head> <body> <?php echo
32$error;?> <?php echo form_open_multipart('upload/do_upload');?>
33<input type="file" name="userfile" size="20" /> <br /><br /> <input
34type="submit" value="upload" /> </form> </body> </html>
35You'll notice we are using a form helper to create the opening form tag.
36File uploads require a multipart form, so the helper creates the proper
37syntax for you. You'll also notice we have an $error variable. This is
38so we can show error messages in the event the user does something
39wrong.
40
41The Success Page
42================
43
44Using a text editor, create a form called upload_success.php. In it,
45place this code and save it to your applications/views/ folder:
46
47<html> <head> <title>Upload Form</title> </head> <body> <h3>Your file
48was successfully uploaded!</h3> <ul> <?php foreach ($upload_data as
49$item => $value):?> <li><?php echo $item;?>: <?php echo $value;?></li>
50<?php endforeach; ?> </ul> <p><?php echo anchor('upload', 'Upload
51Another File!'); ?></p> </body> </html>
52The Controller
53==============
54
55Using a text editor, create a controller called upload.php. In it, place
56this code and save it to your applications/controllers/ folder:
57
58<?php class Upload extends CI_Controller { function \__construct() {
59parent::\__construct(); $this->load->helper(array('form', 'url')); }
60function index() { $this->load->view('upload_form', array('error' => '
61' )); } function do_upload() { $config['upload_path'] = './uploads/';
62$config['allowed_types'] = 'gif\|jpg\|png'; $config['max_size'] =
63'100'; $config['max_width'] = '1024'; $config['max_height'] = '768';
64$this->load->library('upload', $config); if ( !
65$this->upload->do_upload()) { $error = array('error' =>
66$this->upload->display_errors()); $this->load->view('upload_form',
67$error); } else { $data = array('upload_data' =>
68$this->upload->data()); $this->load->view('upload_success', $data); } }
69} ?>
70
71The Upload Folder
72=================
73
74You'll need a destination folder for your uploaded images. Create a
75folder at the root of your CodeIgniter installation called uploads and
76set its file permissions to 777.
77
78Try it!
79=======
80
81To try your form, visit your site using a URL similar to this one::
82
83 example.com/index.php/upload/
84
85You should see an upload form. Try uploading an image file (either a
86jpg, gif, or png). If the path in your controller is correct it should
87work.
88
89***************
90Reference Guide
91***************
92
93Initializing the Upload Class
94=============================
95
96Like most other classes in CodeIgniter, the Upload class is initialized
97in your controller using the $this->load->library function::
98
99 $this->load->library('upload');
100
101Once the Upload class is loaded, the object will be available using:
102$this->upload
103
104Setting Preferences
105===================
106
107Similar to other libraries, you'll control what is allowed to be upload
108based on your preferences. In the controller you built above you set the
109following preferences::
110
111 $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: $this->upload->initialize($config);
112
113The above preferences should be fairly self-explanatory. Below is a
114table describing all available preferences.
115
116Preferences
117===========
118
119The following preferences are available. The default value indicates
120what will be used if you do not specify that preference.
121
122Preference
123Default Value
124Options
125Description
126**upload_path**
127None
128None
129The path to the folder where the upload should be placed. The folder
130must be writable and the path can be absolute or relative.
131**allowed_types**
132None
133None
134The mime types corresponding to the types of files you allow to be
135uploaded. Usually the file extension can be used as the mime type.
136Separate multiple types with a pipe.
137**file_name**
138None
139Desired file name
140If set CodeIgniter will rename the uploaded file to this name. The
141extension provided in the file name must also be an allowed file type.
142
143**overwrite**
144FALSE
145TRUE/FALSE (boolean)
146If set to true, if a file with the same name as the one you are
147uploading exists, it will be overwritten. If set to false, a number will
148be appended to the filename if another with the same name exists.
149**max_size**
1500
151None
152The maximum size (in kilobytes) that the file can be. Set to zero for no
153limit. Note: Most PHP installations have their own limit, as specified
154in the php.ini file. Usually 2 MB (or 2048 KB) by default.
155**max_width**
1560
157None
158The maximum width (in pixels) that the file can be. Set to zero for no
159limit.
160**max_height**
1610
162None
163The maximum height (in pixels) that the file can be. Set to zero for no
164limit.
165**max_filename**
1660
167None
168The maximum length that a file name can be. Set to zero for no limit.
169**max_filename_increment**
170100
171None
172When overwrite is set to FALSE, use this to set the maximum filename
173increment for CodeIgniter to append to the filename.
174**encrypt_name**
175FALSE
176TRUE/FALSE (boolean)
177If set to TRUE the file name will be converted to a random encrypted
178string. This can be useful if you would like the file saved with a name
179that can not be discerned by the person uploading it.
180**remove_spaces**
181TRUE
182TRUE/FALSE (boolean)
183If set to TRUE, any spaces in the file name will be converted to
184underscores. This is recommended.
185
186Setting preferences in a config file
187====================================
188
189If you prefer not to set preferences using the above method, you can
190instead put them into a config file. Simply create a new file called the
191upload.php, add the $config array in that file. Then save the file in:
192config/upload.php and it will be used automatically. You will NOT need
193to use the $this->upload->initialize function if you save your
194preferences in a config file.
195
196******************
197Function Reference
198******************
199
200The following functions are available
201
202$this->upload->do_upload()
203===========================
204
205Performs the upload based on the preferences you've set. Note: By
206default the upload routine expects the file to come from a form field
207called userfile, and the form must be a "multipart type::
208
209 <form method="post" action="some_action" enctype="multipart/form-data" />
210
211If you would like to set your own field name simply pass its value to
212the do_upload function::
213
214 $field_name = "some_field_name"; $this->upload->do_upload($field_name)
215
216$this->upload->display_errors()
217================================
218
219Retrieves any error messages if the do_upload() function returned
220false. The function does not echo automatically, it returns the data so
221you can assign it however you need.
222
223Formatting Errors
224*****************
225
226By default the above function wraps any errors within <p> tags. You can
227set your own delimiters like this::
228
229 $this->upload->display_errors('<p>', '</p>');
230
231$this->upload->data()
232=====================
233
234This is a helper function that returns an array containing all of the
235data related to the file you uploaded. Here is the array prototype::
236
237 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" )
238
239Explanation
240***********
241
242Here is an explanation of the above array items.
243
244Item
245Description
246**file_name**
247The name of the file that was uploaded including the file extension.
248**file_type**
249The file's Mime type
250**file_path**
251The absolute server path to the file
252**full_path**
253The absolute server path including the file name
254**raw_name**
255The file name without the extension
256**orig_name**
257The original file name. This is only useful if you use the encrypted
258name option.
259**client_name**
260The file name as supplied by the client user agent, prior to any file
261name preparation or incrementing.
262**file_ext**
263The file extension with period
264**file_size**
265The file size in kilobytes
266**is_image**
267Whether the file is an image or not. 1 = image. 0 = not.
268**image_width**
269Image width.
270**image_height**
271Image height
272**image_type**
273Image type. Typically the file extension without the period.
274**image_size_str**
275A string containing the width and height. Useful to put into an image
276tag.