Skip to content
PHP Logo

What potential security risks are present in the PHP code snippet provided for uploading and displaying user images?

The code snippet provided is vulnerable to file upload attacks as it does not validate the file type or sanitize the file name. To mitigate this risk, file type validation and sanitization of the file name should be implemented before allowing the file to be uploaded and displayed.

php
<?php
// Validate file type
$allowed_types = array('jpg', 'jpeg', 'png', 'gif');
$file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);

if (!in_array($file_extension, $allowed_types)) {
    die("Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.");
}

// Sanitize file name
$filename = preg_replace("/[^a-zA-Z0-9.]/", "", $_FILES['image']['name']);

// Upload file
$upload_dir = 'uploads/';
$upload_file = $upload_dir . $filename;

if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_file)) {
    echo "File uploaded successfully.";
} else {
    echo "File upload failed.";
}

// Display uploaded image
echo '<img src="' . $upload_file . '" alt="Uploaded Image">';
?>