Upload dan Hapus Foto Pada PHP

Berikut ini script Unggah dan Hapus File Gambar, script ini memungkinkan kita untuk mengupload image atau file gambar ke sebuah direktori yang kita definisikan, sekaligus script untuk menghapus image/file gambar yang sudah tidak diperlukan lagi.
Silahkan simak script dibawah ini, silahkan amati, tiru dan modifikasi :
File koneksi.php
<?php
$host="localhost";
$user="root";
$pass="";
$db="<nama databasemu>";
$koneksi=mysql_connect($host,$user,$pass) or die ("tidak dapat melakukan koneksi".mysql_error());
$konekdb=mysql_select_db($db) or die ("Database tidak ditemukan".mysql_error());
?>
Kemudian, buat file index.php untuk mengupload dan menampilkan daftar gambar-gambar yang telah diupload,
<?php
include "koneksi.php";
echo " <table align=center border=0 cellpadding=5 bordercolor=#FFFFFF bgcolor=#99CC00 width=300>
<tr width=15><th>No</th>
<th width=150>Gambar</th>
<th >Aksi</th>
</tr>";
$tampil=mysql_query("SELECT * FROM gambar ORDER BY id_image");
echo "<h4 align=center><a href=input.php>Tambah Gambar</a></h2>";
$no=1;
while ($data=mysql_fetch_array($tampil)){
echo "<tr bgcolor= #FFFFFF><td align=center >$no</td>
<td>$data[nama_image]</td>
<td><a href=\"hapus.php?id=$data[id_image]&namafile=$data[image]\" onClick=\"return confirm('Apakah Data -:: $data[nama_image] ::- benar-benar akan Dihapus?')\">Hapus</a></td>
</tr>";
$no++;
}
echo "</table>";
?>
Selanjutnya, buat script proses_upload.php untuk mengeksekusi query unggah file foto seperti dibawah ini :
<?php
include "koneksi.php";
$lokasi_file = $_FILES['fupload']['tmp_name'];
$tipe_file = $_FILES['fupload']['type'];
$nama_file = $_FILES['fupload']['name'];
$direktori = "image/$nama_file";
if (!empty($lokasi_file)) {
move_uploaded_file($lokasi_file,$direktori);
if ($tipe_file != "image/jpeg" AND $tipe_file != "image/pjpeg"){
echo " ";
}
else{
mysql_query("INSERT INTO gambar(nama_image,
image)
VALUES('$_POST[nama_image]',
'$nama_file')");
header('location:tampil.php');
}
}
else{
mysql_query("INSERT INTO gambar(nama_image,)
VALUES('$_POST[nama_image]')");
header('location:tampil.php');
}
?>
Selanjutnya, buat script aksi hapus.php untuk menghapus file foto seperti dibawah ini :
<?php
include "koneksi.php";
$hapus=mysql_query("DELETE FROM gambar WHERE id_image='$_GET[id]'");
unlink("image/$_GET[namafile]");
header('location:index.php');
?>
Selanjutnya, buat script tampil.php untuk menampilkan file foto seperti dibawah ini :
<?php
$gambar=mysql_query("SELECT * FROM gambar ORDER BY id_image DESC LIMIT 0,30");
while($b=mysql_fetch_array($gambar)){
echo "<td align=center>
<img src='image/$b[image]' border='0'></td>";
}
?>
Selesai deh silahkan dicoba,semoga berhasil!!!
Jangan lupa, buat folder image yang letaknya berada didalam folder yang sama dengan koneksi.php, tampil.php, hapus.php dan index.php. Demikian sobat Terimakasih

0 Response to "Upload dan Hapus Foto Pada PHP"

Posting Komentar