php-upload image and upload to database

Asked

Viewed 593 times

0

I’m trying to insert an image into the database but when I click image upload, it gives the following error: Warning: getimagesize(): Filename cannot 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? Thanks in advance.

  • What error are you making? Edit the question and ask it too. It might be interesting to put the entire HTML form as well, because in PHP you are trying to save a value $_POST["Image"] which is not in the code shown.

  • is right initially I thought the error was in the query, but now I see that the problem is this, the variable $image is not in the form!

  • I don’t know if that’s it. when I click upload image. appears this:Warning: getimagesize(): Filename cannot be Empty in /home/unn_w17015779/public_html/upload.php on line 9 File is not an image.;

  • I know you want it in PHP, but take a look at this example, which also uses PHP:https://devdactic.com/ionic-image-upload-php/

2 answers

0

Follow my examples below :

upload_image.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>

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

php connection.

<?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 with these 3 files in a Test/ folder, with chmod 777

0


Your code works (with the observation that in my environment there was no execution of functions in javascript, because you did not put them). With the form you posted: inserir a descrição da imagem aqui

Click on Upload image:

File is an image - image/png.

I suggest you call your upload.php file with this little snippet of code (var_dump will show if it really is an image in the files array):

<?php
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;
    }
}

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

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. By piecing together everything you posted and creating a test database, I ran and worked (entered the image into 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;
    }
}
  • my code also works when it comes to uploading, but then it has to be stored in the database and I think it’s the chunk of the query that makes it an error. your stretch n allows me to enter in the database

  • In the body of the question it spoke of an error you were having on line 9 (the first answer’s target). Have you corrected it? Anyway, I edited the answer to include the save image part. Note the fact that the front part must be working for the second part to work.

  • the first code that Voce put or initially used it just like this and did not give error ai when I tried to insert part that would send the data to the database is that gave error

  • What was the mistake that came?

  • Please see what is written I edited the post and put the error that

  • It seems that the question has not been updated, do not have the error that Voce said he put.

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

  • oi Juven_v tried to use its code but the following error appears: array(1) { ["fileToUpload"]=> array(5) { ["name"]=> string(12) "IMG_5054.JPG" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpmdeTn3" ["error"]=> int(0) ["size"]=> int(71642) } } File is an image - image/jpeg.;

  • This is not an error. It is only the output of the var_dump function (which shows the contents of a variavels). With this we can see that where your image is stored (tmp_name) and that its validations are working (the if with the variable check).

  • Thank you Juven_v for having responded so quickly, I’m a little lost, have as Oce please explain how do I stop this from appearing sff?

  • I edited the answer again. There must be a small syntax error in your sql (misspelled column name, etc). The edition has the necessary information to solve.

  • hi Juven_v again, after all not working, tou having the following error:array(1) { ["fileToUpload"]=> array(5) { ["name"]=> string(12) "IMG_5046.JPG" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpooKK6j" ["error"]=> int(0) ["size"]=> int(6081742) } } File is an image - image/jpeg.Errorcolumn Count doesn’t match value Count at Row 1;

Show 8 more comments

Browser other questions tagged

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