0

I have read numerous articles on stackoverflow and google regarding file upload and show directly in/from MYSQL BLOB column. I donot need to upload file anywhere because only one file is involved in my complete project and that is the logo file to be updated by the user. Although I wanted to do the things with Codeigniter Upload library, but i couldn't complete the code so I was trying simple PHP solution, but it hasnot worked either.

Below is my code.

Code for Upload Form:

<?php echo form_open_multipart('UpdateCompanyInfo'); ?>
        <div class="form-group">
            <label>Logo</label>
            <input type="file" class="form-control" name="logo">
            [200 px (width)x200px (height)]
        </div>
    <div class="box-footer">
        <button type="submit" class="btn btn-primary">Update Logo</button>
    </div>
<?php echo form_close(); ?>

Code for Upload:

$check = getimagesize($_FILES["logo"]["tmp_name"]);
if($check !== false)
 {
    if($check[0]=="200" && $check[1]=="200" )
    {
        $image = $_FILES['logo']['tmp_name'];
        $imageFileType = strtolower(pathinfo($_FILES['logo']['name'],PATHINFO_EXTENSION));
        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
            return '<div class="alert alert-danger">'.$imageFileType.' Logo file of only jpg/png/jpeg type is acceptable.</div>';
        }
        $imgContent = addslashes(file_get_contents($image));
        if($this->db->update("company", array('logo'=>$imgContent)))
        {
            return '<div class="alert alert-success">Logo has been updated successfully.</div>';
        }
        else
        {
            return '<div class="alert alert-danger">Error 101. Failed to update the logo.</div>';
        }
    }
    else
        return '<div class="alert alert-danger">Logo file of only 200px X 200px is acceptable.</div>';
}

Code to show the Image in View

echo '<img src="data:image/png;base64,'.base64_encode($companyinfo[0]->logo).'"/>';

I uploaded the png file, so I have used data:image/png

On inspecting the image element in view, I get the following output:

<img src="data:image/png;base64,iVBORw0KGgpcMFwwXDAN ....... v6/IDhCwtLWDE56vdo6CwCC07dMeva1dhgIGnEBikg7xODG0Pq+m61z8bC4Vqpzxpq6d8BhQK7Q1+rte/oyhK61mIAoGRznxWpiYmb8jaleunKEotrSaXy1Xb1lnxXhXvSAGgKtXBetZJOQEAIQkBAQAhCQEAIQkBACEJA8P7xP2GoiDrA7B2BXDBcMFwwXDBJRU5ErkJggg==">

All articles over internet are showing this solution, but why it is not working at my end?

ITSagar
  • 673
  • 2
  • 10
  • 29
  • 1
    I'm just guessing because I've never stored an image into a database, but if you apply `addslashes()` to the content of the image, wouldn't the data be corrupted for being image data because you've altered it? – DigiLive Feb 16 '19 at 12:31
  • Any errors being returned by either PHP or MySQL? – SpacePhoenix Feb 16 '19 at 12:45
  • @SpacePhoenix Just an icon which appears in the browser when image is not rendered. – ITSagar Feb 16 '19 at 13:30
  • @dnFer I got the solution from marked answer and used it, https://stackoverflow.com/questions/17717506/how-to-upload-images-into-mysql-database-using-php-code – ITSagar Feb 16 '19 at 13:33
  • @dnFer I saw addslashes() used everywhere, but your assumption works. logo is displayed when I remove addslashes() – ITSagar Feb 16 '19 at 13:36

4 Answers4

0

You need to save image as base64_encode in database. Change your code as below line while uploading:

$imgContent = base64_encode(file_get_contents($image));

and when you need to show image, you just need to put content. No need to encode again. As below:

echo '<img src="data:image/png;base64,'.$companyinfo[0]->logo.'"/>';

Hope it helps you.

Rohit Mittal
  • 2,064
  • 2
  • 8
  • 18
0

After trying the suggestions of @dnFer I tried using stripslashes while displaying the image. Things worked fine.

 echo '<img src="data:image/png;base64,'.base64_encode(stripslashes($companyinfo[0]->logo)).'"/>';

But I have a Question. Somewhere I read: "As I was reading this I saw the problem was stripslashes(). Since the data is binary it might contain arbitrary characters that are equal to slashes so it will remove them. "

Will this be a problem? And is my data still safe after stripping away the slashes?

ITSagar
  • 673
  • 2
  • 10
  • 29
0

Short answer:

Change

$imgContent = addslashes(file_get_contents($image));

to

$imgContent = file_get_contents($image);

Long answer:

When applying addslashes(), the binary data of the image changes when it contains one or more single quote ('), double quote ("), backslash (\) or NUL (the NUL byte). It adds a backslash before those characters.

This is probably done to avoid SQL injection at the time prepared statements didn't exist or where rarely used. Eg:

$imgContent = addslashes(file_get_contents($image));
$query = mysql_query ("insert into imageTable values ("INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$imgContent}', '{$image_name}')"));

//Do Stuff like reading the image date from the database...

$imgContent = stripslashes($imgContent);
echo '<img src="data:image/png;base64,' . base64_encode($imgContent) . '"/>';

These days, not using prepared statements is bad practice and I suspect your database library makes use of it as well at the following line:

$this->db->update("company", array('logo'=>$imgContent));

Prepared statements (using mysqli or PDO) statements will prevent SQL injection, which make the use of addslashes() unnecessary.

Notes:

  • Make sure your database data field is large enough (TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB) to contain the complete image (data).
  • Do not store base64 encoded image data in the database as this data is about 30% larger than the binary data.
  • Prefer to store images on the file server instead of the database, since storing lots of data can slow down the database server.
DigiLive
  • 1,093
  • 1
  • 11
  • 28
  • Still as at the 3th code block: `echo ' – DigiLive Feb 19 '19 at 11:27
  • But the issue is no matter what approach I use, logo is visible in web page, but not in the pdf created through mpdf library – ITSagar Feb 19 '19 at 11:35
  • The topic was all about storing image data in to a database and display it by use of the html img tag. Not about the mpdf library. The question is answered since the image does show in the webpage. For problems regarding the mpdf library, you should ask a new question. – DigiLive Feb 19 '19 at 15:32
-2
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image">
</form>

Php code upload.php

<?php
include_once 'dbconn.php';
$image = $_FILE['image'];
$name = $image['name'];
$tmpname = $image['tmp_name'];
$imgdestination = '../img/'.$name;
move_uploaded_file($tmpname, $imgdestination);
?>