PHP display image from mysql

2

I am developing a CMS where the user can insert articles and if you want to upload an image to that same article, the text uploads work correctly but the images do not, the only thing that appears is the name of the image in the site where the image would be supposed to appear, I followed the same logic that I did to upload the text (articles).

PHP:

    <?php
session_start();
include_once('../includes/connection.php');
if(isset($_SESSION['logged_in'])) {
    // display add page
        if (isset($_POST['title'], $_POST['content'])) {
        $title = $_POST['title'];
        $content = $_POST['content'];
        $image = $_FILES['image']['name'];

            if (empty($title) || empty($content)) {
                $error = 'Todos os campos têm de ser preenchidos!';
            }

            else {
                $query = $pdo->prepare('INSERT INTO articles(article_title, article_content, article_img, article_timestamp) VAlUES (?, ?, ?, ?)');

                $query->bindValue(1, $title);
                $query->bindValue(2, $content);
                $query->bindValue(3, $image);
                $query->bindValue(4, time());

                $query->execute();

                header('Location:index.php');
            }
        }

}
        else {
        header('Location:index.php');
    }
    ?>

    <html>
    <head>
        <title>AdminPT</title>
        <meta charset="UTF-8">
        <link rel ="stylesheet" href="../assets/style.css"/>
    </head>

        <body>
            <div class="container">
                CMS
                <br>

                <h4 id ="add">Adicionar Artigo</h4>

                <?php
                if (isset($error)) { ?>
                    <small style="color:#aa0000"><?php echo $error; ?></small>
                <?php } ?>

                <form action="add.php" method="post" autocomplete="off" enctype="multipart/form-data">
                    <input id="title" type="text" name="title" placeholder="Título"/><br><br>
                    <textarea id="content" rows="15" placeholder="Conteúdo" name="content"></textarea>
                    <input type="file" name="image"/><br><br>
                    <input id="addBtn" type="submit" value="Adicionar Artigo"/>
                </form>
                <a id="back" href="../admin">&larr; Voltar</a>
            </div>
        </body>
    </html>

Display image (HTML):

<div id="news">
            <?php foreach ($articles as $article) { ?>
            <div><h2><?php echo utf8_encode($article['article_title']); ?></h2><div id="newsImg"><?php echo $article['article_img']; ?></div><br><span id="date">Publicado 
                    <?php
                        setlocale(LC_ALL, 'pt_BR.utf8', 'Portuguese_Brazil');
                        //setlocale(LC_ALL, NULL);
                        date_default_timezone_set('Europe/Lisbon');

                        $uppercaseMonth = ucfirst(gmstrftime('%B'));
                        echo utf8_encode(strftime( '%a, '.$uppercaseMonth.' %d de %Y'/* - %H:%M'*/, $article['article_timestamp']));
                    ?></span><p><?php echo utf8_encode($article['article_content']); ?><br><br><span id="print"><a onclick="javascript:window.print();" href="#">Imprimir</a></span><span id="link"><a href="#">Enviar link</a></p></div>
                    <?php } ?>

        </div>
    
asked by anonymous 08.04.2014 / 17:38

2 answers

3

Instead of

$image = $_FILES['image']['name'];

You need to read the file with

$image = file_get_contents( $_FILES['image']['tmp_name'] );

to be able to store.

To show, I would need a separate PHP to do the reverse, and put this PHP as the source of the image, something like this:

<img src="mostraimagem.php?id=286318936">

However, remember that I am simplifying the example, first of all you need to learn how to use the correct BIND for BLOBs, and have the database prepared for this amount of data.

showfile.php would be simple:

<?php

//conecte na base de dados antes, e guarde em $con

$query = "SELECT * FROM articles WHERE id = ?";
$stmt = $conexao->prepare( $query );
$stmt->bindParam(1, $_GET['id']);
$stmt->execute();

if( $stmt->rowCount() ){
   $resultado = $stmt->fetch(PDO::FETCH_ASSOC);
   header(“Content-type: image/jpg”); //acerte pro tipo de imagem
   print $resultado['article_img'];
   die();
}else{
   //pode servir uma imagem padrão, ou um 404
}

?>

The ideal solution would be to reconsider the entire system and just move the file to a folder, and save only this name in the database, thus avoiding an overload in the base and processing of PHP.

To learn how to do this, a great start is this:

  

PHP - Manage file upload

    
08.04.2014 / 17:47
0

To display the images with PHP from the image code there is the GD library, from which you can use the imagecreatefromstring (string $ image) .

Then to load these images you will need to create a file in PHP to load them from the database as you saved them:

<?php
header('Content-Type: image/jpeg');

$articleID = settype($_GET['id'], 'integer');
$pdo = new PDO("...");
$query = $pdo->query("SELECT article_img FROM articles WHERE article_id = $articleID");

while($row = $query->fetch(PDO::FETCH_ASSOC)){
    $image = imagecreatefromstring($row['article_img']);
    imagepng($image);
}

?>

Then you would call this file according to another user's example:

<img src="mostraimagem.php?id={article_id}">

Meanwhile , this is not a very recommendable practice, it would be more interesting if you uploaded the file yourself, according to what is shown in php.net.

    
08.04.2014 / 18:46