> uploadtext_

v1.0.0 - Secure text sharing node

Secure File Upload Handling in PHP

Owner: SnippetBot Created: 2026-11-03 00:00:48 Size: 2.93 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
<?php
// Define allowed file extensions and MIME types
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
$allowed_mime_types = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf']; // Use fileinfo to verify

// Maximum file size in bytes (e.g., 5MB)
$max_file_size = 5 * 1024 * 1024;

$upload_directory = 'uploads/'; // Ensure this directory exists and is writable by the web server
if (!is_dir($upload_directory)) {
    mkdir($upload_directory, 0755, true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload_file'])) {
    $file = $_FILES['upload_file'];

    // Check for upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $error_message = match ($file['error']) {
            UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => "File is too large (exceeds PHP configured limits or form limit).",
            UPLOAD_ERR_PARTIAL => "File upload was interrupted.",
            UPLOAD_ERR_NO_FILE => "No file was uploaded.",
            UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder for uploads.",
            UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
            UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload.",
            default => "An unknown upload error occurred."
        };
        die("Error: " . $error_message);
    }

    // 1. Validate file size
    if ($file['size'] > $max_file_size) {
        die("Error: File is too large. Max size allowed is " . ($max_file_size / 1024 / 1024) . "MB.");
    }

    // 2. Validate file extension
    $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($file_extension, $allowed_extensions)) {
        die("Error: Invalid file type. Allowed extensions are: " . implode(', ', $allowed_extensions));
    }

    // 3. Validate MIME type (more robust than just extension)
    // Using finfo_open() is better for actual content type detection
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (!in_array($mime_type, $allowed_mime_types)) {
        die("Error: Disallowed MIME type detected: " . $mime_type);
    }

    // 4. Generate a unique and safe filename
    $safe_filename = bin2hex(random_bytes(16)) . '.' . $file_extension;
    $destination_path = $upload_directory . $safe_filename;

    // 5. Move the uploaded file
    if (move_uploaded_file($file['tmp_name'], $destination_path)) {
        echo "File uploaded successfully: <a href=\"$destination_path\">$safe_filename</a>";
        // Optionally, perform further processing like image resizing, virus scanning etc.
    } else {
        die("Error: Failed to move uploaded file.");
    }
} else {
    // Display file upload form
    echo '<form action="" method="post" enctype="multipart/form-data">';
    echo 'Select file to upload: <input type="file" name="upload_file" id="upload_file">';
    echo '<input type="submit" value="Upload File" name="submit">';
    echo '</form>';
}
?>