Overview
Working with files in CodeIgniter is much simpler and more secure than PHP’s $_FILES
.
In this example, I am going to show you how to upload a file using the CodeIgniter 4 framework PHP.
Here, we are using 2 files for uploading a file:
Controller: Document.php app\Controllers\Document.php
View: upload_file.php app\Views\upload_file.php
app/Config/Routes.php
$routes->add('document/', 'Document::upload_form');
$routes->post('document/upload', 'Document::upload');
app/Views/upload_file.php
<?php
$attr = 'class="form-horizontal" id="add_client_form" autocomplete="off"';
echo form_open_multipart("document/upload", $attr);
?>
<div class="form-group">
<label class="col-sm-2 control-label">File</label>
<div class="col-md-4">
<input type="file" id="file" name="file">
<p class="help-block">Allowed types (.jpg, .png, .gif, .pdf)</p>
</div>
<div class="col-md-6"></div>
</div>
app/Controllers/Document.php
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
class Document extends BaseController {
public function __construct() {
helper(['url', 'form', 'array']);
}
public function upload_form() {
echo view("upload_file");
}
public function upload() {
$path = 'uploads/';
$file = $this->request->getFile('file');
$upload_file = $this->uploadFile($path, $file);
if($upload_file)
echo "File uploaded successfully @ ".$upload_file;
}
public function uploadFile($path, $image) {
if ($image->isValid() && ! $image->hasMoved()) {
$newName = $image->getRandomName();
$image->move('./'.$path, $newName);
return $path.$image->getName();
}
return "";
}
}