A PHP Error was encountered

Severity: 8192

Message: Return type of CI_Session_files_driver::open($save_path, $name) should either be compatible with SessionHandlerInterface::open(string $path, string $name): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

Filename: drivers/Session_files_driver.php

Line Number: 132

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

A PHP Error was encountered

Severity: 8192

Message: Return type of CI_Session_files_driver::close() should either be compatible with SessionHandlerInterface::close(): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

Filename: drivers/Session_files_driver.php

Line Number: 290

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

A PHP Error was encountered

Severity: 8192

Message: Return type of CI_Session_files_driver::read($session_id) should either be compatible with SessionHandlerInterface::read(string $id): string|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

Filename: drivers/Session_files_driver.php

Line Number: 164

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

A PHP Error was encountered

Severity: 8192

Message: Return type of CI_Session_files_driver::write($session_id, $session_data) should either be compatible with SessionHandlerInterface::write(string $id, string $data): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

Filename: drivers/Session_files_driver.php

Line Number: 233

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

A PHP Error was encountered

Severity: 8192

Message: Return type of CI_Session_files_driver::destroy($session_id) should either be compatible with SessionHandlerInterface::destroy(string $id): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

Filename: drivers/Session_files_driver.php

Line Number: 313

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

A PHP Error was encountered

Severity: 8192

Message: Return type of CI_Session_files_driver::gc($maxlifetime) should either be compatible with SessionHandlerInterface::gc(int $max_lifetime): int|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

Filename: drivers/Session_files_driver.php

Line Number: 354

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_cookie_params(): Session cookie parameters cannot be changed after headers have already been sent

Filename: Session/Session.php

Line Number: 296

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Session ini settings cannot be changed after headers have already been sent

Filename: drivers/Session_files_driver.php

Line Number: 108

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_save_handler(): Session save handler cannot be changed after headers have already been sent

Filename: Session/Session.php

Line Number: 110

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_start(): Session cannot be started after headers have already been sent

Filename: Session/Session.php

Line Number: 143

Backtrace:

File: /home2/umernaze/public_html/coderanks/application/controllers/Article.php
Line: 7
Function: __construct

File: /home2/umernaze/public_html/coderanks/index.php
Line: 317
Function: require_once

Logo
Code Ranks ×

File Upload in CodeIgniter Php

12/04/2019  .   8 minutes, 47 seconds to read  .   Posted by Admin
#Php #FileUpload #WebDevelopment #Codeigniter #Model,View,Controller #htmlemail #codeigniteremail #mysql #phpmyadmin #best-practices #EntityFramework #Jquery #WebDevelopment

In this Article, we'll walk through the complete process of uploading a file(image and file) where users can add a file with all types or multiple files with multiple types using PHP CodeIgniter (a framework of PHP). We will also learn how a user creates Database, Connection with Database, Insertion, Selection and Forms with Post method and Action. A complete package to start the CodeIgniter Framework.

Requirements:

  1.  Xampp or Wamp Server Installed
  2. Code Editor (VS Code)
  3. CodeIgniter Project with latest Version 3.1.10 (you can download it on the official site of CodeIgniter or click here to download.

Detail:

Database:

Create a database called ci_file_upload. In the database named as ci_file_upload, create a table named as a file. The file table will take the following four fields as input from registration.

  1. id- INT(11) AUTO_INCREMENT PRIMARY_KEY
  2. file_name- VARCHAR(255)
  3. file_title- VARCHAR(255)
  4. created_date- TIMESTAMP DEFAULT CURRENT_TIMESTAMP

Or you can create it with the following query:

CREATE TABLE `file` (
      `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
      `file_name` varchar(255) NOT NULL,
      `file_title` varchar(255) NOT NULL,
      `created_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

After this, the structure of the table will look like:

In the project folder, there is the file name database.php in application/config folder. set it up for your database where hostname set to localhost automatically, the username is usually root or empty, the password is empty or set it to your local server password and the database name is ci_file_upload. That's it for the database.

MVC:

  1. Model: The handler of the database.
  2. View: The client side of the project.
  3. Controller: the bridge and control of model and view.

Now there are three folders model, views and controllers which represent the MVC of the CodeIgniter framework.

View:

Let's start with the views which are the client side interactions. In the view create the file name as file_form.php and write the following code in it.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <style>
    #add{

    }
    </style>
</head>

<body>
    <div class="container">
        <div class="col-md-6 offset-md-3 " style="margin-top:100px;">
            <div class="file-form">
                <h2>File Input</h2>
                <?php
                $opendata = array('class' => 'form-horizontal');
                echo validation_errors();
                echo form_open_multipart("file/save", $opendata);
                ?>
                <div class="form-group">
                    <?php $labeldata = array('class' => 'col-md-12 control-label'); ?>
                    <?= form_label('File:', 'file', $labeldata); ?>
                    <div class="col-md-12">
                        <input type="file" name="file" class="form-control btn" id="img-id">
                    </div>
                </div>
                <div class="form-group">
                    <?php $addbtn = array('class' => 'offset-md-9 col-md-3 btn btn-info', 'id' => 'add');
                    echo form_submit($addbtn, 'Submit'); ?>
                </div>
                <?= form_close(); ?>
            </div>
        </div>
    </div>
</body>

</html>

Bootstrap CSS and JS JS for jquery files including in the header. The form is in CodeIgniter and which is multipart for file uploading. When the view is complete, then there is a controller to load the view file

Controller:

The controller is here to understand the few things.

First of all, there is a controller class which starts with capital later extends from the built-in parent class CI_Controller provides you with a stream of data to avoid writing.

There are libraries, helpers, configurations, models, drivers etc but here, we use just a few of them.

$this is used everywhere whenever you want to call, store or load something. Actually $this is a singleton Codeigniter instance (the controller object).

The __construct() method is a magic method to load automatically whenever the object of the class created. For more detail about magic methods, you can read the article here.

In the constructor, there are two helpers and one library to load. The form_validation is a library to validate the form and its input values. The URL helper is to support the URL's given in the project. The form helper to load the assistance of form to work with.

In the index function, there is a view loaded with $this instance.

<?php 
    Class File extends CI_Controller { 
        
        Public function __construct() 
        { 
            parent::__construct();
            $this->load->library('form_validation');
            $this->load->helper(array('url','form'));
        }
        public function index()
        {
            $this->load->view('file_form');
        }
    }
?>

Now the URL to load the view in your localhost is  http://localhost/ci-file-upload/index.php/file.

The view will look like:

Before choosing the file and clicking the submit button, there is the function required in File Controller to receive data from the form and a function in the FileModel to insert into the database.

Now the controller will look like:

<?php 
    Class File extends CI_Controller { 
        
        Public function __construct() 
        { 
            parent::__construct();
            $this->load->library('form_validation');
            $this->load->helper(array('url','form','file'));
            $this->load->model('FileModel');
        }
        public function index()
        {
            $this->load->view('file_form');
        }

        public function home()
        {
            $data['fileData']=$this->FileModel->allFileData();
            $this->load->view('home',$data);
        }

        public function save()
        {
            $data=$this->input->post();
            if($_FILES['file']['name'] !=''){
                $target_dir ="./file";
                $config['upload_path'] = $target_dir;
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if ($this->upload->do_upload('file'))
                {
                    $data = $this->upload->data();
                    $insert = array(
                        'file' => $data['file_name']
                    );
                    // echo '<pre>',print_r($insert);exit;
                    $success = $this->FileModel->insertFileData($insert);
                    if($success){
                        redirect('file/home');
                    }
                }
            }
        }
    }
?>

There is a helper included named as a file to assist all component of file uploading.

A model named as FileModel also loaded in the constructor. $data stores all the form values in it as an array. Now check if the file values not empty.

Inside the if condition, there is a configuration of file. The target directory is stored in the variable $target_dir and assigned it to the upload path.

Allowed types are available in all aspects of the file. There are different values set to the $config such as min or max_size, min or max_width, min or max_height, file_name as the manual name of the file, overwrite for updating a file etc. For more click here to see the documentation of Codeigniter. 

The upload library is load with our selected preferences stored in $config. The command upload with do_upload is set to upload the file in the targeted directory.

Now insert and upload data into the database. For this, create an array $insert and passed it to the Model function insertFileData().

After the success in insertion, there is a redirection or direction to the function in the File Controller named as home. There is also the selection performed from the database and passed it to the view with the multiple arrays as we returned the data from the database with result_array() function.

Model:

In the model, the function with the same name and a parameter passed to it and the model name should be in the format like the first letter is capital and the Model letter is capital at the end.

The model will look like:

<?php 
    Class FileModel extends CI_Model { 
        
        Public function __construct() 
        { 
            parent::__construct(); 
            $this->load->database();
        }

        public function insertFileData($insert)
        {
            return $this->db->insert('file',$insert);
        }

        public function allFileData()
        {
            return $this->db->select('*')
                            ->from('file')
                            ->get()
                            ->result_array();
        }
    }
?>

In FileModel constructor, there should load the database and $this->db is an instance to it. In calling the insert function, the first parameter is the table_name and the second one is the values to insert as an array. There is a second function named as allFileData() which is a selection from the database and return an array of results.

Now the final Step is to display the files.

In home.php file write the following code in it carefully.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <style>
    .image img {
        width: 280px;
        height: 250px;
    }
    </style>
</head>

<body>
    <div class="container">
        <div class="file-home" style="margin-top:100px;">
            <h2>Home</h2>
            <div class="col-md-12">
                <div class="row">
                    <?php
                    foreach($fileData as $file){
                    ?>
                        <div class="image col-md-4 text-center">
                            <img src="<?=base_url()?>file/<?=$file['file_name']?>" alt="file">
                        </div>
                    <?php }
                    ?>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

The Home or Landing page will look like:

file-uploading-home

Important Points To Remember:

  1. Codeigniter is an MVC based PHP framework.
  2. Model: The handler of the database.
  3. View: The client side of the project.
  4. Controller: the bridge and control of model and view.
  5. Form_Validation is a library to validate a form input values.
  6. Form Helper is to assist the all aspects of form.
  7. File Helper and Config library is required to upload a file.
  8. Always call the Confiq library after setting up your config prefrences.
  9. The method do_upload() is uploading the file and then the insertion to database is performed by calling the specific method of Model.
  10. Redirection in Controller and some Return value in Model is required to validate/check the results.