How to save an image of a form to the bank

In my form, the user puts your order information and an image for reference, however, this 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>

Is giving error 500, the page is not working.

This is the first time I've tried to save an image, so if something is absurdly wrong, point it at me. :)

Author: Mariana Bayonetta, 2017-10-24

1 answers

To manipulate a file, one must use

$_FILES ( http://php.net/manual/pt_BR/reserved.variables.files.php )

Saving images to the bank is not a good practice by far ! rs

As requested by the chat, a complete example of sending the file to a directory and the file data in the bank: (take an image named " loading.gif " and leave it in the root folder, so it will display it while the form sends)

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

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>
    <script type="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>

_send.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');

?>
 1
Author: rbz, 2017-10-24 12:41:04