Upload/upload images with php

Asked

Viewed 894 times

5

Form

<label>Imagem do produto:</label>
<input type="file" name="imagem-produto">

Script

$foto = $_POST["imagem-produto"];
$tamanhoMax = 1024 * 1024; # 1MB

if (isset($_FILES['imagem-produto']['name']) && $_FILES['imagem-produto']['error'] == 0):
    if ($_FILES['imagem-produto']['size'] < $tamanhoMax):
        $arquivoTMP = $_FILES['arquivo']['tmp_name'];
        $nomeF = $_FILES["imagem-produto"]["name"];
        //Seleciona extensão
        $extensaoF = pathinfo($nomeF, PATHINFO_EXTENSION);
        //Converte a extensão para minúsculo
        $extensaoF =  strtolower($extensaoF);
        //Somente imagens .jpg;.jpeg;.png
        if (strstr('.jpg;.jpeg;.png', $extensaoF)):
            //nome único para a imagem
            //Evita nomes com acentos ou caracteres alfanuméricos
            $novoNomeF = uniqid(time()).$extensaoF;
            //Concatena a pasta com o nome
            $destino = 'imagens_produtos/' . $novoNomeF;
            if (@move_uploaded_file($arquivoTMP, $destino)):
?>
                <p class="alert success">Sua foto foi cadastrada com sucesso.</p>
<?php
            ;else:
?>
            <p class="alert error">Erro ao salvar arquivo, aparentemente você não tem permissão de escrita</p>
<?php
            endif;
        ;else:
?>
        <p class="alert error">Só aceitamos arquivos com as extensões <span>.jpg</span>, <span>.png</span> ou <span>.jpeg</span> .</p>
<?php
        endif;
    ;else:
?>
        <p class="alert error">O arquivo de imagem ultrapassa o limite de peso. <span>(0.5MB)</span></p>
<?php
    endif;
;else:
?>
    <p class="alert error">Você não enviou nenhum arquivo.</p>
<?php
endif;
?>

I performed this script to save images to the server, but it keeps entering the first error. How to solve ? There is some other problem in the code ?

*First error = first condition else (<p class="alert error">Você não enviou nenhum arquivo.</p>)

  • 1

    put the enctype in the <form> ?

  • yes, I did, and yet he made the mistake

  • 2

    Before the first if (isset(, put this in a row above: print_r($_FILES); exit;. Include the result of that test in the question.

2 answers

4


Your code is pretty messed up, and yet you used it $_POST["imagem-produto"] and $_FILES['imagem-produto'] at the same time, does not make sense the same name in two types of variables, the site has several simple download examples, in PHP documentation also, use as is, learn what each variable superglobal means.

Another problem is that here you used different names:

$arquivoTMP = $_FILES['arquivo']['tmp_name'];
$nomeF = $_FILES["imagem-produto"]["name"];

One this $_FILES['arquivo'] and another $_FILES["imagem-produto"], no use typing randomly or copying examples of code without knowing what you’re doing, do not understand as a negative and yes positive criticism, learn to use variables, do something like:

if (isset($_FILES['imagem-produto']['name']) && $_FILES['imagem-produto']['error'] == 0) {
    $arquivo = $_FILES['imagem-produto'];

    if ($arquivo['size'] < $tamanhoMax) {
        $arquivoTMP = $arquivo['tmp_name'];
        $nomeF = $arquivo["name"];

In addition to reducing the code you avoid being confused with the "Keys".

Your problem was pretty much the same as this question Form does not execute PHP script, a series of "typos", for not knowing well what was doing, perhaps copied code from somewhere, I recommend that you make use of the variables to reduce code and learn first how things really work, the documentation this and for this, these links should help you:

First of all

Check if your folder has write permission imagens_produtos

Revised code

I redid all your code, reorganized it and I believe it now works.

Note: I switched the alternative syntax by normal, this because the alternative syntax is more unusual to be used usually people use only in small ifs and not in extensive php codes, in my view it would be better used where we have a lot of HTML and little PHP, for example templates, something like this seems better used

<?php if ($a == 5): ?>
A é igual a 5
<?php endif; ?>    

Complete code:

<?php

$tamanhoMax = 1024 * 1024; # 1MB

if (isset($_FILES['imagem-produto']['name'])) {
    $arquivo = $_FILES['imagem-produto']; //Sua variavel

    if ($arquivo['error'] != 0) {
        switch ($code) {
            case UPLOAD_ERR_INI_SIZE:
                $message = "O upload excedeu a configuração do upload_max_filesize no php.ini";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $message = "O upload excedeu o MAX_FILE_SIZE";
                break;
            case UPLOAD_ERR_PARTIAL:
                $message = "O upload foi feito parcialmente";
                break;
            case UPLOAD_ERR_NO_FILE:
                $message = "Não foi selecionado um arquivo";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $message = "Pasta temporaria não encontrada";
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $message = "Erro na escrita do disco";
                break;
            case UPLOAD_ERR_EXTENSION:
                $message = "Uma extensão do PHP interrompeu o upload do arquivo";
                break;

            default:
                $message = "Erro desconhecido";
        }

        echo '<p class="alert error">', $message,'</p>';
    } else if ($arquivo['size'] < $tamanhoMax) {
        $arquivoTMP = $arquivo['tmp_name'];
        $nomeF = $arquivo["name"];

        //Seleciona extensão
        $extensaoF = pathinfo($nomeF, PATHINFO_EXTENSION);

        //Converte a extensão para minúsculo
        $extensaoF =  strtolower($extensaoF);

        //Somente imagens .jpg;.jpeg;.png
        if (strstr('.jpg;.jpeg;.png', $extensaoF)) {

            //nome único para a imagem
            //Evita nomes com acentos ou caracteres alfanuméricos
            $novoNomeF = uniqid(time()).$extensaoF;

            //Concatena a pasta com o nome
            $destino = 'imagens_produtos/' . $novoNomeF;

            if (@move_uploaded_file($arquivoTMP, $destino)) {
                echo '<p class="alert success">Sua foto foi cadastrada com sucesso.</p>';
            } else {
                echo '<p class="alert error">Erro ao salvar arquivo, aparentemente você não tem permissão de escrita</p>';
            }
        } else {
            echo '<p class="alert error">Só aceitamos arquivos com as extensões <span>.jpg</span>, <span>.png</span> ou <span>.jpeg</span> .</p>';
        }
    } else {
        echo '<p class="alert error">O arquivo de imagem ultrapassa o limite de peso. <span>(0.5MB)</span></p>';
    }
} else {
    echo '<p class="alert error">Você não enviou nenhum arquivo.</p>';
}

And the form should look like this:

<form enctype="multipart/form-data" action="SUA PÁGINA PHP AQUI" method="POST">
    <label>Imagem do produto:</label>
    <input type="file" name="imagem-produto">
    <input type="submit" value="Enviar">
</form>

3

Place enctype="multipart/form-data" in form.

or you’re trying to save somewhere without permission

  • 1

    had already put, but not even this solved

Browser other questions tagged

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