How to rename file uploaded in CodeIgniter?

Hello, friends today we will learn how to rename or change the file name of uploaded files in CodeIgniter.
If you are going to add time as the prefix of the file name along with the original name when uploading, but you couldn’t figure it out. Then this tutorial will be very helpful for you.

Step 1. Create a view named image.php. in it copy and paste below code and save it to application/view/

<?php
/*
	Author: Dinesh Sharma
	Description: file Rename while uploading in codeigniter
	Website: http://www.phpglossary-com-296797.hostingersite.com/
*/
defined('BASEPATH') OR exit('No direct script access allowed');
$this->load->helper('url');
?>
<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>File upload</title>
	<meta name="viewport" content="width=device-width, initial-scale=1" />
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
	<div class="col-md-3"></div>
	<div class="col-md-6">
		<?php if(isset($msg)){echo $msg;}?>
		<form method="post" enctype="multipart/form-data">
			<div class="form-group">
				<label>Select File</label>
				<input class="form-control" type="file" name="image" />
			</div>
			<div class="form-group">
				<input class="btn btn-primary" type="submit" value="Upload File" />
			</div>
		</form>
	</div>
	<div class="col-md-3"></div>
</div>
</body>
</html>

Step 2. Create a controller called image.php. in it copy and paste below code and save it to application/controllers/

<?php /*
		Author: Dinesh Sharma
		Description:File rename while uploading in codeigniter
		Website: http://www.phpglossary-com-296797.hostingersite.com/
	*/
 
 defined('BASEPATH') OR exit('No direct script access allowed');
 
  class Image extends CI_Controller {
      
      function __construct() {
          parent::__construct();
      }

      public function index()
			{
			    if($this->input->post('uploadImage'))
			    {
			        $image = time().'-'.$_FILES["image"]['name'];

			        $config = array(
			        'upload_path' => "./uploads/",
			        'allowed_types' => "gif|jpg|png|jpeg|JPEG|JPG|PNG|GIF",
			        'overwrite' => TRUE,
			        'max_size' => "99999999999",
			        'max_height' => "600",
			        'max_width' => "800",
			        'file_name' => $image
			        );
			        $this->load->library('upload', $config); 

			        if($this->upload->do_upload('image'))
			        {
			            $res['msg']="Image has been uploaded!";
			            $this->load->view('image', $res);
			        }
			        else
			        {
			            $this->load->view('image');
			        }
			    }
			}
	}
?>

 

Leave a Comment

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

Scroll to Top