How can one handle different file types, such as *.txt or *.doc, when uploading files in PHP?
When uploading files in PHP, you can handle different file types by checking the file extension before allowing the upload. You can use the `pathinfo()` function to retrieve the file extension and then compare it against a list of allowed extensions. If the file extension matches one of the allowed types, you can proceed with the upload; otherwise, you can display an error message to the user.
$allowedExtensions = array('txt', 'doc');
$fileName = $_FILES['file']['name'];
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
if(in_array($fileExtension, $allowedExtensions)){
// Proceed with the file upload
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $fileName);
echo 'File uploaded successfully.';
} else {
echo 'Invalid file type. Only .txt and .doc files are allowed.';
}
Keywords
Related Questions
- Are there any specific considerations or recommendations for handling URLs and special characters in XML files when working with PHP?
- How can PHP be used to differentiate between admin and user functions on a website?
- How can PHP mailer classes like PHPMailer be utilized to send HTML emails with customized links and parameters for user interaction?