Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Storing Images in MySQL Revisited

Sending an Image

After an image is uploaded the user is shown that image. This is achieved using the view.php script that the user is redirected to after uploaded their image. We'll also redirect to this script from the image listing we'll implement in the next section.

To implement this script we need to read in the ID that is passed to the script in the id URL parameter. We then try to load the image from the database based on the given ID.

If an image cannot be found for the given ID (or if the ID isn't included) we send a 404 File Not Found error.

If the image is found we can output it to user. We must send various headers so the user's browser can understand the response.

The only mandatory header is the Content-type header. This tells the browser to expect an image. The value we send with this is stored in the mime_type column in our database.

We also send the Content-length header. This tells the browser how big the file is. This is especially useful for extremely large files, as it allows the browser to tell the user how long the file will take to download.

Listing 9 Downloading an image stored in the database (view.php)
    try {
        if (!isset($_GET['id'])) {
            throw new Exception('ID not specified');
        $id = (int) $_GET['id'];
        if ($id <= 0) {
            throw new Exception('Invalid ID specified');
        $query  = sprintf('select * from images where image_id = %d', $id);
        $result = mysql_query($query, $db);
        if (mysql_num_rows($result) == 0) {
            throw new Exception('Image with specified ID not found');
        $image = mysql_fetch_array($result);
    catch (Exception $ex) {
        header('HTTP/1.0 404 Not Found');
    header('Content-type: ' . $image['mime_type']);
    header('Content-length: ' . $image['file_size']);
    echo $image['file_data'];

In This Article

Bonus listings: 1 available