Ini adalah skrip mudah bagaiman membina borang yang mengandungi fungsi upload (gambar / dokumen).
Sediakan satu fail contohnya : upload.php
<form method="post" action="" enctype = "multipart/form-data">
<div class="form-group">
<label>Nama *</label>
<input name="nama" class="form-control" type="text" placeholder="Masukkan nama" required>
</div>
<div class="form-group">
<label>Photo format (jpg, png, gif)*</label>
<input name="gambar" type="file" required accept=".jpg,.png,.gif">
</div>
<hr>
<input name="act" type="hidden" value="add">
<button class="btn btn-primary" type="submit">Submit</button>
</form>
di bahagian atas borang ini masukkan kod berikut:
<?PHP
$act = (isset($_POST['act'])) ? trim($_POST['act']) : '';
$nama = (isset($_POST['nama'])) ? trim($_POST['nama']) : '';
if($act == "add")
{
// -------- Attachment -----------------
if(isset($_FILES['gambar'])){
$file_name = $_FILES['gambar']['name'];
$file_size = $_FILES['gambar']['size'];
$file_tmp = $_FILES['gambar']['tmp_name'];
$file_type = $_FILES['gambar']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['gambar']['name'])));
$extensions= array("jpg","png","gif");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPG, PNG or GIF file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
print "<script>alert('Successfully Add!.'); self.location='simple.php';</script>";
}else{
print_r($errors);
}
}
}
?>
Sila bina satu folder bernama uploads . Semua gambar yang diupload kan dimasukkan ke dalam folder tersebut.
Leave a Reply