Upload Images does not work PHP

Asked

Viewed 527 times

0

I have the following page in PHP:

<?php 
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Cadastro de Operacional</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><br>Posto '+x+'<p><input type="text" name="posto'+x+'" class="form-control"/></p><p><input type="file" name="arquivo'+x+'"></p><a href="#" class="remove_field btn btn-danger">Remover Posto</a></div>'); 
            window.scrollTo(0,document.querySelector(".scrollingContainer").scrollHeight);

//add input box
}
});

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;

    })
});
</script>
</head>
<body>
    <?php
    if(!empty($_SESSION['cadastro'])){ 
        if($_SESSION['permite_cadastrar'] == 0){
            ?>
            <script language="JavaScript"> 
                window.location="inicial.php"; 
                window.alert("Acesso Negado! Sem permissão!");
            </script> 
            <?php
        }   
    }else{
        $_SESSION['msg'] = "Área restrita";
        ?> 
        <script language="JavaScript"> 
            window.location="index.php"; 
            window.alert("Area Restrita");
        </script> 

        <noscript> 
            Se não for direcionado automaticamente, clique <a href="index.php">aqui</a>. 
        </noscript>
    </script>
    <?php
}
include_once("navbar.php");
?>
<div class="container">
    <form class="form-horizontal" method="POST" action="cadastrar_operacional.php" name="form1">
        <div class="row">
            <div class="col-md-2">
                <br>Referência: <input type="text" name="referencia"  class="form-control">
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <br>Posto 1:<input type="text" name="posto1" class="form-control"/>
                <input name="arquivo1" type="file"  />
                <div class="input_fields_wrap">

                    <div>

                    </div>
                </div>
            </div>
        </div>
        <br>

        <button class="add_field_button btn btn-info">Adicionar novo posto</button>
        <input type="submit" name="submit" class="btn btn-success" value="Cadastrar Referência">    
    </form>
</div>


</body>
</html>

And the form processes here:

<?php 
session_start();
include_once("conexao.php");
?>
<?php
/******
 * Upload de imagens
 ******/
 // verifica se foi enviado um arquivo
if ( isset( $_FILES[ 'arquivo1' ][ 'name' ] ) && $_FILES[ 'arquivo1' ][ 'error' ] == 0 ) {
   $arquivo_tmp = $_FILES[ 'arquivo1' ][ 'tmp_name' ];
   $nome = $_FILES[ 'arquivo1' ][ 'name' ];

    // Pega a extensão
   $extensao = pathinfo ( $nome, PATHINFO_EXTENSION );

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

    // Somente imagens, .jpg;.jpeg;.gif;.png
    // Aqui eu enfileiro as extensões permitidas e separo por ';'
    // Isso serve apenas para eu poder pesquisar dentro desta String
   if ( strstr ( '.jpg;.jpeg;.gif;.png', $extensao ) ) {
        // Cria um nome único para esta imagem
        // Evita que duplique as imagens no servidor.
        // Evita nomes com acentos, espaços e caracteres não alfanuméricos
    $novoNome = uniqid ( time () ) . '.' . $extensao;

        // Concatena a pasta com o nome
    $destino1 = 'imagens / ' . $novoNome;

        // tenta mover o arquivo para o destino
    if ( @move_uploaded_file ( $arquivo_tmp, $destino1 ) ) {
        echo ' <img src = "' . $destino1 . '" class="resize" >';

    }
    else
        echo 'Erro ao salvar o arquivo. Aparentemente você não tem permissão de escrita.<br />';
}
else
    echo 'Você poderá enviar apenas arquivos "*.jpg;*.jpeg;*.gif;*.png"<br />';
}
else
    echo 'Você não enviou nenhum arquivo!';


if (isset($destino1)) {
  $imagem1 = $destino1;
} else {
    $imagem1 = "imagens/sem_imagem.jpg";
}


?>

In theory, it should take the image of the input file with the filename arquivo1 and display the image... but it always displays this: You have not sent any file!

I’m using WAMP Server, I’ve already increased the upload limit and the max size post limit in the settings, and it’s still not working.. someone can help me??

2 answers

5


Hello.

This is happening because you are not using the "enctype form-data". When you make a request through the POST method, you need to specify the type of encoding that the request will compose the body of your request. Basically there are three types:

  • application/x-www-form-urlencoded (default, all characters are encoded before being sent)
  • Multipart/form-date (No character is encoded, necessary for media traffic, as is your case)
  • text/Plain (Spaces are converted to "+" symbols, but no special character is encoded, avoid using this format)

Thus, the correct attribute to use is <form enctype="multipart/form-data">

Good luck.

  • Show! Now I got it. Thank you very much! :)

4

Change the opening of your form that tag below and test again:

<form class="form-horizontal" method="POST" action="cadastrar_operacional.php" name="form1" enctype="multipart/form-data">
  • To make the answer clearer to the questioner, the difference in the form opening is in the attribute enctype="Multipart/form-data". This attribute changes the form data sending format and signals the browser to send the file selected by the input to the server.

  • Vlwww!! Thank you very much! I had made another form model that worked the upload... but I think in this new model I forgot the enctype="Multipart/form-data". Now it’s working again! Thank you very much!!

Browser other questions tagged

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