What are some best practices for handling file operations in PHP to ensure security and prevent data loss?

When handling file operations in PHP, it is crucial to validate user input, sanitize data, and set strict permissions on files to prevent security vulnerabilities and data loss. Additionally, always use secure file paths and avoid using user input directly in file operations to avoid path traversal attacks.

// Example of secure file upload function
function uploadFile($file) {
    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($file["name"]);

    // Validate file type, size, and check for errors
    if ($file["error"] == 0 && $file["size"] < 5000000) {
        if (move_uploaded_file($file["tmp_name"], $targetFile)) {
            echo "File uploaded successfully.";
        } else {
            echo "Error uploading file.";
        }
    } else {
        echo "Invalid file.";
    }
}