Convert BLOB jumble to 0s and 1s [byte stream to binary string] - php

I have a BLOB column in my MySQL table. When I echo the value of the field using PHP I get
SBτF¶☼╢ñ═∩P╙ _ë ☺K ☺♦ Å☼♂↔☻ ♥
Is there a way for me to convert the binary to a string of 0s and 1s?
This data is NOT an Image and NOT a text, they are small UDP packages of data where the 0s and 1s have significance and I need to load that data and interpret it

I couldn't find a solution to this, so I'm going to reinvent the wheel a bit.
function binDigitsFromString($str) {
$r = '';
for($i=0; $i<strlen($str); $i++) $r .= sprintf("%08b",ord($str[$i]));
return $r;
}

You aren't supposed to enco the blob data directly, without specifying the content type in the header.
For example, if the blob consist of image data for a PNG image, you'd set the header like this:
header("Content-Type: image/png");
echo $myBlob;
and that will render as an image.
This is worth a read: http://www.mysqltutorial.org/php-mysql-blob/

You can Convert BLOB to Char and not to Varchar
You can use CAST function to convert the corresponding value to Character set utf8

Related

Undesired data truncation when updating a MEDIUMBLOB

I'm trying to write in a BLOB in my MariaDB using a PHP post call. This BLOB comes from getting a BASE64 from a canvas:
var data= $('#signatureDiv').signature('toDataURL');
var base64data= data.replace(/^data:image\/(png|jpg);base64,/, "");
$.post("myFunc.php", {imgContents: base64data}, function(data) {});
Now, in myFunc.php:
$imgContents = $_POST['imgContents'];
$decodedPNG = base64_decode($imgContents);
$defTest = "UPDATE recogidas SET FirmaProv = ':blobFirma' WHERE ID=$index";
$preparedpdo = $mypdoObject->prepare($defTest);
$preparedpdo->bindParam(':blobFirma', $decodedPNG, PDO::PARAM_LOB);
$preparedpdo->execute();
echo $decodedPNG;
I decode the PNG to save it as a BLOB. Then I prepare a SQL update to upload this BLOB to a proper MEDIUMBLOB column. However, the data is always truncated to few bytes!! Exactly to those bytes:
3A626C6F624669726D61
When it, as a PNG, needs around 100Kb. I tried using this at the beggining of the PHP:
ini_set("odbc.defaultlrl", "1000K");
But it has no effect. To make sure the decode was right, I tried to echo the decoded BLOB, and it returns if correctly.
Why is my database truncating the data to a pack of bytes?
Extra information: It doesn't matter how the picture I make in the canvas is, the data uploaded to the data base is always those same characters.
Why is my database truncating the data to a pack of bytes?
It isn’t. If you had bothered to check what those hex bytes 3A626C6F624669726D61 actually mean, you would have seen that it is :blobFirma. And since you instructed the database to store that string value in your statement, this is absolutely the result that is to be expected.
If you don’t want to store a fixed string value into the column - then remove the quotes around the placeholder from the statement …

How to convert the PostgreSQL bytea value into Data URL value using PHP

PostgreSQL has this datatype called bytea. It is their version of a blob.
In displaying images, png/jpg/gif, the current trend nowadays is to use Data URLs.
My question is how to convert a bytea value into a Base64 Data URL value?
References
bytea - Binary Data Types. PostgreSQL 9.6 Documentation
Data URL - Copy image as data URI by Umar Hansa. Google Developers. May 2015
You may also fetch the complete image data URL from your database, e.g.:
SELECT 'data:image/gif;base64,' || encode(image_data, 'base64') AS image_url
FROM ...
$img_bin = hex2bin(substr($the_bytea, 2));
$url = 'data:image/gif;base64,' . base64_encode($img_bin);
Postgres bytea is a string starting with \x followed by hexadecimal characters. To get the image in binary format, need to strip off the leading \x and convert from hexadecimal characters to binary with hex2bin. Now that you have it in binary, you can base64_encode it.

Convert hex file to floats in php

I am reading a BLOB from a SQL data base. The file should contain 1024 float value pairs but I have no clue how to convert them. This is my query:
$stmt = $sqlHandle->query('SELECT convert (varchar (max), convert (varbinary (max), blob)) AS dump FROM data WHERE id = 200
This gets me a String with 32842 chars, which starts like this:
0x000008044072A051E00000004072AD70A00000004072BA8F600000004072C7AE200000004072D4CCC00
I do not know how the blob was created. I only that the first pair should look similar to this after being converted:
248.23112 0.000048741
Can someone explain to me how I get the string converted?
<?php
var_dump(hexdec("0x000008044072A051E00000004072AD70A00000004072BA8F600000004072C7AE200000004072D4CCC00"));
?>

Reading binary file in php and converting it into string

I spent almost a day for this , but did not get success.
What i want to do is, i have a binary file "data.dat"
I want to read the file contents and output it in text format in say "data.txt" in php.
I tried unpack function of php, but requires the type to be mentioned as the first argument(May be i am wrong, new to php).
$data = fread($file, 4); // 4 is the byte size of a whole on a 32-bit PC.
$content= unpack("C", $data); //C for unsigned charecter , i for int and so on...
But what if i dont know that at what place , what type of data is stored in the file that i am reading?
This function is restricting me because of the type.
I want something similar to this
$content= unpack("s", $data); //where s can denote to string
Thanks.
PHP does not have a "binary" type. Binary data is stored in strings. If you read binary data from a file, it's already stored as a string. You do not need to convert it into a string.
If the binary data already represents text in some standard encoding, you don't need to do anything as you already have a valid string. If the binary data represents some encoding, you need to know what you need to do with it, we don't know.

How can I convert a large string of base64 image data back to an image with PHP?

I have a large string of base64 image data (about 200K). When I try to convert that data by outputting the decoded data with the correct header, the script dies, as if there isn't enough memory. I get no error in my Apache logs. The example code I have below works with small images. How can I decode a large image?
<?php
// function to display the image
function display_img($imgcode,$type) {
header('Content-type: image/'.$type);
header('Content-length: '.strlen($imgcode));
echo base64_decode($imgcode);
}
$imgcode = file_get_contents("image.txt");
// show the image directly
display_img($imgcode,'jpg');
?>
Since base64-encoded data is cleanly separated every 4 bytes (i.e. 3 bytes of plaintext are encoded into 4 bytes of base64-encoded text), you could split your b64 string into multiples of 4 bytes, and process them separately:
while (not at end of string) {
take next 4096 bytes // for example - 4096 is 2^12, therefore a multiple of 4
// you could use much larger blocks, depends on your memory limits
base64-decode them
append the decoded result to a file, or a string, or send it to the output
}
If you have a valid base64 string, this will work identically to decoding it all at once.
OK, here is a closer resolution. While this seems to decode the base64 data in smaller chunks, I still don't get an image in the browser. If I echo the data before I place a header, I get output. Again, this works with a small image but not a large one. Thoughts?
<?php
// function to display the image
function display_img($file,$type) {
$src = fopen($file, 'r');
$data = "";
while(!feof($src)) {
$data .= base64_decode(fread($src, 4096));
}
$length = strlen($data);
header('Content-type: image/'.$type);
header('Content-length: '.$length);
echo $data;
}
// show the image directly
display_img('image.txt','jpg');
?>
Content-length must specify the actual (decoded) content length not the length of the base64 encoded data.
Though I'm not sure that fixing it would solve this problem...
Save the base64 string to an image file using imagejpeg() or the correct function for the different formats, and then display the image with a simple <img> tag.

Categories