• We just launched and are currently in beta. Join us as we build and grow the community.

File Uploading in CodeIgniter 4 Tutorial

redw1ne

Whimsical Wizard
R Rep
0
0
0
Rep
0
R Vouches
0
0
0
Vouches
0
Posts
84
Likes
95
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
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

  1. Open your XAMPP's Control Panel and start the Apache and the MySQL Server.
  2. Open a new tab on your browser and browse .
  3. Create a new database naming "file_upload_db"
  4. 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.


  1. 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.


  1. <?php

  2. namespace

    Config;

  3. use

    CodeIgniter\Config\BaseConfig;
  4. use

    CodeIgniter\Session\Handlers\FileHandler;

  5. class

    App extends

    BaseConfig
  6. {
  7. /**
  8. * --------------------------------------------------------------------------
  9. * Base Site URL
  10. * --------------------------------------------------------------------------
  11. *
  12. * URL to your CodeIgniter root. Typically this will be your base URL,
  13. * WITH a trailing slash:
  14. *
  15. * http://example.com/
  16. *
  17. * If this is not set then CodeIgniter will try guess the protocol, domain
  18. * and path to your installation. However, you should always configure this
  19. * explicitly and never rely on auto-guessing, especially in production
  20. * environments.
  21. *
  22. * @var string
  23. */
  24. public

    $baseURL

    =

    'http://localhost/ci4_file_upload/public/'

    ;

  25. /**
  26. * --------------------------------------------------------------------------
  27. * Index File
  28. * --------------------------------------------------------------------------
  29. *
  30. * Typically this will be your index.php file unless you've renamed it to
  31. * something else. If you are using mod_rewrite to remove the page set this
  32. * variable so that it is blank.
  33. *
  34. * @var string
  35. */
  36. 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.


  1. <?php

  2. namespace

    Config;

  3. // Create a new instance of our RouteCollection class.
  4. $routes

    =

    Services::

    routes

    (

    )

    ;

  5. // Load the system's routing file first, so that the app and ENVIRONMENT
  6. // can override as needed.
  7. if

    (

    is_file

    (

    SYSTEMPATH .

    'Config/Routes.php'

    )

    )

    {
  8. require

    SYSTEMPATH .

    'Config/Routes.php'

    ;
  9. }

  10. /*
  11. * --------------------------------------------------------------------
  12. * Router Setup
  13. * --------------------------------------------------------------------
  14. */
  15. $routes

    ->

    setDefaultNamespace

    (

    'App\Controllers'

    )

    ;
  16. $routes

    ->

    setDefaultController

    (

    'Main'

    )

    ;
  17. $routes

    ->

    setDefaultMethod

    (

    'index'

    )

    ;
  18. $routes

    ->

    setTranslateURIDashes

    (

    false

    )

    ;
  19. $routes

    ->

    set404Override

    (

    )

    ;
  20. // The Auto Routing (Legacy) is very dangerous. It is easy to create vulnerable apps
  21. // where controller filters or CSRF protection are bypassed.
  22. // If you don't want to define all routes, please use the Auto Routing (Improved).
  23. // Set `$autoRoutesImproved` to true in `app/Config/Feature.php` and set the following to true.
  24. //$routes->setAutoRoute(false);

  25. /*
  26. * --------------------------------------------------------------------
  27. * Route Definitions
  28. * --------------------------------------------------------------------
  29. */

  30. // We get a performance increase by specifying the default
  31. // route since we don't have to scan directories.
  32. $routes

    ->

    get

    (

    '/'

    ,

    'Main::index'

    )

    ;
  33. $routes

    ->

    post

    (

    'file/upload'

    ,

    'Main::upload'

    )

    ;

  34. /*
  35. * --------------------------------------------------------------------
  36. * Additional Routing
  37. * --------------------------------------------------------------------
  38. *
  39. * There will often be times that you need additional routing and you
  40. * need it to be able to override any defaults in this file. Environment
  41. * based routes is one such time. require() additional route files here
  42. * to make that happen.
  43. *
  44. * You will have access to the $routes object within that file without
  45. * needing to reload it.
  46. */
  47. if

    (

    is_file

    (

    APPPATH .

    'Config/'

    .

    ENVIRONMENT .

    '/Routes.php'

    )

    )

    {
  48. require

    APPPATH .

    'Config/'

    .

    ENVIRONMENT .

    '/Routes.php'

    ;
  49. }

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.

  1. <?php

  2. namespace

    App\Models;

  3. use

    CodeIgniter\Model;

  4. class

    File

    extends

    Model
  5. {
  6. protected

    $DBGroup

    =

    'default'

    ;
  7. protected

    $table

    =

    'files'

    ;
  8. protected

    $primaryKey

    =

    'id'

    ;
  9. protected

    $useAutoIncrement

    =

    true

    ;
  10. protected

    $insertID

    =

    0

    ;
  11. protected

    $returnType

    =

    'array'

    ;
  12. protected

    $useSoftDeletes

    =

    false

    ;
  13. protected

    $protectFields

    =

    true

    ;
  14. protected

    $allowedFields

    =

    [

    'label'

    ,

    'path'

    ]

    ;

  15. // Dates
  16. protected

    $useTimestamps

    =

    false

    ;
  17. protected

    $dateFormat

    =

    'datetime'

    ;
  18. protected

    $createdField

    =

    'created_at'

    ;
  19. protected

    $updatedField

    =

    'updated_at'

    ;
  20. protected

    $deletedField

    =

    'deleted_at'

    ;

  21. // Validation
  22. protected

    $validationRules

    =

    [

    ]

    ;
  23. protected

    $validationMessages

    =

    [

    ]

    ;
  24. protected

    $skipValidation

    =

    false

    ;
  25. protected

    $cleanValidationRules

    =

    true

    ;

  26. // Callbacks
  27. protected

    $allowCallbacks

    =

    true

    ;
  28. protected

    $beforeInsert

    =

    [

    ]

    ;
  29. protected

    $afterInsert

    =

    [

    ]

    ;
  30. protected

    $beforeUpdate

    =

    [

    ]

    ;
  31. protected

    $afterUpdate

    =

    [

    ]

    ;
  32. protected

    $beforeFind

    =

    [

    ]

    ;
  33. protected

    $afterFind

    =

    [

    ]

    ;
  34. protected

    $beforeDelete

    =

    [

    ]

    ;
  35. protected

    $afterDelete

    =

    [

    ]

    ;
  36. }

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.

  1. <?php

  2. namespace

    App\Controllers;

  3. use

    App\Controllers\BaseController;
  4. use

    App\Models\File

    ;

  5. class

    Main extends

    BaseController
  6. {
  7. public

    function

    __construct(

    )

    {
  8. $this

    ->

    db

    =

    db_connect(

    )

    ;
  9. $this

    ->

    model

    =

    new

    File

    ;
  10. $this

    ->

    session

    =

    session(

    )

    ;
  11. $this

    ->

    request

    =

    \Config\Services::

    request

    (

    )

    ;
  12. $this

    ->

    data

    [

    'session'

    ]

    =

    $this

    ->

    session

    ;
  13. $this

    ->

    data

    [

    'request'

    ]

    =

    $this

    ->

    request

    ;
  14. $this

    ->

    data

    [

    'uploads'

    ]

    =

    $this

    ->

    model

    ->

    findAll

    (

    )

    ;
  15. }
  16. public

    function

    index(

    )

    {
  17. return

    view(

    'home'

    ,

    $this

    ->

    data

    )

    ;
  18. }

  19. public

    function

    upload(

    )

    {
  20. if

    (

    !

    is_dir

    (

    './uploads/'

    )

    )
  21. mkdir

    (

    './uploads/'

    )

    ;
  22. $label

    =

    $this

    ->

    request

    ->

    getPost

    (

    'label'

    )

    ;
  23. $file

    =

    $this

    ->

    request

    ->

    getFile

    (

    'file'

    )

    ;
  24. $fname

    =

    $file

    ->

    getRandomName

    (

    )

    ;
  25. while

    (

    true

    )

    {
  26. $check

    =

    $this

    ->

    model

    ->

    where

    (

    "path"

    ,

    "uploads/{$fname}

    "

    )

    ->

    countAllResults

    (

    )

    ;
  27. if

    (

    $check

    >

    0

    )

    {
  28. $fname

    =

    $file

    ->

    getRandomName

    (

    )

    ;
  29. }

    else

    {
  30. break

    ;
  31. }
  32. }
  33. if

    (

    $file

    ->

    move

    (

    "uploads/"

    ,

    $fname

    )

    )

    {
  34. $this

    ->

    model

    ->

    save

    (

    [
  35. "label"

    =>

    $this

    ->

    db

    ->

    escapeString

    (

    $label

    )

    ,
  36. "path"

    =>

    "uploads/"

    .

    $fname
  37. ]

    )

    ;
  38. $this

    ->

    session

    ->

    setFlashdata

    (

    'main_success'

    ,

    "New File Uploaded successfully."

    )

    ;
  39. return

    redirect(

    )

    ->

    to

    (

    '/'

    )

    ;
  40. }

    else

    {
  41. $this

    ->

    session

    ->

    setFlashdata

    (

    'main_success'

    ,

    "File Upload failed."

    )

    ;
  42. }
  43. return

    view(

    'home'

    ,

    $this

    ->

    data

    )

    ;
  44. }
  45. }

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.

  1. <!DOCTYPE html>
  2. <html

    lang

    =

    "en"

    >
  3. <head

    >
  4. <meta

    charset

    =

    "UTF-8"

    >
  5. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  6. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  7. <title

    >

    CodeIgniter File Upload</

    title

    >

  8. <!-- Font Awesome -->
  9. <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"

    /

    >
  10. <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"

    /

    >

  11. <!-- Bootstrap -->
  12. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"

    integrity=

    "sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"

    crossorigin=

    "anonymous"

    >

  13. <!-- Font Awesome -->
  14. <script

    src

    =

    "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js"

    integrity=

    "sha512-6PM0qYu5KExuNcKt5bURAoT6KCThUmHRewN3zUFNaoI6Di7XJPTMoT6K0nsagZKk2OB4L7E3q1uQKHNHd4stIQ=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    ></

    script

    >

  15. <script

    src

    =

    "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"

    integrity=

    "sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    ></

    script

    >
  16. <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

    >

  17. <script

    src

    =

    "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"

    integrity=

    "sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    ></

    script

    >

  18. <style

    >
  19. html, body{
  20. height:100%;
  21. width:100%;
  22. }
  23. </

    style

    >
  24. </

    head

    >
  25. <body

    class

    =

    "bg-dark bg-gradient bg-opacity-25"

    >
  26. <div

    class

    =

    "container py-4"

    >
  27. <h1

    class

    =

    "text-center fw-bold"

    >

    File Uploading in CodeIgniter 4</

    h1

    >
  28. <hr

    >
  29. <?php if(

    $session->

    getFlashdata('main_error')): ?>
  30. <div

    class

    =

    "alert alert-danger rounded-0"

    >
  31. <?=

    $session->

    getFlashdata('main_error') ?>
  32. </

    div

    >
  33. <?php endif; ?>
  34. <?php if(

    $session->

    getFlashdata('main_success')): ?>
  35. <div

    class

    =

    "alert alert-success rounded-0"

    >
  36. <?=

    $session->

    getFlashdata('main_success') ?>
  37. </

    div

    >
  38. <?php endif; ?>
  39. <div

    class

    =

    "clear-fix py-2"

    ></

    div

    >
  40. <div

    class

    =

    "row"

    >
  41. <div

    class

    =

    "col-lg-4 col-md-6 col-sm-12 col-xs-12"

    >
  42. <div

    class

    =

    "card rounded-0 shadow"

    >
  43. <div

    class

    =

    "card-header"

    >
  44. <div

    class

    =

    "card-title h4 mb-0 fw-bold"

    >

    Upload File Form</

    div

    >
  45. </

    div

    >
  46. <div

    class

    =

    "card-body"

    >
  47. <div

    class

    =

    "container-fluid"

    >
  48. <form

    action

    =

    "<?= base_url('file/upload') ?>

    " method="POST" id="file-upload" enctype="multipart/form-data">
  49. <div

    class

    =

    "mb-3"

    >
  50. <label

    for

    =

    "label"

    class

    =

    "control-label"

    >

    File Label</

    label

    >
  51. <input

    type

    =

    "text"

    name

    =

    "label"

    id

    =

    "label"

    class

    =

    "form-control rounded-0"

    >
  52. </

    div

    >
  53. <div

    class

    =

    "mb-3"

    >
  54. <label

    for

    =

    "formFile"

    class

    =

    "form-label"

    >

    File</

    label

    >
  55. <input

    class

    =

    "form-control rounded-0"

    name

    =

    "file"

    type

    =

    "file"

    id

    =

    "formFile"

    >
  56. </

    div

    >
  57. </

    form

    >
  58. </

    div

    >
  59. </

    div

    >
  60. <div

    class

    =

    "card-footer text-center"

    >
  61. <button

    class

    =

    "btn btn-primary btn-sm bg-gradient rounded-0"

    form=

    "file-upload"

    ><i

    class

    =

    "fa fa-save"

    ></

    i

    >

    Save File</

    button

    >
  62. <button

    class

    =

    "btn btn-light border btn-sm bg-gradient rounded-0"

    type

    =

    "reset"

    form=

    "file-upload"

    ><i

    class

    =

    "fa fa-times"

    ></

    i

    >

    Reset</

    button

    >
  63. </

    div

    >
  64. </

    div

    >
  65. </

    div

    >
  66. <div

    class

    =

    "col-lg-8 col-md-6 col-sm-12 col-xs-12"

    >
  67. <div

    class

    =

    "card rounded-0 shadow"

    >
  68. <div

    class

    =

    "card-header"

    >
  69. <div

    class

    =

    "card-title h4 mb-0 fw-bolder"

    >

    Uploaded Files</

    div

    >
  70. </

    div

    >
  71. <div

    class

    =

    "card-body"

    >
  72. <div

    class

    =

    "container-fluid"

    >
  73. <table

    class

    =

    "table table-striped table-bordered"

    >
  74. <colgroup

    >
  75. <col

    width

    =

    "10%"

    >
  76. <col

    width

    =

    "20%"

    >
  77. <col

    width

    =

    "50%"

    >
  78. <col

    width

    =

    "20%"

    >
  79. </

    colgroup

    >
  80. <thead

    >
  81. <tr

    class

    =

    "bg-primary bg-gradient text-light"

    >
  82. <th

    class

    =

    "p-1 text-center"

    >

    #</

    th

    >
  83. <th

    class

    =

    "p-1 text-center"

    >

    Label</

    th

    >
  84. <th

    class

    =

    "p-1 text-center"

    >

    Path</

    th

    >
  85. <th

    class

    =

    "p-1 text-center"

    ></

    th

    >
  86. </

    tr

    >
  87. </

    thead

    >
  88. <tbody

    >
  89. <?php
  90. $i =

    1

    ;
  91. foreach(

    $uploads as $row)

    :
  92. $row[

    'fname'

    ]

    =

    str_replace(

    "uploads/"

    ,""

    , $row[

    'path'

    ]

    )

    ;
  93. ?>
  94. <tr

    >
  95. <td

    class

    =

    "px-2 py-1 align-middle text-center"

    ><?=

    number_format(

    $i++)

    ?></

    td

    >
  96. <td

    class

    =

    "px-2 py-1 align-middle"

    ><?=

    $row[

    'label'

    ]

    ?></

    td

    >
  97. <td

    class

    =

    "px-2 py-1 align-middle"

    ><p

    class

    =

    "m-0 text-truncate"

    title

    =

    "<?= $row['fname'] ?>

    "><?=

    $row[

    'fname'

    ]

    ?></

    p

    ></

    td

    >
  98. <td

    class

    =

    "px-2 py-1 align-middle text-center"

    >
  99. <a

    href

    =

    "<?= $row['path'] ?>

    " class="text-muted text-decoration-none mx-2" target="_blank" title="View File"><i

    class

    =

    "fa fa-external-link"

    ></

    i

    ></

    a

    >
  100. <a

    href

    =

    "<?= base_url($row['path']) ?>

    " class="text-primary fw-bolder text-decoration-none mx-2" target="_blank" title="Download File" download="<?=

    $row[

    'fname'

    ]

    ?>

    "><i

    class

    =

    "fa fa-download"

    ></

    i

    ></

    a

    >
  101. </

    td

    >
  102. </

    tr

    >
  103. <?php endforeach; ?>
  104. <?php if(

    !isset(

    $uploads)

    || (

    isset(

    $uploads)

    && count(

    $uploads)

    <=

    0

    )

    )

    : ?>
  105. <tr

    >
  106. <th

    colspan

    =

    "4"

    class

    =

    "p-1 text-center"

    >

    No records found</

    th

    >
  107. </

    tr

    >
  108. <?php endif; ?>
  109. </

    tbody

    >
  110. </

    table

    >
  111. </

    div

    >
  112. </

    div

    >
  113. </

    div

    >
  114. </

    div

    >
  115. </

    div

    >
  116. </

    div

    >
  117. </

    body

    >
  118. </

    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 :)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,292

324,360

324,368

Top