// Check if a file is submitted
if (isset($_FILES['file'])) {
// Specify the target directory
$targetDirectory = 'uploads/';
// Build the target file path
$targetFile = $targetDirectory . basename($_FILES['file']['name']);
// Get the file type
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);
// Check if the file type is allowed (e.g., jpg or png)
if ($fileType == 'jpg' || $fileType == 'png') {
// Attempt to move the uploaded file to the target directory
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
echo 'File uploaded successfully!';
} else {
echo 'Error uploading file.';
}
} else {
echo 'Invalid file type.';
}
}
code
File Upload with Type Validation in PHP
This PHP code checks if a file has been submitted, validates its type (allowing only 'jpg' or 'png' files), and then attempts to move the uploaded file to a specified target directory. The comments provide explanations for each part of the code.
File Upload
Validation