Description
Storing an upload under the submitted filename without checking its contents can admit unintended file types.
Potential impact
A matching name can overwrite an existing file. A public upload can distribute malicious content, and a server that executes uploaded scripts may run their code.
Remediation
Limit the size and check the content and MIME type against an allow-list. Choose the storage name and allowed extension on the server. Configure the web server to prevent execution in the upload directory.
Examples
Before
<?php
$target = 'uploads/' . basename($_FILES['uploaded']['name']);
move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
After
<?php
if ($_FILES['uploaded']['error'] === UPLOAD_ERR_OK
&& mime_content_type($_FILES['uploaded']['tmp_name']) === 'image/png') {
$target = '/var/app/uploads/' . bin2hex(random_bytes(16)) . '.png';
move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
}
basename() leaves the final filename under the client’s control. The revised handler moves a successful upload to a random .png name only if the server detects image/png. Validate the full PNG format, handle move_uploaded_file() failure, and configure /var/app/uploads/ to prevent execution.