Problem uploading with php

0

I'm uploading with php pro server. At first it worked perfectly. The problem is that now when it uploads to the folder on the server it changes the name.

<?php

try {

    if (
        !isset($_FILES['arquivo']['error']) ||
        is_array($_FILES['arquivo']['error'])
    ) {
        throw new RuntimeException('Parametros invalidos. Contate o administrador.');
    }

    switch ($_FILES['arquivo']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('O arquivo não foi selecionado.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('O arquivo excedeu o tamanho máximo permitido (5mb).');
        default:
            throw new RuntimeException('Erro desconhecido. Contate o administrador.');
    }

    if ($_FILES['arquivo']['size'] > 5242880) {
        throw new RuntimeException('O arquivo excedeu o tamanho máximo permitido (5mb).');
    }


    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['arquivo']['tmp_name']),
        array(
            'pdf' => 'application/pdf',
        ),
        true
    )) {
        throw new RuntimeException('<br />Arquivo com formato invalido (Extenção permitida: PDF).<br />');
    }

    if (!move_uploaded_file(
        $_FILES['arquivo']['tmp_name'],
        sprintf('Documentos/%s.%s',
            sha1_file($_FILES['arquivo']['tmp_name']),
            $ext
        )
    )) {
        throw new RuntimeException('<br />Falha ao fazer upload do arquivo. Contate o administrador.<br />');
    }

    echo '<br />Arquivo enviado com sucesso <br />';

} catch (RuntimeException $e) {

    echo $e->getMessage();

}
?>

How do I upload it with the original file name and not with tmp?

    
asked by anonymous 09.04.2016 / 16:14

1 answer

2
if (!move_uploaded_file( $_FILES['arquivo']['tmp_name'],
    sprintf('Documentos/%s.%s', sha1_file($_FILES['arquivo']['tmp_name']), $ext)

Note that in this code snippet, you upload the tmp_name file, destined for Documents / Timestamp.ext .

Including, you just left the file extension ( $ ext ) out of the sprintf function.

 $_FILES['arquivo']['tmp_name'] //nome temporário do arquivo no servidor
 $_FILES['arquivo']['name']     //nome original do arquivo do computador do usuário

You need to upload with the original file name.

 if (!move_uploaded_file( $_FILES['arquivo']['tmp_name'], sprintf('Documentos/%s.', $_FILES['arquivo']['name'], $ext)))

Remembering that in the above code, the sha1_file function was removed, which would create a hash of the file. However, you mentioned wanting to save with the original name.

Ultimately, the PHP file system gives us a function to rename files. You can consult it in the documentation:

PHP: rename

    
09.04.2016 / 16:53