1. Enable CSRF

  • Open .env file.
  • Remove ## from the start of the app.CSRFProtection, app.CSRFTokenNameapp.CSRFCookieNameapp.CSRFExpire, and app.CSRFRegenerate.
  • I update the app.CSRFTokenName value with 'csrf_hash_name'. With this name read CSRF hash. You can update it with any other value.
app.CSRFProtection = true
app.CSRFTokenName = 'csrf_hash_name'
app.CSRFCookieName = 'csrf_cookie_name'
app.CSRFExpire = 7200
app.CSRFRegenerate = true
## app.CSRFExcludeURIs = []
  • Open app/Config/Filters.php file.
  • Uncomment in 'csrf' in 'before' if commented.
// Always applied before every request
public $globals = [
    'before' => [
       //'honeypot'
       'csrf',
    ],
    'after' => [
       'toolbar',
       //'honeypot'
    ],
];

2. Route

  • Open app/Config/Routes.php file.
  • Define 2 routes –
  • / – Display file upload view.
  • users/fileUpload – It is used to upload a file.

Completed Code

$routes->get('/', 'UsersController::index');
$routes->post('users/fileUpload', 'UsersController::fileUpload');

3. Controller

  • Create UsersController.php file in app/Controllers/ folder.
  • Open the file.
  • Create 2 methods –
  • index() – Load users view.
  • fileUpload() – This method is called on form submit to upload the file.

Set file validation –

'file' => 'uploaded[file]|max_size[file,1024]|ext_in[file,jpg,jpeg,docx,pdf],'
  1. uploaded – Fails if the name of the parameter does not match the name of any uploaded files.
  2. max_size – Set maximum file upload size in kb.
  3. ext_in – Valid file extensions – jpg, jpeg, docx, pdf.

Here, the 1st parameter is the name of the input field. In the example, it is ‘file’.

For example, If the input field name is ‘imagefile’ then validation is like this – 'uploaded[imagefile]|max_size[imagefile,1024]|ext_in[imagefile,jpg,jpeg],'.

NOTE – You can learn more file validation from here.

If the file is not validated then return to the users view with validation response.

If the file is validated then get the file name and extension. I used $file->getRandomName() to generate a random name but you can create any other meaningful name and assign it to $newName.

I am storing files in the public/uploads folder using move() method. 1st parameter is the file upload path and 2nd parameter is the name.

Assign file path to $filepath variable for preview. Using SESSION flash to display "Uploaded Successfully!" message and file preview.

Redirect to "/" route.

Completed Code

<?php namespace App\Controllers;

class UsersController extends BaseController
{

   public function index(){
     return view('users');
   }

   public function fileUpload(){

     // Validation
     $input = $this->validate([
        'file' => 'uploaded[file]|max_size[file,1024]|ext_in[file,jpg,jpeg,docx,pdf],'
     ]);

     if (!$input) { // Not valid
         $data['validation'] = $this->validator; 
         return view('users',$data); 
     }else{ // Valid

         if($file = $this->request->getFile('file')) {
            if ($file->isValid() && ! $file->hasMoved()) {
               // Get file name and extension
               $name = $file->getName();
               $ext = $file->getClientExtension();

               // Get random file name
               $newName = $file->getRandomName(); 

               // Store file in public/uploads/ folder
               $file->move('../public/uploads', $newName);

               // File path to display preview
               $filepath = base_url()."/uploads/".$newName;

               // Set Session
               session()->setFlashdata('message', 'Uploaded Successfully!');
               session()->setFlashdata('alert-class', 'alert-success');
               session()->setFlashdata('filepath', $filepath);
               session()->setFlashdata('extension', $ext);

            }else{
               // Set Session
               session()->setFlashdata('message', 'File not uploaded.');
               session()->setFlashdata('alert-class', 'alert-danger');

            }
         }

     }

     return redirect()->route('/'); 
   }

}

#codeigniter 4 #php

How to upload an Image file and Display preview in CodeIgniter 4
34.20 GEEK