Your most secure way of uploading files in php?

Discussion in 'PHP' started by eritrea1, Jul 21, 2012.

  1. #1
    Hi Guys,
    I am making a file upload script and actually found this one somewhere and though if it is secure enough, if not how would you make it more secure?


    
    
    if ($_FILES)
    {
    $temp_file = $_FILES['ufile']['tmp_name'];
     $upload_dir = "uploads";
    $name = $_FILES['ufile']['name'];
    switch($_FILES['ufile']['type'])
    {
    case 'image/jpeg': $ext = 'jpg'; break;
    case 'image/gif': $ext = 'gif'; break;
    case 'image/png': $ext = 'png'; break;
    case 'image/tiff': $ext = 'tif'; break;
    default: $ext = ''; break;
    }
    if ($ext)
    {
    $n = "$pic_name.$ext";
    move_uploaded_file($temp_file, $upload_dir."/". $n);
    echo "Uploaded image <img src='uploads/$pic_name.$ext'/> as '$n':<br />";
    
    
    }
    else echo "'$name' is not an accepted image file";
    }
    else echo "No image has been uploaded";
    
    
    ?>
    
    
    
    Code (markup):
    And, this would be the HTML form


    
    <form enctype="multipart/form-data" action="upload_photo.php" method="post">
        <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
        Choose a file to upload: <input name="ufile" type="file" />
        <input type="submit" value="Upload" />
      </form> 
    
    Code (markup):
     
    eritrea1, Jul 21, 2012 IP
  2. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #2
    It depends on what you mean by "secure".

    I would change:

    
    if($_FILES)
    
    Code (markup):
    to

    
    if(!empty($_FILES))
    
    Code (markup):
    First of all because the first compares $_FILES to true, which is not the best way.

    There also needs to be verification of the image's size.
     
    BRUm, Jul 21, 2012 IP