Skip to content
PHP Logo

How can PHP developers integrate file upload functionality into HTML forms effectively and securely?

To integrate file upload functionality into HTML forms effectively and securely, PHP developers can use the $_FILES superglobal to handle file uploads. They should ensure that the form has the enctype attribute set to "multipart/form-data" and validate the file type and size before processing the upload. Additionally, developers should move the uploaded file to a secure directory on the server and generate a unique filename to prevent overwriting existing files.

php
<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload File">
</form>
```

```php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $file = $_FILES["file"];
    
    if ($file["error"] == UPLOAD_ERR_OK) {
        $uploadDir = "uploads/";
        $uploadFile = $uploadDir . uniqid() . "_" . basename($file["name"]);
        
        if (move_uploaded_file($file["tmp_name"], $uploadFile)) {
            echo "File uploaded successfully.";
        } else {
            echo "Error uploading file.";
        }
    } else {
        echo "Error: " . $file["error"];
    }
}
?>