• logo
  • PHP
  • PHP OOPs
  • script
    • JavaScript
    • JQuery
    • Ajax
    • AngularJs
    • VueJs
    • NodeJs
    • ReactJs
  • wordpress
  • Codeigniter
  • Codeigniter 4
  • Laravel
  • Python
  • MySql
  • Json
  • C
  • C++
  • More ...
    • Cakephp Framework
    • MongoDb
    • MySqli PDO
    • .htaccess
    • HTML 5
    • CSS
    • SEO
    • DCA

Codeigniter Tutorials

  • What is codeigniter?
  • Application_Architecture
  • MVC Architecture
  • HMVC Architecture
  • Codeigniter Configuration
  • Remove index.php from url in codeigniter
  • MVC Concept
  • View
  • Alternate PHP Syntax for View Files
  • Routing
  • Codeigniter URL
  • Get Current URL
  • Previous page URL get
  • Seo Friendly URL
  • Slug Create in codeigniter
  • What is _remap() function
  • Remove controller name from url in codeigniter
  • Codeigniter Controller Class
  • Class Constructor
  • GET $ POST method in Codeigniter
  • Models
  • Basepath, Apppath, FCPATH
  • URI Segment
  • Page Redirect
  • Helper class
  • Custom Helper class
  • Form Helper
  • Common Helper Functions
  • Common Function
  • Array Problems
  • Call controller in Helper
  • Add active class to menu using Helper class
  • Custom Library
  • Custom Library Example
  • when to use get_instance()
  • Codeigniter Hook
  • how to work inline css in codeigniter
  • Custom 404 page
  • 404 custom error page
  • Create custom config file in codeigniter
  • How to set and get config item value
  • How to Speed Up CodeIgniter App?
  • Codeigniter Functions
  • Session
  • cookies
  • How to Set & Get Tempdata in Codeigniter
  • flash messages in Codeigniter
  • Flashdata
  • Encryption and Decryption In CodeIgniter
  • Codeigniter security
  • csrf token form security
  • Password Hashing
  • Form Validation
  • Custom Validation
  • Registration Form with validation
  • Server Side Form Validation
  • Validate Select Option Field
  • Date Format Validation
  • Date Format change in codeigniter
  • Date Functions
  • DOB Validation
  • CI CRUD
  • User SignUp
  • User Login
  • User Logout
  • Login Account
  • Login form with RememberMe
  • Login Form with session
  • User change password
  • Change Password with Callback Validation to Check Old Password
  • Forgot password
  • Reset password
  • Insert data in database
  • Fetch data from database
  • Update data in database
  • Delete data in database
  • File Upload
  • Image Upload with resize Image
  • Upload Multiple file and images
  • Upload Multiple images with CRUD
  • File and image update
  • Upload Image Using Ajax.
  • Email Send
  • Email Send Using Email library
  • Email Send Using SMTP Gmail
  • Notification send
  • store data in json format in DB
  • Json parse
  • Fetch data Using Ajax with Json data
  • How to Show data Using Ajax with Json parse
  • Get JSON Data from PHP Script using jQuery Ajax
  • Insert data Using Ajax
  • Submit data Using Ajax with form validation
  • How to show data Using Ajax in codeigniter
  • Insert & Update Using Ajax
  • Registration Form With Validation Using Ajax in codeigniter
  • Delete data Using Ajax Confirmation
  • Delete All data Using checkbox selection
  • Ajax CSRF Token
  • Ajax Post
  • Ajax serverside form validation
  • Contact form using AJAX with form validation
  • DataTable Using Ajax dynamically
  • DataTables pagination using AJAX with Custom filter
  • DataTables AJAX Pagination with Search and Sort in codeigniter
  • DataTables in Codeigniter using Ajax
  • Ajax Custom Serarch
  • Ajax Live Data Search using Jquery PHP MySql
  • Ajax Custom Serarch and sorting in datatable
  • Dynamic Search Using Ajax
  • Autocomplete using jquery ajax
  • Jquery Ajax Autocomplete Search using Typeahead
  • Dynamic Dependent Dropdown Using Ajax
  • Dynamic Dependent Dropdown list Using Ajax
  • Dynamic Dependent Dropdown in codeigniter using Ajax
  • ajax username/email availability check using JQuery
  • Check Email Availability Using Ajax
  • Data Load on mouse scroll
  • Ajax CI Pagination
  • Pagination in codeigniter
  • Ajax Codeigniter Pagination
  • email exists or not using ajax with json
  • CRUD using AJAX With Modal popup in CI
  • Add / Show Data on modal popup using Ajax
  • Modal popup Validation using Ajax
  • Data show on Modal popup Using Ajax
  • Add / Remove text field dynamically using jquery ajax
  • How to Add/Delete Multiple HTML Rows using JavaScript
  • Delete Multiple Rows using Checkbox
  • Multiple Checkbox value
  • Form submit using jquery Example
  • REST & SOAP API
  • Multi-Language implementation in CodeIgniter
  • How to pass multiple array in view
  • Captcha
  • create zip file and download
  • PhpOffice PhpSpreadsheet Library (Export data in excel sheet)
  • data export in excel sheet
  • Excel File generate in Codeigniter using PHPExcel
  • Dompdf library
  • tcpdf library
  • Html table to Excel & docs download
  • CI Database Query
  • Database Query
  • SQL Injection Prevention
  • Auth Model
  • Join Mysql
  • Tree View in dropdown option list
  • OTP Integration in codeigniter
  • curl post
  • download file using curl
  • Sweet Alert
  • Sweet alert Delete & Success
  • Log Message in Codeigniter
  • Menu & Submenu show dynamically
  • Set Default value in input box
  • Cron Jobs
  • Stored Procedure
  • Display Loading Image when AJAX call is in Progress
  • Send SMS
  • IP Address
  • Codeigniter Tutorialspoint
  • Website Link
  • How To Create Dynamic Xml Sitemap In Codeigniter
  • Paypal Payment Integration
  • Get Latitude and Longitude From Address in Codeigniter Using google map API
  • How To Create Simple Bar Chart In Codeigniter Using AmCharts?
  • dynamic Highcharts in Codeigniter
  • Barcode in Codeigniter
  • Codeigniter Interview Questions
  • Project
Home » Codeigniter » 

File Upload


file extension for uploading correct file

‘xls’ => ‘0M8R4KGX’
‘docx’ =>’UESDBBQA’
‘doc’ => ‘0M8R4KGX’
‘txt’ => ‘MS4GV2HH’
‘png’ => ‘IVBORW0K’
‘jpg’ => ‘/9J/4AAQ’
‘pdf’ => ‘JVBERI0X’
‘xlsx’ => ‘UESDBBQA’

view

File name : view.php

<section class="content">
<div class="container-fluid">
<div class="page-content-inner">
<div class="profile">
<h3 class="formheading text-center" style="font-size: 1.25rem;margin-bottom: 34px;">Upload Training Video</h3>
<div class="formblock">
<?php echo form_open_multipart("Training_video/save_training_video"); ?>

<!--Card Start-->
<div class="card card-default">
<div class="card-header form-card-header">
<h3 class="card-title">Upload Training Video</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<div class="form-group">
<div class="col-md-12">
<div class="form-group row">

<label for="inputKey" class="col-md-3 control-label">Module Type<span class="required" aria-required="true"> * </span></label>
<div class="col-md-6">
<select class="form-control requireds selectpicker" name="module_type" id="module_type">

<option value="" selected="selected" disabled="disabled">--- Select Module ---</option>
<?php foreach($moduleinfo as $row){ ?>
<option value="<?php echo $row->pki_id; ?>"> <?php echo $row->vc_title; ?></option>
<?php } ?>

</select>
<span class="error"><?php echo form_error('module_type'); ?></span>
</div>


</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<div class="form-group row">

<label for="inputKey" class="col-md-3 control-label">Video Title<span class="required" aria-required="true"> * </span></label>
<div class="col-md-6">
<input type="text" class="form-control" name="module_title" id="module_title" value="<?php echo set_value('module_title');?>" placeholder=" Enter Module Title"/>
<span class="error"><?php echo form_error('module_title'); ?></span>
</div>


</div>
</div>
</div>


<div class="form-group">
<div class="col-md-12">
<div class="form-group row">
<label for="inputValue" class="col-md-3 control-label">Video Discription<span class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<textarea class="form-control requireds" name="discription" id="discription" placeholder="Enter Discription" rows="3" cols="50"><?php echo set_value('discription'); ?><?php echo set_value('discription'); ?></textarea>
<span class="required" id="discription_error" aria-required="true"></span>
<span class="error"><?php echo form_error('discription'); ?></span>
</div>
</div>
</div>
</div>








<div class="morefiles">
<div class="form-group">
<div class="col-md-12">
<div class="form-group row">
<label for="inputKey" class="col-md-3 control-label">Upload Featured Image</label>
<div class="col-md-7">
<input type="file" id="feature_image" name="feature_image" class="form-control" onchange="Validatefile(this.id,this.value)" value="<?php echo set_value('feature_image'); ?>">


<p style="color:green;">File format Allowed (.jpg, .png) and Max. upload size of each file 5 MB</p>

<span class="help-block" style="color:red;"><?php echo form_error('feature_image'); ?></span>
</div>



</div>
</div>
</div>
</div>



<div class="morefiles">
<div class="form-group">
<div class="col-md-12">
<div class="form-group row">
<label for="inputKey" class="col-md-3 control-label">Upload Video</label>
<div class="col-md-7">
<input type="file" id="video_file" name="video_file" class="form-control" value="<?php echo set_value('video_file'); ?>" >
<span class="required" id="video_file_error" aria-required="true"></span>

<span class="help-block" style="color:red;"><?php echo form_error('video_file'); ?></span>

</div>


</div>
</div>
</div>
</div>






</div></div>
<!--Card End-->
<!--Footer-->
<div class="button_center">
<input type='submit' class="btn btn-primary waves-effect submit_doc" id="submit_complaint" onclick="submit_form()" value="Submit"/>
</div>
<div id="msg_loader" style="display:none;">
<img src="<?php echo base_url(); ?>assets/dist/img/loader.gif">
</div>
<?php echo "</form>";?>
</div>
</div>



</div> <!-- End Row -->
</div> <!-- End container-fluid -->
</section> <!-- End Section -->

Controller

File name : UploadController.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Training_video extends CI_Controller {
var $data = array();
public function __construct()
{
parent::__construct();
}
public function add_training_video()
{
$title = "Add Training Video";
$table = "tv_modules";
$data['moduleinfo']= $this->Video_model->FetchAllRow($table);
$this->load->view('common/header.php',$title);
$this->load->view('common/navigation.php');
$this->load->view('add-training-video',$data);
$this->load->view('common/footer');
}

public function save_training_video()
{


if($this->input->post() !== FALSE)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('module_type', 'Module', 'trim|required');
$this->form_validation->set_rules('module_title', 'Module Title', 'trim|required');
$this->form_validation->set_rules('discription', 'discription', 'trim|required|callback_alpha_numeric_dash_space');

$this->form_validation->set_rules("feature_image", "Featured Image", "callback_file_check");
$this->form_validation->set_rules("video_file", "Video File", "callback_video_file_chdeck");


if ($this->form_validation->run() == FALSE)
{
$title = "Add Activity Module";
$this->load->view('common/header.php',$title);
$this->load->view('common/navigation.php');
$this->load->view('add-training-video');
$this->load->view('common/footer');
}
else
{

if (!isset($this->data['error']))
{
$module_type = $this->input->post('module_type');
$module_title = $this->input->post('module_title');
$discription = $this->input->post('discription');
$created_by = $_SESSION['UserID'];


$current_time = date('dmY_his');
$newname = "doc_".$current_time;
$file_EXT = pathinfo($_FILES['feature_image']['name'], PATHINFO_EXTENSION);
$image_file_name = $newname.'.'.strtolower($file_EXT);

// $image_file_name=date("dmY")."_".time()."_".$_FILES['feature_image']['name'];

$config['upload_path'] = 'upload/video_feature_image/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '5000'; // max_size in 5mb
// $config['encrypt_name'] = TRUE; // it generate randomly name $config['file_name'] = $image_file_name;
$this->load->library('upload', $config);
//$fileName = $this->upload->data('feature_image');
$fileName = $_FILES['feature_image']['name'];
$fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
// $fileExt = pathinfo($_FILES["feature_image"]["name"], PATHINFO_EXTENSION);
//print_r($fileExt);

if(!$this->upload->do_upload('feature_image')) {
$error = array('error' => $this->upload->display_errors());
$title = "Add Videos Activity";
$this->load->view('common/header.php',$title);
$this->load->view('common/navigation.php');
$this->load->view('add-training-video',$error);
$this->load->view('common/footer');
}
else {
$data = $this->upload->data();
$image_name = $data['file_name'];
}



/* ######## Video File Upload ########### */

$video_file_name=date("dmY")."_".time()."_".$_FILES['video_file']['name'];
$config_video['upload_path'] = 'upload/video_library/';
$config_video['allowed_types'] = 'avi|mp4|3gp|mpeg|mpg|mov|flv|wmv';
$config_video['max_size'] = '102400';
$config_video['overwrite'] = FALSE;
$config_video['remove_spaces'] = TRUE;
$config_video['file_name'] = $video_file_name;
//$fileName = $this->upload->data('video_file');
$fileName = $_FILES['video_file']['name'];
$fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
// $fileExt = pathinfo($_FILES["video_file"]["name"], PATHINFO_EXTENSION);
//print_r($fileExt);
$this->load->library('upload', $config_video);
$this->upload->initialize($config_video);

if (!$this->upload->do_upload('video_file'))
{
// Upload Failed

/*$error = array('error' => $this->upload->display_errors());
$title = "Add Videos Activity";
$this->load->view('common/header.php',$title);
$this->load->view('common/navigation.php');
$this->load->view('add-training-video',$error);
$this->load->view('common/footer');
*/


$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('Training_video/add_training_video');



}
else
{
$video_data = array();
$video_data = $this->upload->data();
$video_name = $video_data['file_name'];
}


/* ######## End Video File Upload ########### */




$videos_data = array( 'vc_title' => $module_title,
'fki_module_id' => $module_type,
'vc_discription' => $discription,
'vc_featured_image' => $image_name,
'vc_file_name' => $video_name,
'fki_entered_by' => $created_by,
'dt_entered_on' => date('Y-m-d H:i:s'),
'fki_status_id' => 1
);

$insert_id = $this->Video_model->Insert('tv_videos_details',$videos_data);

$_SESSION['temp']['success_msg'] = 'Training Video added Successfully';
unset($_SESSION['temp']['error_msg']);
redirect('upload-training-video');



}
else{
$_SESSION['temp']['error_msg'] = 'Server Error .Please Try Again';
unset($_SESSION['temp']['success_msg']);
redirect('upload-training-video');
}

}


}
}


public function videos_list($id)
{
$id = base64_decode($id);
$title = "Videos List";
$table = "tv_videos_details";
$field = "fki_module_id";
$data['videolist'] = $this->Video_model->FetchAllRowById($table, $field, $id);

$this->load->view('common/header.php',$title);
$this->load->view('common/navigation.php');
$this->load->view('videos-list',$data);
$this->load->view('common/footer');
}


public function file_check($str){
$allowed_mime_type_arr = array('image/gif','image/jpeg','image/jpg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['feature_image']['name']);
if(isset($_FILES['feature_image']['name']) && $_FILES['feature_image']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('file_check', 'Please select only jpg/png image.');
return false;
}
}else{
$this->form_validation->set_message('file_check', 'Please choose a Image to upload.');
return false;
}
}

public function video_file_chdeck($str){
$allowed_mime_type_arr = array('mpeg|avi|wmv|mp4');
$mime = get_mime_by_extension($_FILES['video_file']['name']);
if(isset($_FILES['video_file']['name']) && $_FILES['video_file']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('video_file_chdeck', 'Please select only Video File');
return false;
}
}else{
$this->form_validation->set_message('video_file_chdeck', 'Please choose Video to upload.');
return false;
}
}


public function alpha_space($str)
{
if (! preg_match('/^[a-zA-Z\s]+$/', $str)) {
$this->form_validation->set_message('alpha_space', 'The %s field contain only characters');
return FALSE;
} else {
return TRUE;
}
}

public function alpha_numeric_dash_space($str_in = '')
{
if (! preg_match("/^([-a-z0-9_ ])+$/i", $str_in))
{
$this->form_validation->set_message('alpha_numeric_dash_space', 'The %s field only contain alpha-numeric, underscores & dashes.');
return FALSE;
}
else
{
return TRUE;
}
}




}

Controller

File name : Uploadprofile.php

<?php
defined('BASEPATH') OR exit('no direct script access allowed');
class Uploadprofile extends CI_Controller
{
public function __construct()
{
parent::__construct();

}

public function index()
{
$this->load->view('uploadprofile');
}

public function profilepicupload()
{
$new_file_name=date("mdY")."_".time();
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 1024;
$config['max_height'] = 1200;

$config['file_name'] = $new_file_name;

$this->load->library('upload', $config);
// $this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('uploadprofile', $error);
}
else {
$data = $this->upload->data();
$image_name = $data['file_name'];
echo $image_name;
$saved_file_name = $this->upload->data('file_name');
//echo $saved_file_name;
$ext = substr(strrchr($saved_file_name, '.'), 1);
echo $ext;

$without_extension = substr($saved_file_name, 0, strrpos($saved_file_name, "."));
echo $without_extension;
$without_extension = basename($saved_file_name, '.' .$ext);
/* $data = array(
'upload_data' => $this->upload->data()

); */
echo "File uploaded Successfully!";
}

}

}

View :-

File name : uploadprofile.php

<html>
<head>

</head>
<body>
<?php echo $error;?> <form action="<?php echo base_url();?>uploadprofile/profilepicupload" method="post" enctype="multipart/form-data">

<input type="file" name="userfile"/>
<input type="submit" name="submit" value="Submit"/>

</form>
</body>
</html>


Example

Controller :-

File name : Addleaderinfo.php

<?php
defined('BASEPATH') OR exit('no direct access allowd');
class Addleaderinfo extends CI_Controller
{
public function __construct()
{
parent::__construct();
}

public function index()
{
$this->load->view('admin_views/header');
$this->load->view('admin_views/leftpanel');
$this->load->view('admin_views/addleaderinfo');
$this->load->view('admin_views/footer');
}

public function insert_leader_info()
{
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 1024;
$config['max_height'] = 1200;

$this->load->library('upload', $config);
// $this->upload->initialize($config);
if ( ! $this->upload->do_upload('filename')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('addleaderinfo', $error);
}
else {
$data = $this->upload->data();
$image_name = $data['file_name'];
}


$data = array(
'candidate_name' => $this->input->post('name'),
'party_name ' => $this->input->post('partyname'),
'email' => $this->input->post('email'),
'dob'=> $this->input->post('dob'),
'gender' => $this->input->post('gender'),
'mobile' => $this->input->post('mob'),
'qualification'=> $this->input->post('qualification'),
'state'=> $this->input->post('state'),
'details'=> $this->input->post('details'),
'candidate_image' => $image_name

);

$this->Admin_model->leader_insert($data);
$success = "Your data is successfully submited.";
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Your data is successfully submited.</div>');
redirect('admin/Addleaderinfo');

}
}


view file:-

File name : addleaderinfo.php

<!DOCTYPE html>
<html>
<head>

</head>
<body>

<div class="row">

<center>
<div style="color: red;">
<?php //echo validation_errors(); ?>
</div>
</center>


<h3 class='flashMsg flashSuccess' style="color: green;">
<?=$this->session->flashdata('msg')?>
</h3>

<h3 class='flashMsg flashSuccess' style="color: green;">
<?php //echo $error;?>
</h3>

<form class="form-horizontal"
action="<?php echo base_url();?>admin/addleaderinfo/insert_leader_info"
method="post" name="frm" id="frm" enctype="multipart/form-data">

<div class="col-md-6">

<input type="text" class="form-control" name="name" /> <input
type="text" class="form-control" name="partyname" /> <input
type="text" class="form-control" name="email" /> <input
type="text" class="form-control datepicker" name="dob"> <input
type="radio" class="" name="gender" value="male">&nbsp;&nbsp;Male
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" class=""
name="gender" value="female">&nbsp;&nbsp;Female <input
type="file" class="fileinput btn-primary" name="filename"
id="filename" title="Browse file" /> <input type="text"
class="form-control" name="mob" /> <select
class="form-control select" name="qualification">
<option value="">--- Select ---</option>
<option value="B.A">B.A</option>

</select> <select class="form-control select" name="state">
<option value="">--- Select state ---</option>
<option value="delhi">delhi</option>

</select>

<textarea class="form-control" rows="6" name="details"></textarea>

<input type="submit" name="submit" value="Submit"/>

</div>

</form>
</div>
</body>
</html>


CodeIgniter - File Uploading :-

File name : myview.php

<html>

<head>
<title>Upload Form</title>
</head>

<body>
<?php echo $error;?>

<form action = "<?php echo base_url();?>Myupload/picupload" method = "post" name="frm" enctype="multipart/form-data">
<input type = "file" name = "userfile" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
</form>

</body>

</html>


Controller file :-

File name : Myupload.php

<?php

class Myupload extends CI_Controller {

public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}

public function index() {
$this->load->view('myview', array('error' => ' ' ));
}

public function picupload() {
$data = array();
$filenme = "img_" . time() . $_FILES['userfile']['name'];
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png|pdf|jpeg';
$config['max_size'] = 5000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['file_name'] = $filenme;

$this->load->library('upload', $config);
// $this->upload->initialize($config);

if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('myview', $error);
}

else {
$datafile = $this->upload->data();
$doc_name = $datafile['file_name'];
$data['thumbnail'] = $doc_name;
$this->load->view('upload_success', $data);
}
}
}
?>


success view :-

File name : upload_success.php

<html>

<head>
<title>Upload Form</title>
</head>

<body>
<h3>Your file was successfully uploaded!</h3>

<ul>
<?php foreach ($thumbnail as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>

<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>

</html>


Example :-

File name : view

<html>
<head>

</head>
<body>
<form action="<?php echo base_url();?>uploadprofile/profilepicupload" method="post" enctype="multipart/form-data">

<input type="file" name="userfile"/>
<input type="submit" name="submit" value="Submit"/>

</form>
</body>
</html>


controller :-

File name : controller

public function myfileupload()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
if (empty($_FILES['userfile']['name'])) {
$this->form_validation->set_rules('userfile', 'Uplpoad Document', 'required');
}
if ($this->form_validation->run() == false) {
$data = array();
$data['title'] = 'Complaint';
$data['heading'] = '';
$this->load->view('header', $data);
$this->load->view('home', $data);
$this->load->view('footer', $data);

} else {

$uploadPath = FILE_ROOT_PATH . '\assets\images';
$filenme = "img_" . time() . $_FILES['userfile']['name'];

$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 1024;
$config['max_width'] = 1024;
$config['max_height'] = 1024;
$config['file_name'] = $filenme;
$this->load->library('upload', $config);
// $this->upload->initialize($config);

if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('home', $error);
}
else {
$data = $this->upload->data();
$image_name = $data['file_name'];

}
$data = array(
'image_name' => $image_name
);
$data['query1'] = $this->gst_model->file_gst_complaint($data);

$this->session->set_flashdata('msg', '<div class="alert text-center">Your data is successfully submited.</div>');
redirect('/');



}


Example :

How to upload File and images in codeigniter? :

File name : user_view.php

<b><?php if(isset($response)) echo $response; ?></b>
<form method='post' action='<?php echo base_url(); ?>' enctype='multipart/form-data'>

<input type='file' name='thumbnail' > <br/><br/>
<input type='submit' value='Upload' name='upload' />
</form>

controller

File name :

<?php<?phpdefined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {

public function index(){
// load base_url
$this->load->helper('url');

// Check form submit or not
if($this->input->post('upload') != NULL ){
$data = array();
if(!empty($_FILES['thumbnail']['name'])){
// Set preference
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf';
$config['max_size'] = '100'; // max_size in kb
$config['file_name'] = $_FILES['thumbnail']['name'];

// Load upload library
$this->load->library('upload',$config);
// $this->upload->initialize($config);

// File upload
if($this->upload->do_upload('thumbnail')){
// Get data about the file
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
$data['response'] = 'successfully uploaded '.$filename;
}else{
$data['response'] = 'Sorry Your File not Uploaded';
}
}else{
$data['response'] = 'Sorry Your Thumbnail file is empty';
}
// load view
$this->load->view('user_view',$data);
}else{
// load view
$this->load->view('user_view');
}
}
}

File name :


config/constant.php :-

File name : constant.php

/**** define custom constant for file path.***/
if($_SERVER['HTTP_HOST'] == 'localhost')
{
define('FILE_ROOT_PATH', $_SERVER['DOCUMENT_ROOT'].'\secura');

}
else
{
define('FILE_ROOT_PATH', $_SERVER['DOCUMENT_ROOT']);
}


File Upload using Helper Function

Single file or Multiple File/images

File name :

if(isset($_FILES['attachment']['name'])&&($_FILES['attachment']['name'] != "")){
$upload_path_dir = "/media/docfiles/";
$uploadfiles = file_uploading($upload_path_dir,$_FILES['attachment']);

if ($uploadfiles === FALSE) {
$error = array('errors' => $this->upload->display_errors());
$_SESSION['temp']['error_msg'] = $error;
redirect('home');
}else{
$upload_file_name = $uploadfiles;
$total_files = count($upload_file_name);
for($i = 0; $i < count($upload_file_name); $i++){
$data_file[] = array(
'file_uploaded_name'=> $upload_file_name[$i],
'status'=>1,
'created_at'=>date('Y-m-d H:i:s'),
'created_by'=>$user_uid,
);
}
$insertfiledata = $this->User_model->InsertArray($table='sdo_standard',$data_file);
}

}
$_SESSION['temp']['success_msg'] = "FileUploaded successfully.";
unset($_SESSION['temp']['error_msg']);
redirect('home');

File Uploading Helper Function

File name :

if (! function_exists('file_uploading')){

function file_uploading($upload_path,$files) {

$CI = get_instance();

$CI->load->library('upload');

$date = date('Y-m-d');

$upload_path_directory = $upload_path;

if (!is_dir($upload_path_directory)) {
$oldmask = umask(0);
mkdir($upload_path_directory,0777,TRUE);
umask($oldmask);

}


if(is_array($files['name'])){
$file_type = 1;
}else{
$file_type = 2;
}

if($file_type==2){

$info = pathinfo($files['name']);
$uploadfile_names = $info['filename'];
$uploadfile_name = str_replace(' ', '_', $uploadfile_names);

$extension = $info['extension'];

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random_strng = substr(str_shuffle($characters), 0, 4);

$filename = $uploadfile_name.'_'.$random_strng.'_'.$date.'.' . $extension;

$_FILES['file']['name'] = $filename;
$_FILES['file']['type'] = $files['type'];
$_FILES['file']['tmp_name'] = $files['tmp_name'];
$_FILES['file']['size'] = $files['size'];


$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'jpg|jpeg|png|bmp|pdf';
$config['file_name'] = $filename;
$config['max_size'] = '5000';


$CI->load->library('upload', $config);
$CI->upload->initialize($config);

if(!$CI->upload->do_upload('file',$filename)){
return false;
}else{
return $allfiles = $filename;
}
}
else if($file_type==1){

$filesCount = count($files['name']);

for($i = 0; $i < $filesCount; $i++){

$info = pathinfo($files['name'][$i]);
$uploadfile_names = $info['filename'];
$uploadfile_name = str_replace(' ', '_', $uploadfile_names);

$extension = $info['extension'];

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random_strng = substr(str_shuffle($characters), 0, 4);

$filename = $uploadfile_name .'_'.$random_strng.'_'.$date.'.' . $extension;

$_FILES['file']['name'] = $filename;
$_FILES['file']['type'] = $files['type'][$i];
$_FILES['file']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['file']['size'] = $files['size'][$i];


$config['upload_path'] = $upload_path_directory;
$config['allowed_types'] = 'jpg|jpeg|png|bmp|pdf';
$config['file_name'] = $filename;
$config['max_size'] = '5000';


$CI->load->library('upload', $config);
$CI->upload->initialize($config);

if(!$CI->upload->do_upload('file',$filename)){
return false;

}else{
$allfiles[] = $filename;
}

}
$total_upload_file = count($allfiles);

if($total_upload_file>1){
return $allfiles;

}else{
$files = $allfiles;
return $files;
}
}

}
}

How to create Random String

File name :

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random_strng = substr(str_shuffle($characters), 0, 4);
// it gives 4 character random string.

file upload validation in codeigniter

File name :

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Doc', 'required');


Change To


$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('userfile', 'Doc', 'required');
}

File uploading validation

File name :

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Files management class created by CodexWorld
*/
class Files extends CI_Controller {

function __construct() {
parent::__construct();
}

public function upload(){
$data = array();

//load form validation library
$this->load->library('form_validation');

//load file helper
$this->load->helper('file');

if($this->input->post('uploadFile')){
$this->form_validation->set_rules('file', '', 'callback_file_check');

if($this->form_validation->run() == true){
//upload configuration
$config['upload_path'] = 'uploads/files/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['max_size'] = 1024;
$this->load->library('upload', $config);
//upload file to directory
if($this->upload->do_upload('file')){
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];

/*
*insert file information into the database
*.......
*/

$data['success_msg'] = 'File has been uploaded successfully.';
}else{
$data['error_msg'] = $this->upload->display_errors();
}
}
}

//load the view
$this->load->view('files/upload', $data);
}

/*
* file value and type check during validation
*/
public function file_check($str){
$allowed_mime_type_arr = array('application/pdf','image/gif','image/jpeg','image/pjpeg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['file']['name']);
if(isset($_FILES['file']['name']) && $_FILES['file']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('file_check', 'Please select only pdf/gif/jpg/png file.');
return false;
}
}else{
$this->form_validation->set_message('file_check', 'Please choose a file to upload.');
return false;
}
}
}




<?php
if(!empty($success_msg)){
echo '<p class="statusMsg">'.$success_msg.'</p>';
}elseif(!empty($error_msg)){
echo '<p class="statusMsg">'.$error_msg.'</p>';
}
?>

<form method="post" enctype="multipart/form-data">
<p><input type="file" name="file"/></p>
<?php echo form_error('file','<p class="help-block">','</p>'); ?>
<p><input type="submit" name="uploadFile" value="UPLOAD"/></p>
</form>

How to validate file Uploading in codeigniter?

File name :

<?php

class UploadImage extends CI_Controller {

public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}


public function index() {
$this->load->view('imageupload_view', array('error' => '' ));
}


/**
* Method to upload image to the server
*
* @return Response
*/
public function uploadImage() {


$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'gif|jpeg|jpg|png';
$config['max_size'] = 2048;
$this->load->library('upload', $config);

if ( ! $this->upload->do_upload('image')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('imageupload_view', $error);
}else {
echo "Upload Successful";
exit;
}
}

}
?>









<!DOCTYPE html>
<html>
<head>
<title>Image upload in Codeigniter with example</title>
</head>
<body>

<?php echo $error;?>
<?php echo form_open_multipart('upload-image/post');?>
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>


</body>
</html>

Change File extention capital to smaller

File upload with lower case extenstion.

File name :

public function submit_data()
{
$current_time = date('dmY_his');
$newname = "doc_".$current_time;
$file_EXT = pathinfo($_FILES['image_name']['name'], PATHINFO_EXTENSION);
$new_file_name = $newname.'.'.strtolower($file_EXT);

$config['upload_path']="./assets/images";
$config['allowed_types'] = 'pdf|png|jpg|jpeg';
// $config['encrypt_name'] = TRUE; // it generate randomly name
$config['file_name'] = $new_file_name;
$this->load->library('upload',$config);

if($this->upload->do_upload("image_name"))
{

$data = array('upload_data' => $this->upload->data());
$title= $this->input->post('title');
$image= $data['upload_data']['file_name'];

$result= $this->Auth_model->save_upload($title,$image);

if(!empty($result)){
$_SESSION['temp']['success_msg'] = 'Your Data Successfully Submitted';
unset($_SESSION['temp']['error_msg']);
redirect('Sweetalert_action');
}
}
else {
$_SESSION['temp']['error_msg'] = 'Server Error .Please Try Again';
unset($_SESSION['temp']['success_msg']);
redirect('Sweetalert_action');
}




}

More File Upload

File name :

public function submitpost()
{


$this->form_validation->set_rules('url_title', 'URL Title', 'trim|required');

$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('categoryname', 'Category Name', 'trim|required');
$this->form_validation->set_rules('short_discription', 'Short Discription', 'trim|required');
$this->form_validation->set_rules('slider_image', 'Slider Image', 'callback_file_check_sliderimage');
$this->form_validation->set_rules('feature_image', 'Feature Image', 'callback_file_check_feature');
$this->form_validation->set_rules('discription_image', 'Post Image', 'callback_file_check_dis');
$this->form_validation->set_rules('author_name', 'Author Name', 'trim|required');

if ($this->form_validation->run() === FALSE)
{

// $error = array('error' => $this->upload->display_errors());


$data = array();
$title['title'] = "Validation";
$data['error'] = $this->upload->display_errors();
//$error = array('error' => $this->upload->display_errors());
$result = $this->Admin_model->get_category_info();
$data['category'] = $result;

$this->load->view('admin/header');
$this->load->view('admin/post-details',$data);
$this->load->view('admin/footer');



}

else
{



$url_title = $this->input->post('url_title');
$last_inserted_id = $this->Admin_model->get_last_id();
//print_r($last_inserted_id);die();
//$slug_id = base64_encode($last_inserted_id->id);
$slug_id = $this->encryptor('encrypt',$last_inserted_id->id);
$slug_title = slug($url_title);
//$slug_title' = slugify($url_title);
$slug = strtolower($slug_title.'-'.$slug_id);

/*
if(isUrlExists('post_details',$slug)){
$slug = $slug.'-'.time();
}
$data['post_slug'] = $slug;
*/



// ################ Slider Image #############
if(isset($_FILES['slider_image']) && !empty($_FILES['slider_image']['name']))
{
$slider_image = "sli_".date("dmY")."_".time();
$config['upload_path'] = './assets/images/slider_images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $slider_image;
$config['max_size'] = 1024;
$config['max_width'] = 1024;
$config['max_height'] = 1024;


$this->load->library('upload',$config);
$this->upload->initialize($config);


if (!$this->upload->do_upload('slider_image'))
{

//$error = array('error' => $this->upload->display_errors());
//print_r($error);die();

$data = array();
$title['title'] = "Post Details";
$result = $this->Admin_model->get_category_info();
$this->data['category'] = $result;
$this->data['error'] = $this->upload->display_errors();
//print_r($data['error']);die();
if(!empty($this->data['error']))
{
$error1 = $this->upload->display_errors();
$this->session->set_flashdata('slider_error', '<div class="alert alert-danger alert-block text-center">'.$error1.' </div>');
//redirect('admin/post/');
/*
$data['error'] = $this->upload->display_errors();
//$error = array('error' => $this->upload->display_errors());
$result = $this->Admin_model->get_category_info();
$data['category'] = $result;

$this->load->view('admin/header');
$this->load->view('admin/post-details',$data);
$this->load->view('admin/footer');
*/
}

}else
{

$data_slider = $this->upload->data();
$slider_imagename = $data_slider['file_name'];
}

}




// ################ Feature Image #############

if(isset($_FILES['feature_image']) && !empty($_FILES['feature_image']['name']))
{
$feature_image_name = "fea_".date("dmY")."_".time();
$config2['upload_path'] = './assets/images/featureimages/';
$config2['allowed_types'] = 'gif|jpg|png|jpeg';
$config2['file_name'] = $feature_image_name;
$config2['max_size'] = 1024;
$config2['max_width'] = 1024;
$config2['max_height'] = 1024;

$this->load->library('upload',$config2);
$this->upload->initialize($config2);



if (!$this->upload->do_upload('feature_image'))
{
$error2 = $this->upload->display_errors();
$this->session->set_flashdata('feature_error', '<div class="alert alert-danger alert-block text-center"> '.$error2.' </div>');
//redirect('admin/post/');

/*
$title['title'] = "Post Details";
$result = $this->Admin_model->get_category_info();
$data['category'] = $result;
$data['error'] = $this->upload->display_errors();
//$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/header',$title);
$this->load->view('admin/post-details',$data);
$this->load->view('admin/footer');
*/
}
else{
$data = $this->upload->data();
$feature_imagename = $data['file_name'];
}
}



// ################ Post Image ############# //
if(isset($_FILES['discription_image']) && !empty($_FILES['discription_image']['name']))
{

$dis_image_name = "dis_".date("dmY")."_".time();
$config3['upload_path'] = './assets/images/discription_images/';
$config3['allowed_types'] = 'gif|jpg|png|jpeg';
$config3['file_name'] = $dis_image_name;
$config3['max_size'] = 1024;
$config3['max_width'] = 1024;
$config3['max_height'] = 1024;

$this->load->library('upload', $config3);
$this->upload->initialize($config3);

if(!$this->upload->do_upload('discription_image'))
{
$error3 = $this->upload->display_errors();
$this->session->set_flashdata('postimage_error', '<div class="alert alert-danger alert-block text-center">'.$error3.'</div>');
//redirect('admin/post/');
/*
$title['title'] = "Post Details";
$result = $this->Admin_model->get_category_info();
$data['category'] = $result;
$data['error'] = $this->upload->display_errors();
//$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/header',$title);
$this->load->view('admin/post-details',$data);
$this->load->view('admin/footer');
*/
}
else{
$dis_data = $this->upload->data();
$dis_imagename = $dis_data['file_name'];
}
}

if($error1 != '' || $error2 != '' || $error3 != '')
{
redirect('admin/post/');
}


$data = array(
'title' => strip_tags($this->input->post('title')),
'post_slug' => $slug,
'category_name' => strip_tags($this->input->post('categoryname')),
'subcategory_name' => strip_tags($this->input->post('subcategoryname')),
'short_discription' => strip_tags($this->input->post('short_discription')),
'slider_image' => $slider_imagename,
'feature_image' => $feature_imagename,
'discription_image' => $dis_imagename,
'author_name' => strip_tags($this->input->post('author_name')),
'created_at' => date('Y-m-d H:i:s A'),
//'time' => date('H:i:sa')

);



$result = $this->Admin_model->post_submit($data);
// $last_insertedId = $this->db->insert_id();
if ($result) {
$this->session->set_flashdata('successmsg', '<div class="alert alert-success alert-block text-center">Post Details Added Successfully.</div>');
redirect('admin/post/showpostdetails');
//redirect( base_url('admin/post/showpostdetails'));
}

}



}


/* ***************** File Check Function ********** */




public function file_check_sliderimage($str)
{
$allowed_mime_type_arr = array('application/pdf','image/gif','image/jpeg','image/jpg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['slider_image']['name']);
if(isset($_FILES['slider_image']['name']) && $_FILES['slider_image']['name']!="")
{
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('file_check_sliderimage', 'Please select only pdf/gif/jpg/png/jpeg file.');
return false;
}
}else{
$this->form_validation->set_message('file_check_sliderimage', 'Please choose a Slider Image to upload.');
return false;
}
}



public function file_check_feature($str){
$allowed_mime_type_arr = array('application/pdf','image/gif','image/jpeg','image/jpg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['feature_image']['name']);
if(isset($_FILES['feature_image']['name']) && $_FILES['feature_image']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('file_check_feature', 'Please select only pdf/gif/jpg/png/jpeg file.');
return false;
}
}else{
$this->form_validation->set_message('file_check_feature', 'Please choose a Feature Image to upload.');
return false;
}
}


public function file_check_dis($str){
$allowed_mime_type_arr = array('application/pdf','image/gif','image/jpeg','image/jpg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['discription_image']['name']);
if(isset($_FILES['discription_image']['name']) && $_FILES['discription_image']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('file_check_dis', 'Please select only pdf/gif/jpg/png/jpeg file.');
return false;
}
}else{
$this->form_validation->set_message('file_check_dis', 'Please choose a Discription Images to upload.');
return false;
}
}




Itechtuto

Connect Us Socially:

Quick Links

  • itech
  • About Us
  • Feedback
  • Trademarks
  • Privacy Policy
  • Terms of Use
  • Sitemap
  • Trademarks
  • Privacy Policy
  • Terms of Use
  • Sitemap

Copyright © 2016 itechxpert (P) Ltd. All rights reserved.

Copyright © 2016 itechxpert (P) Ltd. All rights reserved.