Skip to content
PHP Logo

How can file types be properly validated when uploading avatars in PHP?

When uploading avatars in PHP, file types can be properly validated by checking the file extension against a list of allowed extensions. This helps prevent users from uploading malicious files that could harm the server. Additionally, it is important to validate the file type using PHP's `fileinfo` extension to ensure that the file's actual content matches its extension.

php
// Define allowed file extensions
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');

// Get uploaded file's extension
$uploaded_file_extension = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);

// Validate file extension
if (!in_array($uploaded_file_extension, $allowed_extensions)) {
    echo "Invalid file type. Please upload a JPG, JPEG, PNG, or GIF file.";
    exit;
}

// Validate file type using fileinfo extension
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$uploaded_file_type = finfo_file($finfo, $_FILES['avatar']['tmp_name']);
finfo_close($finfo);

if (!in_array($uploaded_file_type, array('image/jpeg', 'image/png', 'image/gif'))) {
    echo "Invalid file type. Please upload a JPG, JPEG, PNG, or GIF file.";
    exit;
}

// Process file upload
// Your code to move the uploaded file to the desired location