0

I am creating my own website at http://harrisonprograms.com and I have a problem on the profile page.

The problem is I have created a PHP script that will upload an image to the server for example the image directory might be Users/whatevertheusername/imagename.png and then add a string reference to it in MySQL on the users MySQL row. However before the script performs this it checks if the file uploaded is an image file using the substring function, I can't post an image because my reputation isn't high enough so here's the code in text

if(isset($_POST['SUBMITFILE2'])){

$imageName = $_FILES['UPLFILE2']['name'];
$imageData = file_get_contents($_FILES['UPLFILE2']['tmp_name']);
$imageType = $_FILES['UPLFILE2']['type'];

//VALIDATE WHETHER FILE IS AN IMAGE OR NOT
if(substr("$imageName", 0, 5) == 'image'){

The thing I can't understand is it used to work and validate if the file was an image or not but now it has stopped working and I don't know why.

3 Answers3

3

So the checking file type by name or extension is not good, because you can easily change it by plain remane function. You can check if uploaded file is an image using e.g. mime type. In php you have function mime_content_type(). Example of usage:

$imageMimeTypes = array(
    'image/png',
    'image/gif',
    'image/jpeg');

$fileMimeType = mime_content_type($_FILES['UPLFILE2']['tmp_name']);

if (in_array($fileMimeType, $imageMimeTypes)) {
    //passed validation 
}

Of course you can define more mime types of images.

marian0
  • 3,336
  • 3
  • 27
  • 37
  • Thank you marian this was very helpful It helped determine if the file was an image or not and now I can add more image types if I like, I also have learnt something about uploading files thank you. – Harrison Pickering Sep 30 '14 at 21:38
0

you can use exif_imagetype to Determine the type of an image

codinglazy
  • 13
  • 4
0

Pretty sure you can find your answer here : php check file extension in upload form

$allowed =  array('gif','png' ,'jpg'); //extension allowed
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
    echo 'error';
}else{
//your extra code...
}
Community
  • 1
  • 1
Sebastien B.
  • 476
  • 3
  • 10
  • Don't see your point, if he only want image format type to be uploaded this will work just fine.. if you take a .txt or a .exe and change the extension to a .png, sure it's will pass but it's will just be a broken png. Now if you can enter on the server change back the extension to .exe then run it, it's another story! – Sebastien B. Sep 30 '14 at 20:50
  • I will try this in a sec but it says my input file is undefined and I know why. – Harrison Pickering Sep 30 '14 at 20:53