WikiGalaxy

Personalize

PHP File Upload

Understanding File Upload in PHP:

PHP provides a convenient way to handle file uploads from a client to a server. The process involves HTML forms and PHP scripts that process the uploaded files.

Creating an HTML Form:

To upload files, you need a form with the <input type="file"> element. Ensure the form's method is set to POST and the enctype attribute is set to multipart/form-data.

Handling File Upload in PHP:

Use PHP's $_FILES superglobal to access file information. You can check for errors, move uploaded files, and validate file types and sizes.

Security Considerations:

Always validate and sanitize file inputs to prevent security vulnerabilities. Restrict file types and sizes to avoid potential risks.


<form action="upload.php" method="post" enctype="multipart/form-data">
  <label for="file">Choose file:</label>
  <input type="file" name="file" id="file">
  <input type="submit" value="Upload">
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["file"]["name"]);
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    // Check file size
    if ($_FILES["file"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg"
    && $fileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // If everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "The file ". htmlspecialchars( basename( $_FILES["file"]["name"])). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>
    

Explanation of Code:

The HTML form allows users to select a file for upload. The PHP script processes the uploaded file, checking for errors and ensuring security measures like file type and size restrictions.

Conclusion:

File uploads in PHP are straightforward but require careful handling to ensure security and functionality. Proper validation and error handling are crucial.

Console Output:

The file example.jpg has been uploaded.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025