PHP MVC CodeIgniter Laravel Core PHP MORE

How to upload file in PHP MVC with example


In this example we using Models, Views, Controller Structure for upload file.

Image table

Here is the Controller file hello.php which inside controllers folder

controllers/hello.php

<?php
class Hello extends Controller {
function __construct() {
parent::__construct();
}
function file_upload(){
if(isset($_POST['submit']))
{
$output_dir = "public/uploads";//Path for file upload
$fileCount = count($_FILES["image"]['name']);
$RandomNum = time();
$ImageName = str_replace(' ','-',strtolower($_FILES['image']['name'][$i]));
$ImageType = $_FILES['image']['type'][$i]; //"image/png", image/jpeg etc.
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
$ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
$NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;
$ret[$NewImageName]= $output_dir.$NewImageName;
move_uploaded_file($_FILES["image"]["tmp_name"][$i],$output_dir."/".$NewImageName );
$data = array(
'image' =>$NewImageName
);
$this->model->file_details($data);
echo "Image Uploaded Successfully";
}
$this->view->render('hello/upload');
}
}
?>

models/hello_model.php

hello_model.php

<?php
class Hello_Model extends Model
{
public function __construct()
{
parent::__construct();
}
public function file_details($data)
{
$this->db->insert('image_table', $data);
}
}
?>

Here is the view file upload.php which inside views folder contains the form.

views/hello/upload.php

<!DOCTYPE html>
<html>
<body>
<form method="post" action="multi_file_upload" enctype="multipart/form-data">
<input type="file" name="image[]" multiple="multiple" >
<p align="center"><button type="submit" class="btn btn-warning" id="butsave" name="submit">Submit<span class="glyphicon glyphicon-send"></span></button></p>
</form>
</body>
</html>
Path: localhost/project_folder_name/view_folder_name/view_filename
Example: localhost/mvc/hello/file_upload