In what ways can PHP be used to validate file extensions and prevent users from uploading potentially harmful files, such as executable PHP files disguised as images?

To prevent users from uploading potentially harmful files, such as executable PHP files disguised as images, PHP can be used to validate file extensions. This can be done by checking the file extension against a list of allowed extensions and rejecting any files that do not match. Additionally, PHP can also check the file's MIME type to further validate its content.

$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
$allowedMimeTypes = array('image/jpeg', 'image/png', 'image/gif');

$uploadedFile = $_FILES['file'];
$fileName = $uploadedFile['name'];
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
$fileMimeType = mime_content_type($uploadedFile['tmp_name']);

if (!in_array($fileExtension, $allowedExtensions) || !in_array($fileMimeType, $allowedMimeTypes)) {
    // File extension or MIME type is not allowed, reject the file upload
    echo "Invalid file type. Please upload a valid image file.";
} else {
    // File is safe to upload
    move_uploaded_file($uploadedFile['tmp_name'], 'uploads/' . $fileName);
    echo "File uploaded successfully.";
}