From c9c8748770a062f59d6b54ff68b960400b0d4ced Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 10:46:19 +0900 Subject: [PATCH 01/10] docs: fix coding style of sample code --- user_guide_src/source/libraries/uploaded_files.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/user_guide_src/source/libraries/uploaded_files.rst b/user_guide_src/source/libraries/uploaded_files.rst index 094eacc1eafa..c0284f221d79 100644 --- a/user_guide_src/source/libraries/uploaded_files.rst +++ b/user_guide_src/source/libraries/uploaded_files.rst @@ -110,7 +110,7 @@ In controller:: foreach($imagefile['images'] as $img) { if ($img->isValid() && ! $img->hasMoved()) { $newName = $img->getRandomName(); - $img->move(WRITEPATH.'uploads', $newName); + $img->move(WRITEPATH . 'uploads', $newName); } } } @@ -153,7 +153,7 @@ Verify A File You can check that a file was actually uploaded via HTTP with no errors by calling the ``isValid()`` method:: if (! $file->isValid()) { - throw new \RuntimeException($file->getErrorString().'('.$file->getError().')'); + throw new \RuntimeException($file->getErrorString() . '(' . $file->getError() . ')'); } As seen in this example, if a file had an upload error, you can retrieve the error code (an integer) and the error @@ -216,12 +216,12 @@ Moving Files Each file can be moved to its new location with the aptly named ``move()`` method. This takes the directory to move the file to as the first parameter:: - $file->move(WRITEPATH.'uploads'); + $file->move(WRITEPATH . 'uploads'); By default, the original filename was used. You can specify a new filename by passing it as the second parameter:: $newName = $file->getRandomName(); - $file->move(WRITEPATH.'uploads', $newName); + $file->move(WRITEPATH . 'uploads', $newName); Once the file has been removed the temporary file is deleted. You can check if a file has been moved already with the ``hasMoved()`` method, which returns a boolean:: From 7422d99f97507a01af43a010baa0cbf2863d2de5 Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 10:46:49 +0900 Subject: [PATCH 02/10] docs: fix typo --- user_guide_src/source/libraries/uploaded_files.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/user_guide_src/source/libraries/uploaded_files.rst b/user_guide_src/source/libraries/uploaded_files.rst index c0284f221d79..b15185506e81 100644 --- a/user_guide_src/source/libraries/uploaded_files.rst +++ b/user_guide_src/source/libraries/uploaded_files.rst @@ -117,7 +117,7 @@ In controller:: where the **images** is a loop from the form field name -If there are multiple files with the same name you can use ``getFile()`` ro retrieve every file individually:: +If there are multiple files with the same name you can use ``getFile()`` to retrieve every file individually:: In controller:: $file1 = $this->request->getFile('images.0'); From 34340569a9866f3d52cb1338eff0b6afd01f4f1b Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 10:47:24 +0900 Subject: [PATCH 03/10] docs: decorate words in code with '``' --- user_guide_src/source/libraries/uploaded_files.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/user_guide_src/source/libraries/uploaded_files.rst b/user_guide_src/source/libraries/uploaded_files.rst index b15185506e81..c0e4b27baf9a 100644 --- a/user_guide_src/source/libraries/uploaded_files.rst +++ b/user_guide_src/source/libraries/uploaded_files.rst @@ -160,7 +160,7 @@ As seen in this example, if a file had an upload error, you can retrieve the err message with the ``getError()`` and ``getErrorString()`` methods. The following errors can be discovered through this method: -* The file exceeds your upload_max_filesize ini directive. +* The file exceeds your ``upload_max_filesize`` ini directive. * The file exceeds the upload limit defined in your form. * The file was only partially uploaded. * No file was uploaded. @@ -255,7 +255,7 @@ passing it as the second parameter:: $path = $this->request->getFile('userfile')->store('head_img/', 'user_name.jpg'); -Moving an uploaded file can fail, with an HTTPException, under several circumstances: +Moving an uploaded file can fail, with an ``HTTPException``, under several circumstances: - the file has already been moved - the file did not upload successfully From a177ea33d1d8c70869053168d85afdc88ad2ac6e Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 10:48:41 +0900 Subject: [PATCH 04/10] docs: make it a single sentence --- user_guide_src/source/libraries/uploaded_files.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/user_guide_src/source/libraries/uploaded_files.rst b/user_guide_src/source/libraries/uploaded_files.rst index c0e4b27baf9a..d48bc02a9dcb 100644 --- a/user_guide_src/source/libraries/uploaded_files.rst +++ b/user_guide_src/source/libraries/uploaded_files.rst @@ -138,7 +138,7 @@ In controller:: $file1 = $this->request->getFile('my-form.details.avatars.0'); $file2 = $this->request->getFile('my-form.details.avatars.1'); -.. note:: using ``getFiles()`` is more appropriate +.. note:: Using ``getFiles()`` is more appropriate. ===================== Working With the File From 80689ddc4cb3b72179f9cee57ef12ec619b3e13d Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 10:49:22 +0900 Subject: [PATCH 05/10] docs: decroate file paths with ** --- user_guide_src/source/libraries/uploaded_files.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/user_guide_src/source/libraries/uploaded_files.rst b/user_guide_src/source/libraries/uploaded_files.rst index d48bc02a9dcb..e1734165c6e5 100644 --- a/user_guide_src/source/libraries/uploaded_files.rst +++ b/user_guide_src/source/libraries/uploaded_files.rst @@ -245,7 +245,7 @@ With the simplest usage, a single file might be submitted like:: -By default, upload files are saved in writable/uploads directory. The YYYYMMDD folder +By default, upload files are saved in **writable/uploads** directory. The **YYYYMMDD** folder and random file name will be created. Returns a file path:: $path = $this->request->getFile('userfile')->store(); From 49a07f0ccb46e313e08b8cb6c53de00e0df537e3 Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 10:49:48 +0900 Subject: [PATCH 06/10] docs: make warning for security matter --- user_guide_src/source/libraries/uploaded_files.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/user_guide_src/source/libraries/uploaded_files.rst b/user_guide_src/source/libraries/uploaded_files.rst index e1734165c6e5..d4ecc9d34867 100644 --- a/user_guide_src/source/libraries/uploaded_files.rst +++ b/user_guide_src/source/libraries/uploaded_files.rst @@ -196,11 +196,12 @@ Other File Info **getClientExtension()** -Returns the original file extension, based on the file name that was uploaded. This is NOT a trusted source. For a -trusted version, use ``guessExtension()`` instead:: +Returns the original file extension, based on the file name that was uploaded:: $ext = $file->getClientExtension(); +.. warning:: This is NOT a trusted source. For a trusted version, use ``guessExtension()`` instead. + **getClientMimeType()** Returns the mime type (mime type) of the file as provided by the client. This is NOT a trusted value. For a trusted From 352a67166ad6e592c70c17c64626e41e075ccad0 Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 12:13:47 +0900 Subject: [PATCH 07/10] docs: add file upload sample code like CI3 --- .../source/libraries/uploaded_files.rst | 176 ++++++++++++++++-- 1 file changed, 163 insertions(+), 13 deletions(-) diff --git a/user_guide_src/source/libraries/uploaded_files.rst b/user_guide_src/source/libraries/uploaded_files.rst index d4ecc9d34867..1f60167f9189 100644 --- a/user_guide_src/source/libraries/uploaded_files.rst +++ b/user_guide_src/source/libraries/uploaded_files.rst @@ -1,6 +1,6 @@ -*************************** +########################### Working with Uploaded Files -*************************** +########################### CodeIgniter makes working with files uploaded through a form much simpler and more secure than using PHP's ``$_FILES`` array directly. This extends the :doc:`File class ` and thus gains all of the features of that class. @@ -12,12 +12,162 @@ array directly. This extends the :doc:`File class ` and thus g :local: :depth: 2 -=============== +*********** +The Process +*********** + +Uploading a file involves the following general process: + +- An upload form is displayed, allowing a user to select a file and + upload it. +- When the form is submitted, the file is uploaded to the destination + you specify. +- Along the way, the file is validated to make sure it is allowed to be + uploaded based on the preferences you set. +- Once uploaded, the user will be shown a success message. + +To demonstrate this process here is brief tutorial. Afterward you'll +find reference information. + +Creating the Upload Form +======================== + +Using a text editor, create a form called upload_form.php. In it, place +this code and save it to your **app/Views/** directory:: + + + + + Upload Form + + + + +
  • + + + + + + +

    + + + + + + + + +You'll notice we are using a form helper to create the opening form tag. +File uploads require a multipart form, so the helper creates the proper +syntax for you. You'll also notice we have an ``$errors`` variable. This is +so we can show error messages in the event the user does something +wrong. + +The Success Page +================ + +Using a text editor, create a form called upload_success.php. In it, +place this code and save it to your **app/Views/** directory:: + + + + + Upload Form + + + +

    Your file was successfully uploaded!

    + +
      +
    • name: getBasename() ?>
    • +
    • size: getSizeByUnit('kb') ?> KB
    • +
    • extension: guessExtension() ?>
    • +
    + +

    + + + + +The Controller +============== + +Using a text editor, create a controller called Upload.php. In it, place +this code and save it to your **app/Controllers/** directory:: + + []]); + } + + public function upload() + { + $validationRule = [ + 'userfile' => [ + 'label' => 'Image File', + 'rules' => 'uploaded[userfile]' + . '|is_image[userfile]' + . '|mime_in[userfile,image/jpg,image/jpeg,image/gif,image/png,image/webp]' + . '|max_size[userfile,100]' + . '|max_dims[userfile,1024,768]', + ], + ]; + if (! $this->validate($validationRule)) { + $data = ['errors' => $this->validator->getErrors()]; + + return view('upload_form', $data); + } + + $img = $this->request->getFile('userfile'); + + if (! $img->hasMoved()) { + $filepath = WRITEPATH . 'uploads/' . $img->store(); + + $data = ['uploaded_flleinfo' => new File($filepath)]; + + return view('upload_success', $data); + } else { + $data = ['errors' => 'The file has already been moved.']; + + return view('upload_form', $data); + } + } + } + +The Upload Directory +==================== + +The uploaded files are stored in the **writable/uploads/** directory. + +Try it! +======= + +To try your form, visit your site using a URL similar to this one:: + + example.com/index.php/upload/ + +You should see an upload form. Try uploading an image file (either a +**jpg**, **gif**, **png**, or **webp**). If the path in your controller is correct it should +work. + +*************** Accessing Files -=============== +*************** All Files ----------- +========= When you upload files they can be accessed natively in PHP through the ``$_FILES`` superglobal. This array has some 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:: ] Single File ------------ +=========== 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``: @@ -140,15 +290,15 @@ In controller:: .. note:: Using ``getFiles()`` is more appropriate. -===================== +********************* Working With the File -===================== +********************* Once you've retrieved the UploadedFile instance, you can retrieve information about the file in safe ways, as well as move the file to a new location. Verify A File -------------- +============= You can check that a file was actually uploaded via HTTP with no errors by calling the ``isValid()`` method:: @@ -169,7 +319,7 @@ this method: * File upload was stopped by a PHP extension. File Names ----------- +========== **getName()** @@ -192,7 +342,7 @@ To get the full path of the temp file that was created during the upload, you ca $tempfile = $file->getTempName(); Other File Info ---------------- +=============== **getClientExtension()** @@ -212,7 +362,7 @@ version, use ``getMimeType()`` instead:: echo $type; // image/png Moving Files ------------- +============ Each file can be moved to its new location with the aptly named ``move()`` method. This takes the directory to move the file to as the first parameter:: @@ -238,7 +388,7 @@ Moving an uploaded file can fail, with an HTTPException, under several circumsta - the file move operation fails (e.g., improper permissions) Store Files ------------- +=========== Each file can be moved to its new location with the aptly named ``store()`` method. From fbabefa946ae4899e90e9c0b0a92eca49861fb9f Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 13:51:27 +0900 Subject: [PATCH 08/10] docs: add esc() to views --- user_guide_src/source/libraries/uploaded_files.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/user_guide_src/source/libraries/uploaded_files.rst b/user_guide_src/source/libraries/uploaded_files.rst index 1f60167f9189..961823036e60 100644 --- a/user_guide_src/source/libraries/uploaded_files.rst +++ b/user_guide_src/source/libraries/uploaded_files.rst @@ -43,7 +43,7 @@ this code and save it to your **app/Views/** directory:: -
  • +
  • @@ -81,9 +81,9 @@ place this code and save it to your **app/Views/** directory::

    Your file was successfully uploaded!

      -
    • name: getBasename() ?>
    • -
    • size: getSizeByUnit('kb') ?> KB
    • -
    • extension: guessExtension() ?>
    • +
    • name: getBasename()) ?>
    • +
    • size: getSizeByUnit('kb')) ?> KB
    • +
    • extension: guessExtension()) ?>

    From 3839795e6cd65c5440a5bc197fc20f69198f3099 Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 19:03:12 +0900 Subject: [PATCH 09/10] docs: decorate variable with '``' --- user_guide_src/source/libraries/validation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/user_guide_src/source/libraries/validation.rst b/user_guide_src/source/libraries/validation.rst index 27691f084a55..3550bec9ff9d 100644 --- a/user_guide_src/source/libraries/validation.rst +++ b/user_guide_src/source/libraries/validation.rst @@ -896,7 +896,7 @@ Rules for File Uploads ====================== These validation rules enable you to do the basic checks you might need to verify that uploaded files meet your business needs. -Since the value of a file upload HTML field doesn't exist, and is stored in the $_FILES global, the name of the input field will +Since the value of a file upload HTML field doesn't exist, and is stored in the ``$_FILES`` global, the name of the input field will need to be used twice. Once to specify the field name as you would for any other rule, but again as the first parameter of all file upload related rules:: From 0daf8c90166f35230216bb878343f8931444ad7a Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 30 Nov 2021 19:03:50 +0900 Subject: [PATCH 10/10] docs: add note about Validation rules --- user_guide_src/source/libraries/uploaded_files.rst | 4 ++++ user_guide_src/source/libraries/validation.rst | 2 ++ 2 files changed, 6 insertions(+) diff --git a/user_guide_src/source/libraries/uploaded_files.rst b/user_guide_src/source/libraries/uploaded_files.rst index 961823036e60..615716ea0273 100644 --- a/user_guide_src/source/libraries/uploaded_files.rst +++ b/user_guide_src/source/libraries/uploaded_files.rst @@ -146,6 +146,10 @@ this code and save it to your **app/Controllers/** directory:: } } +.. note:: Since the value of a file upload HTML field doesn't exist, and is stored in the ``$_FILES`` global, + only :ref:`rules-for-file-uploads` can be used to validate upload file with :doc:`validation`. + The rule ``required`` also can't be used, so use ``uploaded`` instead. + The Upload Directory ==================== diff --git a/user_guide_src/source/libraries/validation.rst b/user_guide_src/source/libraries/validation.rst index 3550bec9ff9d..aed337d1b062 100644 --- a/user_guide_src/source/libraries/validation.rst +++ b/user_guide_src/source/libraries/validation.rst @@ -892,6 +892,8 @@ valid_cc_number Yes Verifies that the credit card number matches HSBC Canada Card (hsbc) ======================= ========== ============================================= =================================================== +.. _rules-for-file-uploads: + Rules for File Uploads ======================