CodeIgniter makes working with files uploaded through a form much simpler and more secure than using PHP’s $_FILES array directly. This extends the File class and thus gains all of the features of that class. It provides a raw interface to the uploaded files with a few small features.
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.
1. Copy and Paste the following lines in app/Config/Routes.php
$routes->add('document/', 'Document::upload_form');
$routes->post('document/upload', 'Document::upload');2. Create an upload_file.php file in the app/Views/ directory
<?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>3. Create a controller file Document.php in the app/Controllers/ directory.
<?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 "";
}
}