PHP file upload

PHP file upload and Codeigniter upload

1 year ago

Introduction to Codeigniter upload

 

Codeigniter upload is the next secure level of ordinary PHP file upload. Eventually, Most of the web application projects require a file uploading part. Codeigniter comes with a file uploading class for this process. We have options to take a file name as well as dimension, store the name in the database, move to a folder and much more. The Codeigniter framework makes this process much more secure than core PHP file upload. Although we have options for another framework Codeigniter is the best choice.

I have already explained about features of Codeigniter in the previous section. Moreover, Codeigniter file upload resolves all issues that take with core PHP file upload. Codeigniter gives the option for validating the file. Validate a file include validating and restricting its file size, type, and even various preferences. In addition to that developer-friendly feature makes file upload unique from other frameworks. I will give you a short example of core PHP file uploading before starting Codeigniter upload.

 

PHP file upload

To learn Codeigniter file upload thoroughly understanding core PHP file upload is the first step. It helps you to understand what does each function do ? and How to create a form?. Make sure file_uploads is set on in your “php.ini” file to begin the process. Creating an HTML page “index.html” is the next part. Please refer the HTML code given below.

 

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

The form needs enctype="multipart/form-data" explains which content-type to use when submitting the form. In addition to index.html, you need to create a PHP page upload.php. You are posting data to the upload.php page. Make sure you use POST method in the form tag. Place the upload.php inside the action. Include a name for the input file for collecting the required parameter. Create a folder name upload_file inside your base folder. The file is transferred to this folder meanwhile. Please ensure using a submit button inside the form. The upload.php file creation is displayed below.

<?php
$file_path = "uploads/";
$file = $file_path . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($file)) {
echo "File already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "File is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg"
&& $fileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>

The file size detection is possible using the function strtolower(pathinfo($file,PATHINFO_EXTENSION)). Once file type detected file extension comparison is simple. We have option to check file exists or not using file_exists() function. $_FILES[“fileToUpload”][“size”] used to find file size.

 

Codeigniter file upload

If you are successful with core PHP file uploading Codeigniter file uploading is very simple. To begin with, the process we need to download the Codeigniter project and configure. We need to create a database and a table name file_data. We are inserting the file data into this table. The Codeigniter uses an uploading class as we told earlier. We have to load the upload library in the controller. Inside the construct function, we load the model. The model helps us to connect to the database. Codeigniter does follow the MVC pattern so we need to create a view. The code to create a view includes.

<div id="container">
<h1>CodeIgniter File Upload</h1>
 <div style="width:100%; margin:20px;">
 <?php
 
 if(!empty($message)){
 echo"<code>";
 echo $message;
 echo"</code>";
 }?>
<?php echo form_open_multipart('dashboard/uploadImage');?>
<div style="width:50%;">
<div style="margin-top:20px;">
<label style="color:blue;">File</label>
<input class="form-control" type="file" name="picture" />
</div>
<div style="margin-top:20px;">
<label style="color:blue;">Name</label>
<input class="form-control" type="text" name="name" />
</div>
<div style="margin-top:20px;">
<label style="color:blue;">Email</label>
<input class="form-control" type="text" name="email" />
</div>
<div style="margin-top:20px;">
<input type="submit" class="btn btn-warning" name="userSubmit" value="Upload">
</div>
</div>
</form>
</div>
</div>

Codeigniter allows form_open_multipart() function to use instead of normal form. It allows us to transfer our data to required function inside the controller. We are transferring our data to uploadImage function inside dashboard controller. Then we add dashboard controller inside controller folder. Create upload controller using this code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('array');
$this->load->helper('url');
$this->load->database('default');
$this->load->model("insertModel");
$this->load->helper('form');
$this->load->library('session');
}
public function index()
{

$this->load->view('upload_img');
}
function uploadImage(){
if($this->input->post('userSubmit')){
if(!empty($_FILES['picture']['name'])){
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}else{
$picture = '';
}
}else{
$picture = '';
}
$userData = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'picture' => $picture
);
$insertUserData = $this->insertModel->insertImg($userData);
if($insertUserData){
$data = array('message'=>'User data have been added successfully');
}else{
$data = array('message'=>'Some problems occured, please try again');
}
}
$this->load->view('upload_img',$data);
}
}

 

The submitted data passed to next stage after monitoring the null condition. Then we configure upload_path, allowed_types, and file_name. We load upload library for initializing upload process.
Straightaway we check the file movement processed using do_upload() function. Later each of the data is arranged in an array format and passed to the model. We perform the database insertion in the model. The code to create the model is shown below.

<?php
class insertModel extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->helper('array');
$this->load->helper('url');
$this->load->database('default');
}

public function insertImg($data = array()){
if(!array_key_exists("created",$data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified",$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
$insert = $this->db->insert('file_data', $data);
if($insert){
return $this->db->insert_id();
}else{
return false;
}
}
}

?>

The passed data to the function insertImg() is inserted using $this->db->insert('file_data', $data).

Download Codeigniter file uploading code

To begin with the process download the Codeigniter upload file by clicking the download button given below. I have added a file uploading code to Codeigniter source file. I’ve downloaded Codeigniter source file from codeigniter.com. Follow the steps given below to perform this.
1, Make sure server is active
2, Download the file and copy the same to “htdocs” folder
3, Unzip the file and configure the database
4, Import the SQL file from the root folder into the database
5, After that go for http://localhost/CodeIgniter_file_upload/

Download

Adharsh

3 thoughts on “PHP file upload and Codeigniter upload”

    1. Hi Jisha,

      Thanks for your question. You can limit the size of the uploaded image through a simple piece of code.
      $config['max_size'] = '100';
      $config['max_width'] = '1024';
      $config['max_height'] = '768';

      Yes we can resize the image in easy way. I will give a detail explanation about this topic with a post on coming days. You can resize with this code. $config['create_thumb'] = TRUE;
      $config['maintain_ratio'] = TRUE;
      $config['width'] = 50;
      $config['height'] = 50;

      The width and height of the image will automatically fixed to 50.

      Thanking you,
      Adharsh

Leave a Reply

Your email address will not be published. Required fields are marked *