PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

File uploads

When you allow users to upload files to your website, you are putting yourself at a security risk. While nobody is ever completely safe, here are some precautions you can incorporate to make your site safer.

1. Check the referrer

Check to make sure that the information being sent is from your website. While this information can be faked, it's still a good idea to check.

2. Restrict file types

You can check the mime-type and file extension and only allow certain types to be uploaded.
 
<form enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    File to upload: <input name="uploaded_file" type="file" />
    <input type="submit" value="Upload" />
</form> 
 
// Check that we have a file
if (!empty($_FILES['uploaded_file']) && 
    $_FILES['uploaded_file']['error'] == 0) {

    // Check if the file is a type permited
    $filename = basename($_FILES['uploaded_file']['name']);
    $pathinfo = pathinfo($filename);
    $extension = $pathinfo['extension'];
    
    if (!in_array($extension, 
            array('jpg', 'jpeg', 'gif', 'bmp'))) {
        echo 'File type not permitted';
    }
}
... 7 lines
 

3. Rename files

 
if (!empty($_FILES['uploaded_file']) && 
        $_FILES['uploaded_file']['error'] == 0) {
    $filename = basename($_FILES['uploaded_file']['name']);

    echo $new_filename = uniqid() . "_" . $filename;
        // 502913f491ac3_Chrysanthemum
}
... 1 lines
 

4. Change permissions

Change the permissions on the upload folder so that files within it are not executable.

5. Login and Moderate


Questions    
XSS

        A B C D E F
🔔
1/1