I need my PHP page to show my BLOB image from mysql database

I need my PHP page to show my BLOB image from mysql database

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Rendering BLOB Images: Why echo Breaks Your Gallery

You are encountering a classic server-side rendering issue where PHP treats your database field as text rather than binary data. The symptom you described—garbled characters preceding the image tag and a browser interpreting the URL as plain text—is the direct result of sending the raw binary stream to the client before the browser has finished parsing the HTML document structure.

To render an image stored directly in a MySQL BLOB column, you must stop treating the database row like a string variable. In your current implementation, you are echoing the <img> tag while simultaneously trying to send the binary content. Without explicit handling, PHP outputs the HTML first, followed by the BLOB data, or it treats the BLOB as a string and attempts to escape special characters (like quotes), resulting in the mojibake (garbled text) you see in your browser.

The solution relies on two distinct mechanisms: Output Buffering and Content-Type Headers.

Handling Binary Data with readfile

The most reliable way to serve a BLOB image is to use PHP's readfile() function rather than echoing the string contents of the database field directly. When you execute $row2['image'], PHP reads the binary data into memory as a string. If you then concatenate this string into an HTML echo statement, PHP might inadvertently apply escaping or output it in the wrong context.

By using readfile(), you instruct PHP to read the file (or memory stream) and send its raw bytes directly to the standard output without any further processing. This bypasses the issue of character encoding conflicts between the binary image data and the surrounding HTML text.

// Fetch the technician record
$query_Recordset2 = "SELECT * FROM technician WHERE techID=" . $row1["techID"];
$Rs2 = mysql_query($query_Recordset2) or die(mysql_error());
$row2 = mysql_fetch_assoc($Rs2);

// Set the correct MIME type immediately
header('Content-Type: image/jpeg');

// Check if an image actually exists in the BLOB to prevent 500 errors
if ($row2['image'] && !empty($row2['image'])) {
    // readfile() outputs the raw bytes directly to the browser
    // It does not echo them as part of the HTML string
    readfile($row2['image']);
}

// Optional: Stop script execution after sending binary data
exit;

The Critical Role of header()

You asked where to place 'Content-type: image/jpeg'. The answer is at the very top of your response, before any HTML tags are echoed and before any output buffering occurs.

The HTTP protocol requires that the browser knows how to interpret the incoming stream based on the Content-Type header. If you send binary JPEG data without this header, the browser defaults to text/plain. Consequently, it attempts to render every byte of your image as text characters. This is why you see the "broken image" icon followed by a long string of non-ASCII characters in your source view; the browser is literally trying to display the hex values of your image pixels as text.

In your specific case, placing header('Content-Type: image/jpeg'); immediately after your query and before the readfile() call ensures the browser switches into binary mode for that response segment. Note that if you are using Laravel or a modern framework like Symfony, you should use the built-in Response objects instead of raw header() calls, as they manage output buffering automatically and prevent accidental text leakage from previous responses.

Why Your Current Approach Fails

Your original code attempted to embed the image source inside an <img> tag:

echo "<dt><strong>Technician Image:</strong></dt><dd>" . '<img src='.$row2['image']. ' ...' . "</dd>";

This approach fundamentally misunderstands how BLOBs work in HTML. The src attribute of an <img> tag expects a URL (e.g., /images/photo.jpg). It does not expect raw binary data to be injected directly into the source code.

When you use readfile() without an <img> tag, you are effectively serving the image as a standalone file via a direct HTTP response. This is often cleaner for simple pages because it avoids the complexity of trying to pipe binary streams through HTML rendering engines. If you absolutely require the image to appear within your layout structure (with captions, alt text, etc.), you must separate the concerns:

  1. Send the BLOB as a raw response (using readfile()).
  2. Do not wrap it in an <img> tag on the same request.
  3. If you need HTML context, consider storing images in the filesystem and serving them via relative paths, or use Laravel's Storage facade to generate temporary URLs for secure access.

Migration Considerations

Your source material references the legacy mysql_* functions (e.g., mysql_query, mysql_fetch_assoc). These extensions were deprecated in PHP 5.5.0 and removed in PHP 7.0.0. If you are deploying this code today, you must migrate to mysqli or PDO.

Using PDO prepared statements is highly recommended to prevent SQL injection when injecting $row1["techID"]:

$stmt = $pdo->prepare("SELECT * FROM technician WHERE techID = ?");
$stmt->execute([$row1['techID']]);
$row2 = $stmt->fetch();

This migration path ensures your application remains secure and compatible with modern PHP versions. Additionally, if you are building a new project from scratch, the Laravel framework provides robust tools for handling media storage and serving images securely via signed URLs, reducing the need to manually manage BLOBs in the database entirely.

Our network