How to upload in PHP data coming from a Form with support for text and an image?

2

In my project I have on a page a form to collect data 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 have arranged to do this job is not working.

Here's 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';
            }
            }  
            ?>
    
asked by anonymous 25.03.2015 / 12:35

1 answer

1

Here is a small example of a form with a text field and an image upload. If you look in the PHP documentation has an example of working with $ _FILES link .

Your insert.php file has some syntax errors in the inserts, this may be causing you some error.

Ini_get ('upload_max_filesize') If it is, modify it to fit your need with the ini_set command or change it direct in php.ini , upload_max_filesize the default is 2M.

You can use $ _ FILES ['userfile'] ['error'] to see what error is being thrown.

Sample form:

<?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>
    
06.05.2015 / 14:48