Skip to content
PHP Logo

What are some best practices for creating a PHP script that allows users to upload files and add comments?

When creating a PHP script that allows users to upload files and add comments, it is important to ensure proper validation and security measures are in place. This includes checking file types, file sizes, and implementing measures to prevent malicious uploads. Additionally, storing file uploads in a secure location and sanitizing user input for comments can help prevent security vulnerabilities.

php
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    
    // Check file type
    $fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    } else {
        // Check file size
        if ($_FILES["fileToUpload"]["size"] > 500000) {
            echo "Sorry, your file is too large.";
        } else {
            // Store file
            move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
            
            // Store comments
            $comment = $_POST["comment"];
            // Sanitize input
            $comment = htmlspecialchars($comment);
            // Store comment in database or file
        }
    }
}
?>