File Uploading in CodeIgniter 4 Tutorial
In this tutorial, you will learn how the Simple Way of Uploading Files using PHP CodeIgniter. CodeIgniter is one of the popular PHP frameworks that make the developer jobs easier. The goal of this tutorial is to provide the new programmers, especially those who are new to CodeIgniter Framework an Idea of how to upload files. Here, I will be providing a simple application source code that demonstrates our goal for the tutorial.
Getting Started
Before we continue to the coding part, kindly download the following so you could also run the demo application on your end.
- XAMPP
- This is a virtual server that allows your local machine to run our PHP Scripts. You can also use other similar software.
- CodeIgniter
- Since this tutorial uses the CodeIgniter Framework, you must download it.
The demo application source code I will be providing only uses CDNs for loading the Bootstrap Framework Dependencies. Bootstrap Framework is a CSS (Cascading Style Sheet) that helps the developer to build an application with a good and pleasant user design or user interface to give end-users a better experience while using the application. You must connect to the internet so the CDNs will work and so the system design.
Creating the Database
- Open your XAMPP's Control Panel and start the Apache and the MySQL Server.
- Open a new tab on your browser and browse http://localhost/phpmyadmin.
- Create a new database naming "file_upload_db"
- Then, navigate your page to the SQL page and copy/paste the MySQL Script below. The script will create a new table in your database with the columns needed on the app.
- CREATE TABLE `files` ( `id` int(30) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, `label` varchar(250) NOT NULL, `path` text DEFAULT NULL, `created_at` datetime DEFAULT current_timestamp(), `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The database will serve as the storage of the file details that the users will upload to the application.
App Configuration
Open the App >> Config >> App.php file in your text editor and configure it the same as the script below. In my case, I named my source code folder as ci4_file_upload which you can find in the $baseURL variable. The script below is not the full script of this file. It only shows the part where changes need to be done on your end for this tutorial.
- <?php
- namespace Config;
- use CodeIgniter\Config\BaseConfig;
- use CodeIgniter\Session\Handlers\FileHandler;
- class App extends BaseConfig
- {
- /**
- * --------------------------------------------------------------------------
- * Base Site URL
- * --------------------------------------------------------------------------
- *
- * URL to your CodeIgniter root. Typically this will be your base URL,
- * WITH a trailing slash:
- *
- * http://example.com/
- *
- * If this is not set then CodeIgniter will try guess the protocol, domain
- * and path to your installation. However, you should always configure this
- * explicitly and never rely on auto-guessing, especially in production
- * environments.
- *
- * @var string
- */
- public $baseURL = 'http://localhost/ci4_file_upload/public/';
- /**
- * --------------------------------------------------------------------------
- * Index File
- * --------------------------------------------------------------------------
- *
- * Typically this will be your index.php file unless you've renamed it to
- * something else. If you are using mod_rewrite to remove the page set this
- * variable so that it is blank.
- *
- * @var string
- */
- public $indexPage = '';
Configuring the Route
On your App >> Config directory, you will find a PHP file named Routes.php. Open the file on your text editor and configure it like the script below. This will allow us to browse the part or pages on the application using the specific segments or URLs.
- <?php
- namespace Config;
- // Create a new instance of our RouteCollection class.
- $routes = Services::routes();
- // Load the system's routing file first, so that the app and ENVIRONMENT
- // can override as needed.
- require SYSTEMPATH . 'Config/Routes.php';
- }
- /*
- * --------------------------------------------------------------------
- * Router Setup
- * --------------------------------------------------------------------
- */
- $routes->setDefaultNamespace('App\Controllers');
- $routes->setDefaultController('Main');
- $routes->setDefaultMethod('index');
- $routes->setTranslateURIDashes(false);
- $routes->set404Override();
- // The Auto Routing (Legacy) is very dangerous. It is easy to create vulnerable apps
- // where controller filters or CSRF protection are bypassed.
- // If you don't want to define all routes, please use the Auto Routing (Improved).
- // Set `$autoRoutesImproved` to true in `app/Config/Feature.php` and set the following to true.
- //$routes->setAutoRoute(false);
- /*
- * --------------------------------------------------------------------
- * Route Definitions
- * --------------------------------------------------------------------
- */
- // We get a performance increase by specifying the default
- // route since we don't have to scan directories.
- $routes->get('/', 'Main::index');
- $routes->post('file/upload', 'Main::upload');
- /*
- * --------------------------------------------------------------------
- * Additional Routing
- * --------------------------------------------------------------------
- *
- * There will often be times that you need additional routing and you
- * need it to be able to override any defaults in this file. Environment
- * based routes is one such time. require() additional route files here
- * to make that happen.
- *
- * You will have access to the $routes object within that file without
- * needing to reload it.
- */
- require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
- }
Creating the Model
On your App >> models directory, create a new PHP file named File.php. This file contains the script and variables for our application to manage data in our database file_upload table. Write the following script below and save the file.
- <?php
- namespace App\Models;
- use CodeIgniter\Model;
- {
- protected $DBGroup = 'default';
- protected $table = 'files';
- protected $primaryKey = 'id';
- protected $useAutoIncrement = true;
- protected $insertID = 0;
- protected $returnType = 'array';
- protected $useSoftDeletes = false;
- protected $protectFields = true;
- protected $allowedFields = ['label','path'];
- // Dates
- protected $useTimestamps = false;
- protected $dateFormat = 'datetime';
- protected $createdField = 'created_at';
- protected $updatedField = 'updated_at';
- protected $deletedField = 'deleted_at';
- // Validation
- protected $validationRules = [];
- protected $validationMessages = [];
- protected $skipValidation = false;
- protected $cleanValidationRules = true;
- // Callbacks
- protected $allowCallbacks = true;
- protected $beforeInsert = [];
- protected $afterInsert = [];
- protected $beforeUpdate = [];
- protected $afterUpdate = [];
- protected $beforeFind = [];
- protected $afterFind = [];
- protected $beforeDelete = [];
- protected $afterDelete = [];
- }
Creating the Controller
On your App >> Controllers directory, create a new PHP file naming Main.php. This file contains the PHP codes that display our pages and process our uploaded data. Write the following script on your end too.
- <?php
- namespace App\Controllers;
- use App\Controllers\BaseController;
- class Main extends BaseController
- {
- public function __construct(){
- $this->db = db_connect();
- $this->session = session();
- $this->request = \Config\Services::request();
- $this->data['session']= $this->session ;
- $this->data['request'] = $this->request ;
- $this->data['uploads']= $this->model->findAll();
- }
- public function index(){
- return view('home', $this->data);
- }
- public function upload(){
- $label = $this->request->getPost('label');
- $file = $this->request->getFile('file');
- $fname = $file->getRandomName();
- while(true){
- $check = $this->model->where("path", "uploads/{$fname}")->countAllResults();
- if($check > 0){
- $fname = $file->getRandomName();
- }else{
- break;
- }
- }
- if($file->move("uploads/", $fname)){
- $this->model->save([
- "label" =>$this->db->escapeString($label),
- "path" => "uploads/".$fname
- ]);
- $this->session->setFlashdata('main_success',"New File Uploaded successfully.");
- return redirect()->to('/');
- }else{
- $this->session->setFlashdata('main_success',"File Upload failed.");
- }
- return view('home', $this->data);
- }
- }
Creating the View
Lastly, create a new file naming home.php on your App >> Views directory. This file contains the HTML and PHP Scripts of our application interface. The script contains included CDNs, our form panel elements, and the display panel for the list of uploaded files.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <!-- Font Awesome -->
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- <!-- Bootstrap -->
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
- <!-- Font Awesome -->
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
- <style>
- html, body{
- height:100%;
- width:100%;
- }
- </style>
- </head>
- <body class="bg-dark bg-gradient bg-opacity-25">
- <div class="container py-4">
- <hr>
- <?php if($session->getFlashdata('main_error')): ?>
- <div class="alert alert-danger rounded-0">
- <?= $session->getFlashdata('main_error') ?>
- </div>
- <?php endif; ?>
- <?php if($session->getFlashdata('main_success')): ?>
- <div class="alert alert-success rounded-0">
- <?= $session->getFlashdata('main_success') ?>
- </div>
- <?php endif; ?>
- <div class="row">
- <div class="col-lg-4 col-md-6 col-sm-12 col-xs-12">
- <div class="card rounded-0 shadow">
- <div class="card-header">
- </div>
- <div class="card-body">
- <div class="container-fluid">
- <form action="<?= base_url('file/upload') ?>" method="POST" id="file-upload" enctype="multipart/form-data">
- <div class="mb-3">
- <input type="text" name="label" id="label" class="form-control rounded-0">
- </div>
- <div class="mb-3">
- <input class="form-control rounded-0" name="file" type="file" id="formFile">
- </div>
- </form>
- </div>
- </div>
- <div class="card-footer text-center">
- </div>
- </div>
- </div>
- <div class="col-lg-8 col-md-6 col-sm-12 col-xs-12">
- <div class="card rounded-0 shadow">
- <div class="card-header">
- </div>
- <div class="card-body">
- <div class="container-fluid">
- <table class="table table-striped table-bordered">
- <colgroup>
- <col width="10%">
- <col width="20%">
- <col width="50%">
- <col width="20%">
- </colgroup>
- <thead>
- <tr class="bg-primary bg-gradient text-light">
- </tr>
- </thead>
- <tbody>
- <?php
- $i = 1;
- foreach($uploads as $row):
- $row['fname'] = str_replace("uploads/","", $row['path']);
- ?>
- <tr>
- <td class="px-2 py-1 align-middle text-center">
- </td>
- </tr>
- <?php endforeach; ?>
- <?php if(!isset($uploads) || (isset($uploads) && count($uploads) <= 0)): ?>
- <tr>
- </tr>
- <?php endif; ?>
- </tbody>
- </table>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
That's it! You can now test the application on your end. To do that, browse http://localhost/[source_code_folder_name]/public/ in your browser. Check the application if it works and achieves our goal for this tutorial.
DEMO VIDEO
If in any case you'll find or encounter any errors on your end, please review your source code maybe you have missed something or you can also download the working source code I created for this tutorial. The download link is located below this article.
That's the end of this tutorial. I hope this tutorial will help you with what you are looking for and you'll find this useful for your current or future CodeIgniter Project. Explore more on this website for more tutorials and Free Source Codes.
Happy Coding :)
Comments
Add new comment
- Add new comment
- 2827 views