Home » Codeigniter,PHP » Upload Image File Random Name Codeigniter

Upload Image File Random Name Codeigniter

Published by Ade Kurniawan on

Upload foto di codeigniter memiliki kemudahan dengan mengunakan libraries upload. Sebelum melakukan upload image tentu terlebih dahulu kita harus memiliki database. disini database yang digunakan adalah indonetsource dan terdiri atas tabel admin yang akan di isi dengan nama dan foto. Baiklah untuk membuat upload foto dengan codeigniter ini silahkan ikuti langkah – langkah berikut :

Upload Image Codeigniter

1. Buatlah tabel dengan nama tabel admin

CREATE TABLE admin (
id_admin int(11) NOT NULL AUTO_INCREMENT,
level enum(‘Admin’) NOT NULL,
nama varchar(50) NOT NULL,
foto varchar(255) NOT NULL,
PRIMARY KEY (id_admin)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1

Tabel di atas terdiri atas 4 kolom hal terpenting adalah dengan mengalokasikan kolom foto yang akan diisi nantinya dengan nama file image random seperti img_JtRrw8z3kFWeLcg.jpg

2. Buatlah directory upload path di project codeigniter

Directory upload path adalah directory yang akan dijadikan tempat penyimpanan image nantinya ketika upload image berhasil dilakukan. Untuk membuat directory ini silahkan masuk ke project disini nama projectnya indonetsource dan buat new folder beri nama foto.

indonetsouce->foto

3. Membuat script upload image

Setelah memiliki tabel dan folder maka hal berikutnya yang harus dilakukan untuk membuat upload image codeigniter ini adalah dengan menyelesaikan pengkodingan Model, View dan Controller.

Buka directory model dan buat file M_upload.php

<?php 
class M_upload extends CI_Model{

	public function input($table,$data) {
		return $this->db->insert($table,$data);
	}

	public function get_admin(){
		$this->db->select('*');
		$this->db->from('admin');		
		return $this->db->get();
	}
}

Model M_upload terdiri atas 2 function yaitu function input sebagai function untuk memasukkan data ke database dan function get_admin untuk menampilkan data dari tabel admin.

Bukalah directory Controller dan buat file Upload_image.php

<?php 
class Upload_image extends CI_Controller{
	
	function __construct()
	{
		parent::__construct();	
		$this->load->model('m_upload');
	}
 
	public function index()
	{
		$data['data_admin'] = $this->m_upload->get_admin()->result();
		$this->load->view('view_upload',$data);
	}

	public function upload_foto()
	{
			$config['upload_path'] 		= './foto/';
	        $config['allowed_types'] 	= 'jpg|png|jpeg';
	        $config['max_size'] 		= '5000';
	        $config['max_width']  		= '10000';
	        $config['max_height']  		= '10000';
	        $config['overwrite'] 		= TRUE;
	        $this->upload->initialize($config);
	        $dataupload = array();
	        $rand = random_string('alnum', 15);
	        foreach($_FILES as $field => $file)
	        {
	            // No problems with the file
	            if($file['error'] == 0)
	            {
	                // So lets upload
	                if ($this->upload->do_upload($field))
	                {	
	                    $data = $dataupload[$field] = $this->upload->data();
	                    foreach ($dataupload as $key => $value) {	                    	
							if(isset($value['file_name']))
							{
								$data[$key] = $value['file_name'];
								$this->load->library('image_lib');
							    $config_crop['image_library'] 	= 'gd2';
							    $config_crop['source_image'] 	= './foto/'.$data[$key].'';
							    $config_crop['maintain_ratio'] 	= FALSE;
							    $config_crop['create_thumb'] 	= FALSE;
							    $config_crop['new_image'] 		= './foto/img_'.$rand.'.jpg';
							    $config_crop['quality'] 		= "60%";
								//Set cropping for y or x axis, depending on image orientation
								if ($value['image_width'] > $value['image_height']) 
								{
								    $config_crop['width'] = $value['image_height'];
								    $config_crop['height'] = $value['image_height'];
								    $config_crop['x_axis'] = (($value['image_width'] / 2) - ($config_crop['width'] / 2));
								}
								else 
								{
								    $config_crop['height'] = $value['image_width'];
								    $config_crop['width'] = $value['image_width'];
								    $config_crop['y_axis'] = (($value['image_height'] / 2) - ($config_crop['height'] / 2));
								}

							    $this->image_lib->initialize($config_crop);
							    $this->image_lib->crop();
								$this->image_lib->clear();
							}
							else
							{
								$data[$key] = "";
							}
						} 
	                }
	                else
	                {
	                    $this->form_validation->set_message('_file[]', $this->upload->display_errors());
	                    echo"<script>alert('Format file upload tidak sesuai. Silahkan ulangi kembali.'); window.history.back();</script>";
	            		return FALSE;
	                }
	            }
	        }	

	        $data = array('nama' => $this->input->post('nama'));   	        
			  foreach ($dataupload as $key => $value) {
			  	 // echo $value['file_name'];
				if(isset($value['file_name']))
				{
					$data[$key] = 'img_'.$rand.'.jpg';
				}
				else
				{
					$data[$key] = "";
				}
			}
			
			$this->m_upload->input('admin',$data);           
			redirect(''.base_url().'upload_image');
	}
}

Controller Upload_image merupakan bagian yang berperan besar dalam pembuatan format rand dan proses do upload dapat di lihat image file yang di upload dari view di ambil oleh controller melalui function upload_foto dengan fugsi $_FILES. function upload_foto melakukan initialize($config) jika initialiaze berhasil maka selanjutnya file dilakukan resize image dan selanjutnya diberi unik name dengan format rand.

Langkah terakhir buatlah view_upload.php di directory views

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

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="icon" href="<?=base_url()?>/bootstrap/images/indonetsource.ico" type="image/gif">
     <link rel="stylesheet" href="<?php echo base_url('bootstrap/font-awesome/css/font-awesome.min.css')?>" >        
    <link href="https://fonts.googleapis.com/css?family=Nunito:400,600|Open+Sans:400,600,700" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo base_url('bootstrap/css/easion.css');?>">    
    <script src="<?php echo base_url('bootstrap/js/chart-js-config.js')?>"></script>
    <title>Indonetsource - Upload foto Codeigniter</title>
</head>

<body>
    <div class="dash">
        <div class="dash-nav dash-nav-dark">
            <header>
                <a href="#" class="menu-toggle">
                    <i class="fa fa-bars"></i>
                </a>
                <a href="https://www.indonetsource.com/" class="easion-logo" ><img width="30px" src="<?php echo base_url('bootstrap/images/indonetsource.png') ?>"><span>&nbspIndonetsource</span></a>
            </header>
            <nav class="dash-nav-list">
                <a href="https://www.indonetsource.com/upload-image-file-random-name-codeigniter/" class="dash-nav-item">
                    <i class="fa fa-home"></i> Dashboard </a>
                <div class="dash-nav-dropdown">
                    <a href="#" class="dash-nav-item dash-nav-dropdown-toggle">
                        <i class="fa fa-server"></i> Example</a>
                    <div class="dash-nav-dropdown-menu">
                        <a href="<?php echo base_url('upload') ?>" class="dash-nav-dropdown-item">Upload</a>
                    </div>
                </div>
            </nav>
        </div>
        <div class="dash-app">
            <header class="dash-toolbar">
                <a href="#" class="menu-toggle">
                    <i class="fa fa-bars"></i>
                </a>
                <a href="#!" class="searchbox-toggle">
                    <i class="fa fa-search"></i>
                </a>
                <form class="searchbox" action="#!">
                    <a href="#!" class="searchbox-toggle"> <i class="fa fa-arrow-left"></i> </a>
                    <button type="submit" class="searchbox-submit"> <i class="fa fa-search"></i> </button>
                    <input type="text" class="searchbox-input" placeholder="type to search">
                </form>
                <div class="tools">
                    <a href="#!" class="tools-item">
                        <i class="fa fa-bell"></i>                        
                    </a>
                    <div class="dropdown tools-item">
                        <a href="#" class="" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fa fa-user"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenu1">
                            <a class="dropdown-item" href="#">hello...!!</a>
                        </div>
                    </div>
                </div>
            </header>
            <main class="dash-content">
                <div class="container-fluid">
                    <div class="card easion-card">
                        <div class="card-header">
                            <div class="easion-card-icon">
                                <i class="fa fa-edit"></i>
                            </div>
                            <div class="easion-card-title"> Input Admin </div>
                        </div>
                        <div class="card-body">
                            <form action="upload_image/upload_foto" method="post" enctype="multipart/form-data">
                                <div class="form-group">
                                    <label for="">Nama Admin</label>
                                    <input type="text" name="nama" class="form-control col-sm-4"  placeholder="Nama Admin">
                                </div>
                                <div class="form-group">                                            
                                    <input  type="file" name="foto"/>                                            
                                </div>                                        
                                <button type="submit" class="btn btn-primary  btn-sm submit-reset">Simpan </button>                                                
                            </form>
                        </div>

                        <div class="card-header">
                            <div class="easion-card-icon">
                                <i class="fa fa-edit"></i>
                            </div>
                            <div class="easion-card-title"> Data Admin </div>
                        </div>
                        <div class="card-body">
                           <table class="table table-bordered">
                               <tr>
                                   <th>No</th>
                                   <th>Nama</th>
                                   <th>Nama Foto Unik Fungsi Random</th>
                                   <th>File foto</th>
                               </tr>
                               <?php 
                                $no = 1;
                               foreach ($data_admin as $key ): ?>
                                <tr>
                                    <td><?php echo $no++ ?></td>
                                    <td><?php echo $key->nama; ?></td>
                                    <td><?php echo $key->foto; ?></td>
                                    <td><img width="80px" src="<?php echo base_url('foto/').$key->foto; ?>"></td>
                                </tr>
                               <?php endforeach ?>
                           </table>
                        </div>
                     </div>
                </div>
            </main>
        </div>
    </div>
    <script src="<?php echo base_url('bootstrap/js/jquery-3.3.1.slim.min.js')?>" ></script>
    <script src="<?php echo base_url('bootstrap/js/popper.min.js')?>"></script>
    <script src="<?php echo base_url('bootstrap/js/bootstrap.min.js')?>"></script>
    <script src="<?php echo base_url('bootstrap/js/easion.js')?>"></script>
</body>

</html>

Setelah menyelesaikan cara upload foto codeigniter dengan random name di atas maka silahkan di tes di browser dengan mengakses url http://localhost/indonetsouce/upload_image

Demikian tutorial cara upload dan rename file upload codeigniter Jika berhasil maka hasilnya akan sama seperti demo upload foto codeigniter berikut:


0 Comments

Leave a Reply

Avatar placeholder

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