Howto display an image in html which is stored in database

Hi,
I have a HTML page with forms to upload, delete and download an image file. There is also a link on the file name which displays the image file. This all works fine.
I would like to display the image which is stored in the database on the html page itself, rather than have a link to it which directs a user to a new page.
The html file is file.html.php

<?php include_once $_SERVER['DOCUMENT_ROOT'] .
    '/artgibney/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>PHP/MySQL File Repository</title>
  </head>
  <body>
    <h1>PHP/MySQL File Repository</h1>

    <form action="" method="post" enctype="multipart/form-data">
      <div>
        <label for="upload">Upload File:
        <input type="file" id="upload" name="upload"></label>
      </div>
      <div>
        <label for="desc">File Description:
        <input type="text" id="desc" name="desc"
            maxlength="255"></label>
      </div>
      <div>
        <input type="hidden" name="action" value="upload">
        <input type="submit" value="Upload">
      </div>
    </form>

    <?php if (count($files) > 0): ?>

    <p>The following files are stored in the database:</p>

    <table>
      <thead>
        <tr>
          <th>Filename</th>
          <th>Type</th>
          <th>Description</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($files as $f): ?>
        <tr>
          <td>
            <img src="<?php htmlout($f['filename']); ?>" height="187" width="110">
          </td>
          <td>
            <a href="?action=view&amp;id=<?php htmlout($f['id']); ?>"
                ><?php htmlout($f['filename']); ?></a>
          </td>
          <td><?php htmlout($f['mimetype']); ?></td>
          <td><?php htmlout($f['description']); ?></td>
          <td>
            <form action="" method="get">
              <div>
                <input type="hidden" name="action" value="download"/>
                <input type="hidden" name="id" value="<?php htmlout($f['id']); ?>"/>
                <input type="submit" value="Download"/>
              </div>
            </form>
          </td>
          <td>
            <form action="" method="post">
              <div>
                <input type="hidden" name="action" value="delete"/>
                <input type="hidden" name="id" value="<?php htmlout($f['id']); ?>"/>
                <input type="submit" value="Delete"/>
              </div>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </body>
</html>

The index.php file

<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/magicquotes.inc.php';

if (isset($_POST['action']) and $_POST['action'] == 'upload')
{
  // Bail out if the file isn't really an upload
  if (!is_uploaded_file($_FILES['upload']['tmp_name']))
  {
    $error = 'There was no file uploaded!';
    //include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/error.html.php';
    include 'error.html.php';
    exit();
  }
  $uploadfile = $_FILES['upload']['tmp_name'];
  $uploadname = $_FILES['upload']['name'];
  $uploadtype = $_FILES['upload']['type'];
  $uploaddesc = $_POST['desc'];
  $uploaddata = file_get_contents($uploadfile);

include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

  try
  {
    $sql = 'INSERT INTO filestore SET
        filename = :filename,
        mimetype = :mimetype,
        description = :description,
        filedata = :filedata';
    $s = $pdo->prepare($sql);
    $s->bindValue(':filename', $uploadname);
    $s->bindValue(':mimetype', $uploadtype);
    $s->bindValue(':description', $uploaddesc);
    $s->bindValue(':filedata', $uploaddata);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Database error storing file!';
    //include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/error.html.php';
    include 'error.html.php';
    exit();
  }

  header('Location: .');
  exit();
}

if (isset($_GET['action']) and
    ($_GET['action'] == 'view' or $_GET['action'] == 'download') and
    isset($_GET['id']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

  try
  {
    $sql = 'SELECT filename, mimetype, filedata
        FROM filestore
        WHERE id = :id';
    $s = $pdo->prepare($sql);
    $s->bindValue(':id', $_GET['id']);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Database error fetching requested file.';
    include 'error.html.php';
    exit();
  }

  $file = $s->fetch();
  if (!$file)
  {
    $error = 'File with specified ID not found in the database!';
    include 'error.html.php';
    exit();
  }

  $filename = $file['filename'];
  $mimetype = $file['mimetype'];
  $filedata = $file['filedata'];
  $disposition = 'inline';

  if ($_GET['action'] == 'download')
  {
    $mimetype = 'application/octet-stream';
    $disposition = 'attachment';
  }

  // Content-type must come before Content-disposition
  header('Content-length: ' . strlen($filedata));
  header("Content-type: $mimetype");
  header("Content-disposition: $disposition; filename=$filename");

  echo $filedata;
  exit();
}

if (isset($_POST['action']) and $_POST['action'] == 'delete' and
    isset($_POST['id']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

  try
  {
    $sql = 'DELETE FROM filestore
        WHERE id = :id';
    $s = $pdo->prepare($sql);
    $s->bindValue(':id', $_POST['id']);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Database error deleting requested file.';
    //include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/error.html.php';
    include 'error.html.php';
    exit();
  }

  header('Location: .');
  exit();
}

include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

try
{
  $result = $pdo->query(
      'SELECT id, filename, mimetype, description
      FROM filestore');
}
catch (PDOException $e)
{
  $error = 'Database error fetching stored files.';
  //include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/error.html.php';
  include 'error.html.php';
  exit();
}

$files = array();
foreach ($result as $row)
{
  $files[] = array(
      'id' => $row['id'],
      'filename' => $row['filename'],
      'mimetype' => $row['mimetype'],
      'description' => $row['description']);
      //'filedata' => $row['filedata']);
}

include 'files.html.php';

This code is from the sitepoint book ‘PHP and MYSQL from Novice to Ninja’ by Kevin Yank.
The relevant piece of code in the html file is,

          <td>
            <img src="<?php htmlout($f['filename']); ?>" height="187" width="110">
          </td>

I have tried instead this,

<img src="<?php htmlout($f['filedata']); ?>" height="187" width="110">

I know this would need ‘filedata’ to be called at the end of the index.php like this,

try
{
  $result = $pdo->query(
      'SELECT id, filename, mimetype, description, filedata
      FROM filestore');
}
catch (PDOException $e)
{
  $error = 'Database error fetching stored files.';
  //include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/error.html.php';
  include 'error.html.php';
  exit();
}

$files = array();
foreach ($result as $row)
{
  $files[] = array(
      'id' => $row['id'],
      'filename' => $row['filename'],
      'mimetype' => $row['mimetype'],
      'description' => $row['description']),
      'filedata' => $row['filedata']);
}

include 'files.html.php';

‘filedata’ is the field in the table which actually contains the binary file that is the image. The column has type BLOB.
Any help would be greatly appreciated.
Thanks,
Shane

Hi,
The problem seems to be that the index.php file does not call the html file because it is having problems selecting the ‘filedata’ field. When I remove this, then files.html.php file is called fine.
Can data of type BLOB be held in an array?
Thanks,
Shane

Instead of this:

<a href=“?action=view&id=<?php htmlout($f[‘id’]); ?>”><?php htmlout($f[‘filename’]); ?></a>

try:

<img src=“?action=view&id=<?php htmlout($f[‘id’]); ?>”/ >

Hi,
Thanks for your reply. A snippet of the page source looks like this,

        </tr>
      </thead>
      <tbody>
                <tr>
          <td>
            <img src="Captured.JPG" height="187" width="110">

          </td>
          <td>
            <a href="?action=view&amp;id=4"
                >Captured.JPG</a>
          </td>
          <td>image/jpeg</td>
          <td>test</td>
          <td>

To get this page to work at all in the browser I had to not SELECT the filedata field at the end of index.php
excerpt from index.php

include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

try
{
  $result = $pdo->query(
      'SELECT id, filename, mimetype, description
      FROM filestore');
}
catch (PDOException $e)
{
  $error = 'Database error fetching stored files.';
  //include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/error.html.php';
  include 'error.html.php';
  exit();
}

$files = array();
foreach ($result as $row)
{
  $files[] = array(
      'id' => $row['id'],
      'filename' => $row['filename'],
      'mimetype' => $row['mimetype'],
      'description' => $row['description']);
      //'filedata' => $row['filedata']);
}

include 'files.html.php';

As the href is working fine, I would prefer to leave it and just try to solve one problem at a time, to display an image file on the html page.
What should I do now?
Thanks,
Shane

Sorry, I think I edited my post after you’d read it. :slight_smile:

Ha, yes i was getting a bit confused. I will try your suggestion now. thanks

Hi,
Yes that works, fantastic,
thanks for your help,
Shane

If the image is under 32K you can use a Data URI scheme to embed it directly into the output html without having to use a separate PHP file to fetch the image. If you don’t care about IE 8 you can apply this to larger files.

Hi Michael,
Thanks for the Data URI scheme link and info.
Is there any reason why the HTML file, files.html.php does not load (I get a blank white screen) when I include the field ‘filedata’ in the query? Filedata is of type BLOB.
Here is an excerpt from files.html.php:


include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';
try
{
  $result = $pdo->query(
      'SELECT id, filename, mimetype, description, filedata
      FROM filestore');
}
catch (PDOException $e)
{
  $error = 'Database error fetching stored files.';
  //include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/error.html.php';
  include 'error.html.php';
  exit();
}

$files = array();
foreach ($result as $row)
{
  $files[] = array(
      'id' => $row['id'],
      'filename' => $row['filename'],
      'mimetype' => $row['mimetype'],
      'description' => $row['description']),
      'filedata' => $row['filedata']);
}

include 'files.html.php';

Thanks,
Shane