Belajar Upload Image di PHP menggunakan Bootstrap

Akhirnya ada waktu luang sehingga saya bisa menyempatkan untuk menulis lagi, kali ini tulisan saya mengenai Belajar upload image di php menggunakan Bootstrap. Bagi teman-teman yang mungkin membutuhkan script gimana sih cara upload image di PHP?

Nah..sebuah pilihan yang tepat buat teman-teman yang mampir ke blog saya ini.

Sedikit cerita awal mula script Upload Image ini yaitu ketika saya terlibat dalam sebuah project pembuatan website career. Saya pikir alangkah baiknya script ini saya bagikan sehingga dapat dipelajari ataupun dikembangkan oleh teman-teman.

Langkah – Langkah Belajar Upload Image PHP

1. Buat struktur folder di localhost teman-teman seperti ini.

— assets
——- css
——- fonts
——- images
———– uploads
——- js
— include

Penjelasan :
– Folder assets digunakan untuk menaruh file-file css, js, fonts, images, dan uploads
– Folder include digunakan untuk menaruh file php yang akan di include

2. Buat sebuah file php baru dengan nama index.php isikan dengan script dibawah ini :

<!DOCTYPE html>
<html>
<head>
	<title>Upload Image PHP</title>
	
	<!-- Bootstrap Core CSS -->
	<link href="assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/font-awesome.min.css" rel="stylesheet">
<style type="text/css">
#box-container {
	padding: 5px;
}
.btn-file {
    overflow: hidden;
    position: relative;
}
.btn-file input[type=file] {
    top: 0;
    left: 0;
    min-width: 100%;
    min-height: 100%;
    text-align: left;
    opacity: 0;
    background: none;
    cursor: inherit;
    display: block;
    position: absolute;
}
#profile-preview img {
    width: 150px;
    height: 200px;
}
#profile-preview {
	margin-bottom: 10px;
}
.btBtn {
	margin: 10px 0 2px;
}
.box-profile {
	margin: 0 auto;
	padding: 10px;
	background-color: #CCC;
	border: 1px solid grey;
	width: 300px;
}
.box-profile h2 {
	font-size: 20px;
	font-weight: bold;
	margin: 0 0 10px; 
}
</style>
</head>
<body>
<div id="box-container">
	<div class="box-profile">
		<h2 align="center">UPLOAD IMAGE PHP</h2>
		<form action="include/upload_file.php" method="post" enctype="multipart/form-data">
			<div id="profile-preview">
				<img src="assets/images/profile.jpg" alt="profile" class="img-responsive center-block" style="border:1px solid grey;"/>
			</div>
			<div align="center">
				<div class="btn btn-primary btn-file btn-md">
					<i class="glyphicon glyphicon-floppy-open" aria-hidden="true"></i>
					<input id="preview-img" name="preview-img" type="file" onchange="readURL(this);" value=""/>
				</div>
				<button type="button" class="btn btn-danger btn-md btn-remove">
				  <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
				</button>
				<div class="btBtn">
					<input type="submit" class="btn btn-primary" name="submit" value="Submit Button">
				</div>
				<div class="caption">
					<small>Types : .jpg, .jpeg, .png</small><br>
					<small>Max File Size : 1MB</small>
				</div>
			</div>
		</form>
	</div>
</div>

</body>

<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$('#preview-img').on('change',function(){
		$('#profile-preview').find('img').removeAttr('style');
	});
	$(".btn-remove").click(function() {
        var formimage = document.getElementById('preview-img');
        formimage.value = '';
        $('#profile-preview > img').removeAttr("src");
        $('#profile-preview > img').attr('src', 'assets/images/profile.jpg');
		$('#profile-preview').find('img').css({'border':'1px solid grey'});
    });
	
	//Upload Profile Image
    function readURL(input) {
        var fileInput = document.getElementById('preview-img');
        var filePath = fileInput.value;
        var allowedExtensions = /(\.jpg|\.jpeg|\.png)$/i;
        if (!allowedExtensions.exec(filePath)) {
            alert('File type not allowed!!');
            fileInput.value = '';
            return false;
        } else {
            if (input.files && input.files[0]) {
				var filex = input.files[0].size;
				var sizex = (filex/1024).toFixed(2);
				//1000000 MB = 1 MB
				//2000000 MB = 2 MB
				if(filex >= 1000000 ) {
					alert('File size too large!!');
					fileInput.value = '';
					return false;
				}
                var reader = new FileReader();
                reader.onload = function(e) {
                    $('#profile-preview > img').attr('src', e.target.result);
                };

                reader.readAsDataURL(input.files[0]);
            }
        }
    }
</script>
</html>

Penjelasan :
– Function readURL() ini dipanggil ketika tombol upload diklik lalu hanya file .jpg dan .png saja yang bisa diupload, size file yang bisa diupload pun dibatasi hanya 1 MB saja

3. Kemudian copy script dibawah ini lalu simpan dengan nama upload_file.php :

<?php
/*=========================================
 * Simple Upload Image PHP Using Bootstrap
 * Author : iwane.prasetiyo@gmail.com
 * www.tukarpengetahuan.com
 ==========================================*/
 include('imageExists.php');
if(!empty($_REQUEST)){
	
	$uploads_dir = realpath(dirname(__FILE__)."/../assets/images/uploads");
	$tmp_name = $_FILES["preview-img"]['tmp_name'];
	$name = basename($_FILES["preview-img"]['name']);
	
	$path = realpath(dirname(__FILE__)."/../assets/images/uploads") .'/';
	
	//Checking already image and rename if there are same name
	$status = '';
	if(file_exists("$uploads_dir/$name")){
		$updatedFileName = imageExists($name,$path);
		$status .= move_uploaded_file($tmp_name, "$uploads_dir/$updatedFileName");
	}
	else{
		$status .= move_uploaded_file($tmp_name, "$uploads_dir/$name");
	}
	
	if(!empty($status)){
		echo '<script>alert("Success Upload Image!!");</script>';
		echo '<script>window.location.href = "delete.php";</script>';
	}
	else{
		echo '<script>alert("Upload Image Failed!!");<script>';
		echo '<script>window.location.href = "upload_file.php";</script>';
	}
}
?>

4. Buat sebuah function yang digunakan untuk melakukan pengecekkan file yang sama ketika diupload, dan kemudian dilakukan rename pada file tersebut. Silahkan copy script berikut simpan dengan nama imageExists.php :

<?php
	// function to rename file
	function imageExists($image,$dir) {
		$i=1; $probeer=$image;
		while(file_exists($dir.$probeer)) {
			$punt=strrpos($image,".");
			if(substr($image,($punt-3),1) && substr($image,($punt-1),1)) {
				$probeer=substr($image,0,$punt)."".$i."".
				substr($image,($punt),strlen($image)-$punt);
			} else {
				$probeer=substr($image,0,($punt-3))."".$i."".
				substr($image,($punt),strlen($image)-$punt);
			}
			$i++;
		}
		return $probeer;
	}
?>

5. Terakhir buat sebuah file delete.php, copy file dibawah ini :

<?php
/*=========================================
 * Simple Delete Image PHP
 * Author : iwane.prasetiyo@gmail.com
 * www.tukarpengetahuan.com
 ==========================================*/
$html = '';
$html .= '<div style="border:1px solid grey;text-overflow:hidden;width:350px;margin:0 auto;">';
$html .= '	<h2 align="center">DELETE IMAGE PHP</h2><br>';
$html .= '	<div align="center">';
$html .= '		<form method="post" enctype="multipart/form-data">';
$html .= '		<input type="file" name="fileToDownload" value="Search Image">';
$html .= '		<input type="submit" name="submit" value="Delete">';
$html .= '		</form>';
$html .= '		<p align="left" style="margin:30px 5px 0 5px;"><small>*Go to Directory project <strong>"Upload Image PHP"</strong> into <i>assets/images/uploads</i> and select image you want deleted</small></p>';
$html .= '		<p style="margin-top:50px;"><a href="../index.php"><u><< Back to Upload </u></a></p>';
$html .= '	</div>';
$html .= '</div>';
echo $html;
if (isset($_POST['submit'])) {
	$target_dir = realpath(dirname(__FILE__)."/../assets/images/uploads/");
	$fullpath = $target_dir .'/'. basename($_FILES["fileToDownload"]["name"]);
	
	$imagename = basename($_FILES["fileToDownload"]["name"]);
	
	if(file_exists($fullpath)){
		unlink($fullpath);
		echo '<script>alert("'.$imagename.' has been deleted");</script>';
		echo '<script>window.location.href = "delete.php";</script>';
	}
	else {
		echo '<script>alert("Could not '.$_POST['submit'].', file does not exist!!");</script>';
		echo '<script>window.location.href = "delete.php";</script>';
	}
	
}

Berikut tampilan dari Upload Image di PHP

Tampilan awal ketika upload :

upload-image-php
upload-image-php

Tampilan Error Filetype Validation :

error-filetype
error-filetype

Tampilan ketika Error Filesize Validation :

error-filesize
error-filesize

Terakhir tampilan untuk Delete Image :

delete-image-php
delete-image-php

Jika ada kesulitan bisa tanya melalui email, atau bila ingin lihat full source code dari Belajar Upload Image di PHP menggunakan Bootstrap silahkan ke akun github saya.(iwn)

Leave a Reply