php- upload image and upload to database

0

I'm trying to insert an image into the database but when I click upload image, it gives the following error: Warning: getimagesize (): Filename can not be empty in /home/unn_w17015779/public_html/upload.php on line 9 File is not an image.;

HTML code:

<body>
<?php include 'addDataAdmin.php';?>
<form name="ContactForm" action="addDataAdmin.php" method="POST" enctype="multipart/form-data" autocomplete="off" onsubmit="return ValidateContactForm();">
    ISBN:<input type="text" name="ISBN">
    Author's Name:<input type="text" name="Authorsname">
    Title:<input type="text" name="Title">
    Edition:<input type="number" name="edition" >
    Year:<input type="text" name="year" onkeypress="return justNumber(event)" >

    Category:
    <select name="category" size="1">
        <option value="computing">Computing</option>
        <option value="Romance">Romance</option>
        <option value="Fiction">Fiction</option>
        <option value="Non-Fiction">Non-Fiction</option>
    </select>
    <br />

    Publisher:<input type="text" name="publisher">
    Quantity-in-stock:<input type="number" name="quantityinstock" >
    Price:<input type="text" name="price" onkeypress="return justNumber(event)">
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit" formaction="/upload.php">
    <input type="submit" value="Send" name="send">
    <input type="reset" value="Clear">
</form>

PHP code:

<?php
include('config.php');
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

if (!empty($_FILES["fileToUpload"]["name"])) {

 $Image =$conn->real_escape_string($_POST['Image']);

    $sql="INSERT INTO books (Image) VALUES('$Image')";

    if(mysqli_query($conn,$sql))
     {
        echo '<h3><font color="red">You have successfully updated </font></h3>';

        }
            else
            {
                echo 'Error';
                echo $sql;
            }
        }




?>;

What am I doing wrong? Thank you in advance.

    
asked by anonymous 21.04.2017 / 18:01

2 answers

0

Your code works (with the observation that in my environment there was no execution of the functions in javascript, because you did not put them). With the form you posted:

ClickingUploadimage:

Fileisanimage-image/png.

Isuggestyoucallyourupload.phpfilewiththislittlebitofcode(var_dumpwillactuallyshowanimageinthefilesarray):

<?phpvar_dump($_FILES);$target_dir="uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

Save to database The written code should be saving something, except the image you want. Use the file_get_contents function to get upload image content.

if (!empty($_FILES["fileToUpload"]["name"])) {
    $Image =$conn->real_escape_string(
    file_get_contents($_FILES["fileToUpload"]["tmp_name"]));
    $sql="INSERT INTO books (Image) VALUES('$Image')";

This should allow your image to be saved. But remembering the array $_FILES["fileToUpload"]["tmp_name"] should point to an existing file somewhere on your computer.

Putting it all together

There are no errors in your script. Joining everything you posted and creating a test database, I ran and it worked (inserted the image in the database). See the comments:

<?php

//minha conexao com o banco (você já tem isso)
$conn = mysqli_connect('localhost', 'aprendendo', '', 'aprendendo');

//só para depuração
var_dump ( $_FILES );

$target_dir = "uploads/";
$target_file = $target_dir . basename ( $_FILES ["fileToUpload"] ["name"] );
$uploadOk = 1;
$imageFileType = pathinfo ( $target_file, PATHINFO_EXTENSION );
// Check if image file is a actual image or fake image
if (isset ( $_POST ["submit"] )) {
    $check = getimagesize ( $_FILES ["fileToUpload"] ["tmp_name"] );
    if ($check !== false) {
        echo "File is an image - " . $check ["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

if (! empty ( $_FILES ["fileToUpload"] ["name"] )) {
    //obtem o conteudo da imagem com file_get_contents
    $Image = $conn->real_escape_string ( file_get_contents ( $_FILES ["fileToUpload"] ["tmp_name"]));
    //criei uma tabela ficticia chamada a, e uma coluna 
    //chamada b (iamgem), substitua pela sua
    $sql = "INSERT INTO a (b) VALUES('$Image')";
    if (mysqli_query ( $conn, $sql )) {
        echo '<h3><font color="red">You have successfully updated </font></h3>';
    } else {
        echo 'Error';
        //se ocorrer algum erro de sintaxe o sql será mostrado na tela
        echo $conn->error;
    }
}
    
21.04.2017 / 20:57
0

Here are my examples below:

Upload_Picture.php

 <h1> Carregar a foto</h1>
<form method="POST" action="proc_upload.php" enctype="multipart/form-data">
	Imagem: <input name="arquivo" type="file"><br><br>
	
	<input type="submit" value="Cadastrar">
</form>

proc_upload.php

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="utf-8">
    </head>
    </body>
        <?php
            include_once("conexao.php");
            $arquivo    = $_FILES['arquivo']['name'];

            //Pasta onde o arquivo vai ser salvo
            $_UP['pasta'] = 'foto/';

            //Tamanho máximo do arquivo em Bytes
            $_UP['tamanho'] = 1024*1024*100; //5mb

            //Array com a extensões permitidas
            $_UP['extensoes'] = array('png', 'jpg', 'jpeg', 'gif');

            //Renomeiar
            $_UP['renomeia'] = false;

            //Array com os tipos de erros de upload do PHP
            $_UP['erros'][0] = 'Não houve erro';
            $_UP['erros'][1] = 'O arquivo no upload é maior que o limite do PHP';
            $_UP['erros'][2] = 'O arquivo ultrapassa o limite de tamanho especificado no HTML';
            $_UP['erros'][3] = 'O upload do arquivo foi feito parcialmente';
            $_UP['erros'][4] = 'Não foi feito o upload do arquivo';

            //Verifica se houve algum erro com o upload. Sem sim, exibe a mensagem do erro
            if($_FILES['arquivo']['error'] != 0){
                die("Não foi possivel fazer o upload, erro: <br />". $_UP['erros'][$_FILES['arquivo']['error']]);
                exit; //Para a execução do script
            }

            //Faz a verificação da extensao do arquivo
            $extensao = strtolower(end(explode('.', $_FILES['arquivo']['name'])));
            if(array_search($extensao, $_UP['extensoes'])=== false){        
                echo "
                    <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/teste/upload_imagem.php'>
                    <script type=\"text/javascript\">
                        alert(\"A imagem não foi cadastrada extesão inválida.\");
                    </script>
                ";
            }

            //Faz a verificação do tamanho do arquivo
            else if ($_UP['tamanho'] < $_FILES['arquivo']['size']){
                echo "
                    <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/teste/upload_imagem.php'>
                    <script type=\"text/javascript\">
                        alert(\"Arquivo muito grande.\");
                    </script>
                ";
            }

            //O arquivo passou em todas as verificações, hora de tentar move-lo para a pasta foto
            else{
                //Primeiro verifica se deve trocar o nome do arquivo
                if($UP['renomeia'] == true){
                    //Cria um nome baseado no UNIX TIMESTAMP atual e com extensão .jpg
                    $nome_final = time().'.jpg';
                }else{
                    //mantem o nome original do arquivo
                    $nome_final = $_FILES['arquivo']['name'];
                }
                //Verificar se é possivel mover o arquivo para a pasta escolhida
                if(move_uploaded_file($_FILES['arquivo']['tmp_name'], $_UP['pasta']. $nome_final)){
                    //Upload efetuado com sucesso, exibe a mensagem
                    $query = mysqli_query($conn, "INSERT INTO usuarios (
                    nome_imagem) VALUES('$nome_final')");
                    echo "
                        <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/teste/upload_imagem.php'>
                        <script type=\"text/javascript\">
                            alert(\"Imagem cadastrada com Sucesso.\");
                        </script>
                    ";  
                }else{
                    //Upload não efetuado com sucesso, exibe a mensagem
                    echo "
                        <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/teste/upload_imagem.php'>
                        <script type=\"text/javascript\">
                            alert(\"Imagem não foi cadastrada com Sucesso.\");
                        </script>
                    ";
                }
            }


        ?>

    </body>
</html>

Change in proc_upload.php to lines containing <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/teste/upload_imagem.php'> to your URL, this has to be done, if not, it will not work

connection.php

<?php
    $servidor = "localhost";
    $usuario = "root";
    $senha = "";
    $dbname = "info";

    //Criar a conexão
    $conn = mysqli_connect($servidor, $usuario, $senha, $dbname);
    if(!$conn){
        die("Falha na conexao: " . mysqli_connect_error());
    }else{
        //echo "Conexao realizada com sucesso";
    }
?>

Test these 3 files in a Test / folder, with chmod 777

    
22.04.2017 / 22:08