Set maximum upload size for PHP

Asked

Viewed 1,135 times

0

I have in a certain area of the system a form to uplevel images movies and music, this part usually only appears to administrator, but now it will be released to some types of users, I wanted to know how I do to determine the maximum size of the files, and how long it is safe not to flood the server, audio I wanted at most 4 minutes, videos at most 2 minutes for images I have no idea, the code I made

  1. I want to set the maximum upload size
  2. I need to add some more detail for security?
  3. I looked it up and found $_FILES['arquivo']['size'] but I didn’t understand how to use, how I define the sizes, whether it is in 2M equal in php.ini or if I have to put the exact number type 2048
  4. The code is good like this?

IF(isset($_POST['btnenviar'])){
    if(isset($_FILES['arquivo'])){
        date_default_timezone_set("Brazil/East"); //Definindo timezone padrão
        $ext = strtolower(substr($_FILES['arquivo']['name'],-4)); //Pegando extensão do arquivo
        $novo_nome = "picture". rand(0,9999) . $ext; //Definindo um novo nome para o arquivo
        if(substr($novo_nome, -4) == '.jpeg' || substr($novo_nome, -3) == 'jpg' || substr($novo_nome, -3) == 'png' || substr($novo_nome, -3) == 'gif'){
            $resultado = TRUE;
        if($resultado == TRUE){
            $dir = 'arquivos/picture/'; //Diretório para uploads
            move_uploaded_file($_FILES['arquivo']['tmp_name'], $dir.$novo_nome); //Fazer upload do arquivo
            echo "✔Imagem Inserida!";
        }else{
            echo "erro critico entre em contato com administrador do sistema";
        }

        }else{
            echo "✖ Impossivel, extensão invalida!";
        }
    }
} else {
    echo 'teste';
}
  • 1

    About the central question I will not know how to help, but about how to improve: 1 - Not always the extension will be the last 4 characters, I advise to use $path_info = pathinfo($_FILES['arquivo']['tmp_name']); $ext = $path_info['extension']; to catch. 2 - The name with a Random has many chances to repeat itself and end up overwriting the file. Use time() it returns a UNIXTIMESTAMP that will be unique.

  • about Rand I don’t use it in the system, I just put it in the code so you can test, actually at the time of uploading the image I register it in the database, and her new id is always the database id, so never repeat, I’ll take a look at the thankssss path_info

1 answer

1


About the maximum file size, it should be done like this:

Configuration of the directive upload_max_filesize PHP, in the file php.ini (remember that the value is measured in bytes). See more details on documentation.

Create, also, one input invisible before the input of the archive setting the maximum size:

<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input name="userfile" type="file" />

Know that the input is scammable. Its purpose is to simply notify the user before to start file transfer. Otherwise and the file is larger than the one configured in the directive, the transfer will be stopped only when it reaches the limit set in the directive. What ends up not being interesting to users... See more details on documentation.

"- audio i wanted at most 4 minutes, videos at most 2 minutes for images i have no idea"

To limit itself based on the duration of the video/audio, the file must already be on the server for then PHP, with some library, check its duration. Of course, that’s not good practice either. The client would have to "up" the entire file for this check and, if it is large, the server would discard the entire file (I would be angry!). If it’s really interesting to you, this validation should be done directly on the client and, who knows, redo it on the server...

"- I need to add some more detail for security?"

It’s always good to take security measures. Such as limiting only "acceptable" extensions to your site by attribute Accept in the input:

<input name="userfile" type="file" accept=".jpg, .png, .gif, .mp3, .wma" />

Of course you also need to validate from the server side...

"- found $_FILES['arquivo']['size'] but I didn’t understand how to use"

When you "Upa" the file, PHP receives its information in associative array $_FILES.

$_FILES['arquivo']['size'] is the size, in bytes, of the received file. Remember that in this case, the file is already on the server. More details on documentation.

"- The code is good like this?"

Good concept is very relative! But I’ll show you my version of your code (untested):

<?php
// Extensões aceitáveis
$ext_ac = array(
    '.jpg',
    '.jpeg',
    '.png',
    '.gif'
);

//Diretório para uploads
$dir = 'arquivos/picture/';


if (
    !empty($_POST['btnenviar'])
    && !empty($_FILES['arquivo'])
    // Tem uma extensão
    && preg_match('/(\.[\w]+)$/', $_FILES['arquivo']['name'])
) {
    date_default_timezone_set("Brazil/East"); //Definindo timezone padrão

    //Pegando extensão do arquivo
    $ext = strtolower(
        preg_replace(
            '/.+(\.[\w]+)$/',
            '$1',
            $_FILES['arquivo']['name']
        )
    );

    if (in_array($ext, $ext_ac)) {
        //Definindo um novo nome para o arquivo
        //$novo_nome = "picture". rand(0,9999) . $ext;
        $novo_nome = (
            'picture_'
            .date('YmdHis')
            .md5(date('U'))
            .$ext
        );

        //Mover e renomear o arquivo
        move_uploaded_file(
            $_FILES['arquivo']['tmp_name'],
            $dir.$novo_nome
        );

        echo "✔Imagem Inserida!";
    } else
        echo "✖ Extensão não aceitável!";
} else
    echo 'teste';
  • Thank you very much, now I have some items that you passed to study, I usually do the checking of inputs with tokens and values are always numbers that I can check, ex: if I have a select each option corresponds 1 number, dps I compare with swith and detect if had change by user, in the text fields I filter with Sanitize + replace and use stmt, but you gave me a very good content, I will study them Thanks

  • @Martinsluan It is highly recommended to validate in the client, but this cannot be only in the client. Should do also, and thoroughly on the server. Especially when it comes to uploading files... Take this, even, as a starting point for your studies. Ahhh, if you’re going to run the script I suggested, give feedback if there was an error for me to edit here in the reply for future readers! ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.