Iklan 728x90

Memahami Script PHP untuk Upload File



Mungkin ada pertanyaan yang sering di tanyakan bagaimana cara membuat script php untuk upload file, upload merupakan proses mengirimkan file dari client ke server menggunakan protokol tertentu sehingga file bisa di kirimkan ke server. Besar file yang bisa di upload biasanya ada pengaturan di file php.ini dari sini kita bisa mengatur maximum file yang bisa di upload. Kami tidak membahas untuk konfigurasi file php.ini yang kami bahas adalah pembuatan script untuk upload file.

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"];
    }
}
?>


Post a Comment

0 Comments