简体   繁体   中英

PHP convert Image file to binary string

I want to convert an image I retrieve from a form to binary string so that I can insert it into a sqlplus table. I've looked around at how to do this conversion and I found that most solutions have this:

example table:

CREATE TABLE images (
    image_id int,
    image blob 
    PRIMARY KEY (image_id));

Form:

<form method="post" enctype="multipart/form-data" action="./Upload/UploadImage.php">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><span style="color: #FF0000;">*</span><br/>
<input type="submit" name="uploadImage" value="Upload Image"></form>

Proposed Conversion Solution:

<?php
    $data = file_get_contents($_FILES["file"]["tmp_name"]);
    $encoded_data = base64_encode($data);
    //echo the data to check it's there
    echo "Encoded Data: " . $encoded_data;
?>

If I echo $data I get a jumbled string, but if i echo $encoded_data I just get: Encoded Data: then nothing.

I want to be able to insert this binary data into my db using

$sql = 'INSERT INTO images VALUES (1, \'' . $encoded_data . '\')';

(I know this is just the sql string - the execution of the statement is not something I felt I needed to include).

UPDATE: I realized I had a type in my $encoded_data = base64_encode($data); line so that works now but the sql throws a string literal too long error.

$fp = fopen($_FILES['file']['tmp_name'], 'r');
$db_img = fread($fp, filesize($_FILES['file']['tmp_name']));
$db_img = addslashes($db_img);
$db_img = base64_decode($db_img);

then

$sql = "INSERT INTO images VALUES (1,'$db_img')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM