What are the best practices for handling file operations over HTTP in PHP?

When handling file operations over HTTP in PHP, it is important to ensure proper error handling, input validation, and security measures to prevent potential vulnerabilities such as directory traversal attacks. It is recommended to use secure file paths, sanitize user input, and limit file operations to only necessary directories.

// Example of handling file upload over HTTP in PHP
if(isset($_FILES['file'])) {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["file"]["name"]);
    
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}