Upload file begitu penting khususnya apliaksi yang berbasis web, karena kita di haruskan untuk upload file, bisa berupa laporan, upload gambar dll. Contoh aplikasi yang membutuhkan upload file seperti manajemen arsip, dimana file pdf data data dokumen bisa di arsipkan.
Buat file upload.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form Upload</title> </head> <body> <form action="upload-manager.php" method="post" enctype="multipart/form-data"> <h2>Upload File</h2> <label for="fileSelect">Nama File:</label> <input type="file" name="photo" id="fileSelect"> <input type="submit" name="submit" value="Upload"> <p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png format yang di perbolehkan maximum 5 MB.</p> </form> </body> </html>
Buat file upload-manager.php
<?php // Check if the form was submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Check if file was uploaded without errors if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){ $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png"); $filename = $_FILES["photo"]["name"]; $filetype = $_FILES["photo"]["type"]; $filesize = $_FILES["photo"]["size"]; // Verify file extension $ext = pathinfo($filename, PATHINFO_EXTENSION); if(!array_key_exists($ext, $allowed)) die("Error: Pilih format file yang cocok."); // Verify file size - 5MB maximum $maxsize = 5 * 1024 * 1024; if($filesize > $maxsize) die("Error: File Terlalu Besar."); // Verify MYME type of the file if(in_array($filetype, $allowed)){ // Check whether file exists before uploading it if(file_exists("upload/" . $filename)){ echo $filename . " File sudah ada."; } else{ move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename); echo "Proses upload berhasil."; } } else{ echo "Error: Terjadi masalah saat upload file. Silahkan ulangi."; } } else{ echo "Error: " . $_FILES["photo"]["error"]; } } ?>
Tags
php