Skip to content

Commit 352a671

Browse files
committed
docs: add file upload sample code like CI3
1 parent 49a07f0 commit 352a671

1 file changed

Lines changed: 163 additions & 13 deletions

File tree

user_guide_src/source/libraries/uploaded_files.rst

Lines changed: 163 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
***************************
1+
###########################
22
Working with Uploaded Files
3-
***************************
3+
###########################
44

55
CodeIgniter makes working with files uploaded through a form much simpler and more secure than using PHP's ``$_FILES``
66
array directly. This extends the :doc:`File class </libraries/files>` and thus gains all of the features of that class.
@@ -12,12 +12,162 @@ array directly. This extends the :doc:`File class </libraries/files>` and thus g
1212
:local:
1313
:depth: 2
1414

15-
===============
15+
***********
16+
The Process
17+
***********
18+
19+
Uploading 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+
29+
To demonstrate this process here is brief tutorial. Afterward you'll
30+
find reference information.
31+
32+
Creating the Upload Form
33+
========================
34+
35+
Using a text editor, create a form called upload_form.php. In it, place
36+
this code and save it to your **app/Views/** directory::
37+
38+
<!DOCTYPE html>
39+
<html lang="en">
40+
<head>
41+
<title>Upload Form</title>
42+
</head>
43+
<body>
44+
45+
<?php foreach ($errors as $error): ?>
46+
<li><?= $error ?></li>
47+
<?php endforeach ?>
48+
49+
<?= form_open_multipart('upload/upload') ?>
50+
51+
<input type="file" name="userfile" size="20" />
52+
53+
<br /><br />
54+
55+
<input type="submit" value="upload" />
56+
57+
</form>
58+
59+
</body>
60+
</html>
61+
62+
You'll notice we are using a form helper to create the opening form tag.
63+
File uploads require a multipart form, so the helper creates the proper
64+
syntax for you. You'll also notice we have an ``$errors`` variable. This is
65+
so we can show error messages in the event the user does something
66+
wrong.
67+
68+
The Success Page
69+
================
70+
71+
Using a text editor, create a form called upload_success.php. In it,
72+
place this code and save it to your **app/Views/** directory::
73+
74+
<!DOCTYPE html>
75+
<html lang="en">
76+
<head>
77+
<title>Upload Form</title>
78+
</head>
79+
<body>
80+
81+
<h3>Your file was successfully uploaded!</h3>
82+
83+
<ul>
84+
<li>name: <?= $uploaded_flleinfo->getBasename() ?></li>
85+
<li>size: <?= $uploaded_flleinfo->getSizeByUnit('kb') ?> KB</li>
86+
<li>extension: <?= $uploaded_flleinfo->guessExtension() ?></li>
87+
</ul>
88+
89+
<p><?= anchor('upload', 'Upload Another File!') ?></p>
90+
91+
</body>
92+
</html>
93+
94+
The Controller
95+
==============
96+
97+
Using a text editor, create a controller called Upload.php. In it, place
98+
this code and save it to your **app/Controllers/** directory::
99+
100+
<?php
101+
102+
namespace App\Controllers;
103+
104+
use CodeIgniter\Files\File;
105+
106+
class Upload extends BaseController
107+
{
108+
protected $helpers = ['form'];
109+
110+
public function index()
111+
{
112+
return view('upload_form', ['errors' => []]);
113+
}
114+
115+
public function upload()
116+
{
117+
$validationRule = [
118+
'userfile' => [
119+
'label' => 'Image File',
120+
'rules' => 'uploaded[userfile]'
121+
. '|is_image[userfile]'
122+
. '|mime_in[userfile,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
123+
. '|max_size[userfile,100]'
124+
. '|max_dims[userfile,1024,768]',
125+
],
126+
];
127+
if (! $this->validate($validationRule)) {
128+
$data = ['errors' => $this->validator->getErrors()];
129+
130+
return view('upload_form', $data);
131+
}
132+
133+
$img = $this->request->getFile('userfile');
134+
135+
if (! $img->hasMoved()) {
136+
$filepath = WRITEPATH . 'uploads/' . $img->store();
137+
138+
$data = ['uploaded_flleinfo' => new File($filepath)];
139+
140+
return view('upload_success', $data);
141+
} else {
142+
$data = ['errors' => 'The file has already been moved.'];
143+
144+
return view('upload_form', $data);
145+
}
146+
}
147+
}
148+
149+
The Upload Directory
150+
====================
151+
152+
The uploaded files are stored in the **writable/uploads/** directory.
153+
154+
Try it!
155+
=======
156+
157+
To try your form, visit your site using a URL similar to this one::
158+
159+
example.com/index.php/upload/
160+
161+
You should see an upload form. Try uploading an image file (either a
162+
**jpg**, **gif**, **png**, or **webp**). If the path in your controller is correct it should
163+
work.
164+
165+
***************
16166
Accessing Files
17-
===============
167+
***************
18168

19169
All Files
20-
----------
170+
=========
21171

22172
When you upload files they can be accessed natively in PHP through the ``$_FILES`` superglobal. This array has some
23173
major shortcomings when working with multiple files uploaded at once, and has potential security flaws many developers
@@ -72,7 +222,7 @@ In this case, the returned array of files would be more like::
72222
]
73223

74224
Single File
75-
-----------
225+
===========
76226

77227
If you just need to access a single file, you can use ``getFile()`` to retrieve the file instance directly. This will return an instance of ``CodeIgniter\HTTP\Files\UploadedFile``:
78228

@@ -140,15 +290,15 @@ In controller::
140290

141291
.. note:: Using ``getFiles()`` is more appropriate.
142292

143-
=====================
293+
*********************
144294
Working With the File
145-
=====================
295+
*********************
146296

147297
Once you've retrieved the UploadedFile instance, you can retrieve information about the file in safe ways, as well as
148298
move the file to a new location.
149299

150300
Verify A File
151-
-------------
301+
=============
152302

153303
You can check that a file was actually uploaded via HTTP with no errors by calling the ``isValid()`` method::
154304

@@ -169,7 +319,7 @@ this method:
169319
* File upload was stopped by a PHP extension.
170320

171321
File Names
172-
----------
322+
==========
173323

174324
**getName()**
175325

@@ -192,7 +342,7 @@ To get the full path of the temp file that was created during the upload, you ca
192342
$tempfile = $file->getTempName();
193343

194344
Other File Info
195-
---------------
345+
===============
196346

197347
**getClientExtension()**
198348

@@ -212,7 +362,7 @@ version, use ``getMimeType()`` instead::
212362
echo $type; // image/png
213363

214364
Moving Files
215-
------------
365+
============
216366

217367
Each file can be moved to its new location with the aptly named ``move()`` method. This takes the directory to move
218368
the file to as the first parameter::
@@ -238,7 +388,7 @@ Moving an uploaded file can fail, with an HTTPException, under several circumsta
238388
- the file move operation fails (e.g., improper permissions)
239389

240390
Store Files
241-
------------
391+
===========
242392

243393
Each file can be moved to its new location with the aptly named ``store()`` method.
244394

0 commit comments

Comments
 (0)