So I have have this script for uploading an image to a server. It allows jpg and png and renames the file to a random 6 digit number.
<?php
if (isset($_FILES['file'])) {
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array(
'jpg',
'png'
);
if (in_array($file_ext, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 10000000) {
$file_name_new = mt_rand(100000, 999999) . '.' . $file_ext;
$file_destination = 'files/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
echo "<a href='$file_destination'>$file_name_new</a>";
}
}
}
}
}
?>
Everything works great. It only allows files with the specified extension .jpg and .png.
Where I run into problems is you are able to rename a txt file such as script.txt to script.txt.jpg and the server will allow it, but it's not actually an image. This offers vulnerability to an attack.
Is there something I can add that will actually verify that the file being uploaded is an image? I heard something about getimagesize but i'm not sure. I'm pretty new to php.