What are the potential benefits of converting a file upload script into a function in PHP?
Converting a file upload script into a function in PHP can help improve code reusability, readability, and maintainability. By encapsulating the file upload functionality within a function, you can easily call it whenever needed without duplicating code. This approach also allows for easier testing and debugging of the file upload process.
function uploadFile($fileInputName, $uploadDirectory) {
$targetFile = $uploadDirectory . basename($_FILES[$fileInputName]["name"]);
if (move_uploaded_file($_FILES[$fileInputName]["tmp_name"], $targetFile)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
}
// Example usage
if ($_SERVER["REQUEST_METHOD"] == "POST") {
uploadFile("fileInputName", "uploads/");
}