Skip to content
PHP Logo

In what scenarios would it be preferable to limit the file extensions of uploaded images in PHP, and how can this be implemented effectively?

Limiting file extensions of uploaded images in PHP is preferable in scenarios where security is a concern, as it helps prevent malicious files from being uploaded to the server. This can be implemented effectively by checking the file extension of the uploaded file against a whitelist of allowed extensions before moving the file to its final destination.

php
$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);

if (!in_array($ext, $allowedExtensions)) {
    // File extension not allowed, handle error or reject the file
} else {
    // Move the file to its final destination
}