What is the purpose of passing an upload to a function in PHP?
When passing an upload to a function in PHP, the purpose is to handle the uploaded file within the function, such as moving it to a specific directory, checking its file type, size, or performing any other necessary operations on the file.
// Example of passing an uploaded file to a function in PHP
function handleUpload($file) {
$targetDir = "uploads/";
$targetFile = $targetDir . basename($file["name"]);
// Move the uploaded file to the target directory
if (move_uploaded_file($file["tmp_name"], $targetFile)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
}
// Usage
if ($_FILES["fileToUpload"]["error"] == UPLOAD_ERR_OK) {
handleUpload($_FILES["fileToUpload"]);
}