Saving an image from a form to the bank

1

In my form, the user places their order information and an image for reference, but that image is not being saved along with the record.

The form:

<!DOCTYPE html>
<html lang="utf-8">
<head>
    <meta charset="UTF-8">
    <title>Documento</title>
</head>
<body>
    <?php
        if(isset($_FILES)){
            $dir = "../img/";
            $image = $_FILES['image']['name'];
            if(move_uploaded_file($_FILES['image']['tmp_name'], $dir.$image)){

                $image = $_FILES['image'];

                $strcon = mysqli_connect('localhost','root','', 'db_formacao') or die('Erro ao conectar ao banco de dados');
                $sql = "INSERT INTO imagens SET image = '$image'" 
                mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro");
                mysqli_close($strcon);

                echo '<script type="text/javascript">
                        alert("Salvo com Sucesso !");
                        window.history.go(-1);
                    </script>';
                ?>
            }
        }
    ?>
    <form id="formulario" method="post" enctype="multipart/form-data" action="">
        Selecione uma imagem:
        <input name="image" type="file"/>
        <br/>
        <button type="submit">Salvar</button>
    </form>
</body>
</html>
  

You're giving the 500 error, the page is not working.

This is the first time I try to save an image, so if something is absurdly wrong, point me out. :)

    
asked by anonymous 24.10.2017 / 13:19

1 answer

1

To manipulate a file, you must use

$ _ FILES ( link )

Saving images to the bank is not a good practice at all! rs

As asked by the chat, a complete example of sending the file to a directory and the data from the file in the database: (take a picture with the name of "loading.gif" and leave it in the root folder, so it will display it as the form sends)

*** Create an "attachments" folder in the root folder.

index.php

<html>
<head>  
    <link type="text/css" rel="stylesheet" href="../assets/css/materialize.min.css"  media="screen,projection"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script><scripttype="text/javascript">
        $(document).ready(function(){
            $("#formulario").submit(function() {
                $('#formulario').hide();
                $('.imagens').hide();
                $('#gif').show();
                //return true;
            });
        });
    </script>
</head>
<body>

    <img src="loading.gif" id="gif" height="auto" width="200" hidden>

    <form id="formulario" method="post" enctype="multipart/form-data" action="_envio.php">
        Selecione uma imagem: 
        <input name="arquivoX" type="file"/>
        <br/>
        <button type="submit">Salvar</button>
    </form>

    <?
    date_default_timezone_set('America/Sao_Paulo');

    $srv    = "enderecoDoBanco";
    $user   = "usuarioDoBanco";
    $pass   = "senhaDoBanco";
    $db     = "nomeDoBanco";

    $db = new mysqli($srv, $user, $pass, $db);

    $sql = "SELECT * FROM anexos";
    $res = $db -> query($sql);

    while ($i = $res -> fetch_assoc()) {

        $a[] = $i;

        //echo "<pre>";
        //print_r($i);
        //echo $i['dir'].$i['arq'];
        ?>
        <img class="imagens" src="<?echo 'anexos\'.$i['arq']?>" height="60" width="60"/>
        <?
    }
    ?>

</body>
</html>

_envia.php

<?php

date_default_timezone_set('America/Sao_Paulo');

$srv    = "enderecoDoBanco";
$user   = "usuarioDoBanco";
$pass   = "senhaDoBanco";
$db     = "nomeDoBanco";

$db = new mysqli($srv, $user, $pass, $db);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
} else {
    echo '<div style="background-color:green;color:white"><b>OK :: CONEXAO BD</b></div><hr>';
}

echo '<pre>';
print_r($_FILES);
print "</pre>";

$uploaddir = 'F:\Xampp\htdocs\_commands\files\anexos\';
$uploadfile = time() . '-' . basename($_FILES['arquivoX']['name']);

if (move_uploaded_file($_FILES['arquivoX']['tmp_name'], $uploaddir.$uploadfile)) {

    // Gera endereço da pasta para o mysql
    $dir = str_replace('\', '\\', $uploaddir);

    // ******* TRATAR NOME (acentos, etc)

    $arq = $uploadfile;
    $extpat = pathinfo($_FILES['arquivoX']['name']);
    $ext = $extpat['extension'];

    echo '<div style="background-color:green;color:white">OK :: Arquivo válido e enviado com sucesso.<br></div>';
    $db -> query("INSERT INTO anexos ('dir','arq','ext') VALUES ('$dir','$arq','$ext')");

} else {

    echo '<div style="background-color:orange;color:white">WARNING :: Possível ataque de upload de arquivo!<br></div>';
}

if ($db -> close()) {
    echo '<div style="background-color:blue;color:white"><b>OK :: CONEXAO BD CLOSE</b></div><hr>';
} else {
    echo '<div style="background-color:orange;color:white"><b>WARNING :: CONEXAO DB CLOSE</b></div><hr>';
}

sleep(3);

header('Location: index.php');

?>
    
24.10.2017 / 14:19