I wrote this code to store an image and avoid that someone store a malware or other files different from an image:
$content = file_get_contents($image);
file_put_contents($path, $content);
// Check imagesize to know if it is an image or not:
$sizeimage = getimagesize(dirname(__FILE__)."/".$path);
if($sizeimage[0]<10000){ echo "ok"; }else{ unlink(dirname(__FILE__)."/".$path); }
I tried to insert another files like a CSS file and it store the CSS in the database.
Why ? What is wrong in my code ?
In case the image file is invalid, $sizeimage[0]
returns 0
(check PHP documentation).
Hence, the following statement also validates true
in case the file is no valid image:
if($sizeimage[0]<10000)
Consider using the following statement:
if($sizeimage[0]>0 && $sizeimage[0]<10000)
This only validates true
when getimagesize()
found an image that's smaller then 1000 pixels.
getimagesize will return false
on error. This means that:
$sizeimage = false
$sizeimage[0] = null
null
converts to 0
and 0 < 10000
if($sizeimage[0]<10000){ echo "ok"; }else{ unlink(dirname(__FILE__)."/".$path); }
getimagesize returns false when a file is not an image, but you don't check on that. You use [0], but if that doesn't exist, it becomes "null", which is less than 10000. So:
<?php
if($sizeimage !== false && isset($sizeimage[0]) && $sizeimage[0] < 10000 && $imagesize[0] > 0) {
echo "Okay.";
}
else {
unlink(dirname(__FILE__)."/".$path);
}
Please check file extension. If its not valid extension then don't allow.
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg"))) { echo 'valid file'; }else { echo 'invalid file type';}
To delete a file, use PHP unlink()
I revised your code as follows:
$content = file_get_contents($image);
file_put_contents($path,$content);
// Check imagesize to know if it is an image or not:
$sizeimage = getimagesize(dirname(__FILE__)."/".$path);
if($sizeimage){ echo "ok"; } else { unlink(dirname(__FILE__)."/".$path); }
This should work. The unlink will be executed when $sizeimage is null or false.
There is a better way to really tell if the file is an image by checking it's mime-type. See finfo_file (PHP 4) or finfo (PHP 5).