Home > Dev > PHP Security > File Upload Security

File Upload Security

This code ensures secure file uploads by validating the file type and size.

function secure_file_upload($file) {
    $allowed_types = array('image/jpeg', 'image/png', 'application/pdf');
    $max_size = 2 * 1024 * 1024; // 2 MB

    if (in_array($file['type'], $allowed_types) && $file['size'] <= $max_size) {
        $upload_dir = '/path/to/uploads/';
        $file_path = $upload_dir . basename($file['name']);
        if (move_uploaded_file($file['tmp_name'], $file_path)) {
            return $file_path;
        }
    }
    return false;
}

// Usage example
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $uploaded_file = secure_file_upload($_FILES['userfile']);
    if ($uploaded_file) {
        echo 'File uploaded successfully: ' . $uploaded_file;
    } else {
        echo 'File upload failed';
    }
}
Back