How to protect file upload in php against shell script

0

How can I protect sending files with php against shell script, knowing that I only accept one type of extension.

    
asked by anonymous 28.10.2016 / 03:35

1 answer

3

Instead of checking the extension you can check the content using the PHP API called fileinfo , as I showed in this response link

  

Note that in PHP5.3 (although rare some servers still use it) we did not have Fileinfo , but we had mime_content_type (in the documentation it does not speak if it is deprecated), then I put it as fallback, if a function if it is available it uses it, if it does not try the older one, however both always see enabled.

Example:

<?php

function mimeType($file)
{
    $mimetype = false;

    if (class_exists('finfo')) {//PHP5.4+
        $finfo     = finfo_open(FILEINFO_MIME_TYPE);
        $mimetype  = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {//php5.3 ou inferiror
        $mimetype = mime_content_type($file);
    }

    return $mimetype;
}

//Libere aqui os tipos permitidos
$validos = array( 'image/jpeg', 'image/png', 'image/gif', 'text/plain' );

$location = 'uploads/';
$arquivo = $_FILES['file'];

if ($arquivo) {
    $name = $arquivo['name'];
    $tmp_name = $arquivo['tmp_name'];

    if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        echo 'Erro ao fazer o upload:', $error;
    } else {
        //Pega o mimetype
        $mimeType = mimeType($tmp_name);

        //Checa o mimetype com o array
        if (!in_array($mimeType, $validos)) {
            echo 'Formato de arquivo invalid';
        } elseif (move_uploaded_file($tmp_name, $location . $name)) {
            echo 'Upload completo';
        }
    }
}
    
28.10.2016 / 03:44