How to upload PHP data from a Form with text and image support?

Asked

Viewed 589 times

2

In my project I have on a page a form for data collection that will be inserted in the database and in a folder of the server. My problem is that in this form I have a support for uploading images. Then in the PHP part to move this information to the database and to the server folder the file I found to do this job is not working.

Here I have my form:

<form action="insert.php" method="post"  enctype="multipart/form-data">
                    Nome do produto:<br>
                    <p><input type="text" name="NomeProduto" value="" placeholder="Username"></p>
                    <br>Escolha a categoria:<br>
                    <input type=text name="Categoria" list=browsers >
                    <datalist id=browsers >
                    <?php
                    //este php serve so para mostrar as categorias disponiveis na base de dados nesta datalist
                        include 'ligarbd.php';

                        $namesql = "SELECT  nomeCategoria FROM categorias";

                            if($namereg = mysql_query($namesql))
                            {
                            while($name = mysql_fetch_array($namereg)){

                                echo'<option> '.$name['nomeCategoria'];
                            }}
                    ?>
                    </datalist>
                    <br><br>

                        Selecione a imagem:<br>
                        <input type="file" name="uploadFile" id="fileToUpload"><br>


                    <br><br><p class="submit"><input type="submit" name="commit" value="Concluir"></p>
                    </form>

Here is my Insert.php file:

                <?php



            $dbhost = 'dados pessoais';
            $dbuser = 'dados pessoais';
            $dbpass = 'dados pessoais';
            $db_name = 'dados pessoais';
            $ftp_user = 'dados pessoais';
            $ftp_pass = 'dados pessoais';
            $ftp_server = "dados pessoais";



            $conn = mysql_connect($dbhost, $dbuser, $dbpass);



            if(! $conn ){

              die('Could not connect: ' . mysql_error());
            }

            mysql_select_db("$db_name")or die("cannot select DB");




            $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");


            // login with username and password
            $login_result = ftp_login($ftp_conn, $ftp_user, $ftp_pass);



            // check connection
            if ((!$ftp_conn) || (!$login_result)) {
                   echo "FTP connection has failed!";
                   echo "Attempted to connect to $ftp_server for user $ftp_user";
                   exit;
               } else {
                   echo "Connected to $ftp_server, for user $ftp_user";
               }


            $NomeProduto= $_POST['NomeProduto'];
            $Categoria= $_POST['Categoria'];
            $uploadDir = 'img/produtos/padaria/'; 
            $uploadDir2 = 'img/produtos/pastelaria/'; 
            $target_file = $uploadDir . basename($_FILES["uploadFile"]["name"]);
            $target_file2 = $uploadDir2 . basename($_FILES["uploadFile"]["name"]);



            //se a categoria for 2  vai para a pasta da padaria, se não vai para a pasta pastelaria (categoria=1)

            if($Categoria == 2) {
            if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file)) {


            // If file has uploaded successfully, store its name in data base
            $sql ="INSERT INTO produto (NomeP,Codcategoria) VALUES ('".$NomeProduto."','"$Categoria."')";
            if(mysql_query($query_image))
            {
            echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
            }
            else
            {
            echo 'File name not stored in database';
            }
            }}

            else if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file2)) {


            // If file has uploaded successfully, store its name in data base
            $sql ="INSERT INTO produto (NomeP,Codcategoria) VALUES ('".$NomeProduto."','"$Categoria."')";
            if(mysql_query($query_image))
            {
            echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
            }
            else
            {
            echo 'File name not stored in database';
            }
            }  
            ?>

1 answer

1

Here is a small example of a form with a text field and an image upload. If you look at the PHP documentation you have an example of how to work with $_FILES http://php.net/manual/en/features.file-upload.post-method.php.

Your Insert.php file has some syntax errors in the Inserts, this may be what is causing you some error.

Make sure the file size is not too large ini_get('upload_max_filesize') if so, modify it to suit your needs with the command ini_set or switch directly on php.ini, upload_max_filesize the default is 2M.

You can use the $_FILES['userfile']['error'] to see which error is being released.

Form example:

<?php
if ($_POST) {

    $descricao = $_POST['descricao'];
    $nomeImagem = $_FILES['imagem']['name'];

    $uploadDir = "meu diretório";
    $uploadFile = $uploadDir . basename($_FILES['imagem']['name']);

    if (move_uploaded_file($_FILES['imagem']['tmp_name'], $uploadFile)) {
        echo "Arquivo válido e enviado com sucesso.<br />";
    } else {
        echo "Possível ataque de upload de arquivo!<br />";
    }

    echo "Debug:<br />";
    echo "Descrição: ".$descricao."<br />";
    echo "Nome da Imagem: ".$nomeImagem."<br />";
    echo 'Aqui estão mais informações de debug de $_FILES: <br />';
    print_r($_FILES);
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <meta charset="utf-8">
        <title>Exemplo de formulário com upload de imagem</title>
    </head>
    <body>
        <h1>Exemplo de formulário com upload de imagem</h1>
        <form action="index.php" method="post" enctype="multipart/form-data">
            <label>Descrição</label>
            <input name="descricao" type="text" value="" />
            <br />
            <label>Imagem</label>
            <input name="imagem" type="file" value="" />
            <p>Tamanho máximo da imagem aceito pelo servidor é de <?php echo ini_get('upload_max_filesize'); ?></p>
            <input type="submit" name="botao" value="Enviar" />
        </form>
    </body>
</html>

Browser other questions tagged

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