3

I've read many posts but for some reason it still doesn't work. As in the title, I want to display image in the website which is stored in MySQL as MEDIUM BLOB. Here is the code which uploads the image:

if (isset($_FILES["fileToUpload"]["tmp_name"])) {
    if(getimagesize($_FILES["fileToUpload"]["tmp_name"]) == FALSE)
        echo '<p style="color: red" >No file selected</p>';
    else {
        echo '<p style="color: red" >SELCETED</p>';
        $image= addslashes($_FILES["fileToUpload"]['tmp_name']);
        //$imageName= addcslashes($_FILES["fileToUpload"]['name']);
        $image = file_get_contents($image);
        $image = base64_encode($image);
    }
}

if (isset($_POST['trescText']) )
    $trescText=$_POST['trescText'];

if($titleText != ""&& $trescText != "") {
    $stmt = $conn->prepare("INSERT INTO blog (title,cykl,tresc, image) VALUES('$titleText','$cyklText','$trescText','$image')");
    $stmt->execute();
    header('Location: addPost.php');
}

$conn->close();

And the code which displays it:

<?php
$stmt = $conn->prepare("SELECT image FROM blog WHERE id='98'");
$stmt->execute();
$stmt->bind_result($image);
while ($stmt->fetch()) {
    // echo '<img src="data:image;base64,'$image' "/>';
    echo '<img src="data:image/jpeg;base64,'.base64_encode($image) .'" />';
}
?>

The problem is that instead of orginal image I get this:

enter image description here

14
  • 1
    You base64 encode the image twice, once when inserting it into the database, once when sending it to the browser. Commented Mar 23, 2017 at 16:34
  • Apart from that a warning: your code is mile wide open to sql injection attacks... Commented Mar 23, 2017 at 16:34
  • @arkascha: Answers don't go in the comments. Commented Mar 23, 2017 at 16:36
  • @BoundaryImposition That is not a full answer in my eyes, I just hint to the cause. That is why it certainly should be a comment. A full answer should contained fixed code. Commented Mar 23, 2017 at 16:36
  • 2
    I suggest you start reading the documentation of the tool you use: php.net/manual/en/mysqli.quickstart.prepared-statements.php Commented Mar 23, 2017 at 16:52

1 Answer 1

2

You base64-encoded it twice: once when inserting it into the database, and again when sending it to the browser.

Base64-encoding has a tangible result; that is, it transforms the data. It is not temporary. The data in your database are the base-64 representation of your image's bytes, and that's the same data that you pull out later with SELECT.

So you only want to do the encoding once.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.