0

I want to output an image that I've stored in MYSQL with file_get_contents("http://www.example.com/img.jpg") in an HTML page. I have the following code but I'm stuck as to how to make this work. Right now, it displays gibberish or if I use header, a broken image. I'm using codeigniter:

Model:

public function img_get() {
        $query = $this->db->query('SELECT * FROM imgtable');
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
        }
        return $data;
    }

Controller:

class Site extends CI_Controller {

public function index() {
    $this->load->model('img_model');

    $data['row'] = $this->img_model->img_get();

    $this->load->view('home_view', $data);
}

View:

<html>
<head>
<title>Homepage</title>
</head>
<body>

<h3>Insert the image url</h3>
<br>

<?php 
    foreach ($row as $r) {
        echo $r->img . "<br />";
    }

?>
</body>
</html>
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
StevenWin
  • 33
  • 6
  • What about generating a temporary URL for that image, and put it into the HTML? – songyy Jan 29 '14 at 03:40
  • You need to use – dev7 Jan 29 '14 at 03:41
  • Not being able to serve images directly is yet another reason why storing images in the database is probably a really bad idea. – tadman Jan 29 '14 at 04:09
  • @tadman What's a better way to do it? – StevenWin Jan 29 '14 at 17:42
  • The recommended practice is to save image files somewhere on your filesystem and store a reference to this in your database, that way your server can simply send the file to service the request, no database access needed and your database backups won't be cluttered with gigabytes of binary data. Even better is using an object-store like [Amazon S3](http://aws.amazon.com/s3/) where you don't have to serve the file at all, just provide a URL to the remote resource. – tadman Jan 30 '14 at 16:26
  • @tadman Interesting. I'll give that a try as it does sound simpler. – StevenWin Feb 03 '14 at 22:55

3 Answers3

2

You are trying to display BLOB data:

displaying an image stored in a mysql blob

Show a BLOB image PHP MySQL along with other data

How to display an BLOB image stored in MySql database?

The trick is using:

<img src="data:image/jpeg;base64,' . base64_encode($r->img) . '">

Credit goes to all the other questions and answers on this site :)

Hope this helps!

Community
  • 1
  • 1
dev7
  • 6,259
  • 6
  • 32
  • 65
1

you cannot do that as http need a header to know what is in the content.

<?php
  foreach($row as $r)
  {
     echo "<img src='yourcontroller?id=your_image_id'></br>";
  }
?>
Ahmad Satiri
  • 459
  • 1
  • 7
  • 16
1

You have to first upload that image in your system. So that you can access that image any time with your site's base url.

Snehal S
  • 865
  • 4
  • 13