I want to base 64 encode uploaded file then save this into Blob type column of a table in MySQL database.
I have tried built in PHP function base64_encode with file variable but this does not seem to work.
Is there a way we can do this?
The reason is that I do not want to use moveuploaded file into a folder.
Thank you.
While base64 is fine for transport, do not store your images base64 encoded. Base64 provides no checksum or anything of any value for storage. Base64 encoding increases the storage requirement by 33% over a raw binary format.
Generally no. Base64 will occupy more space than necessary to store those images. Depending on the size of your images and how frequently they're accessed, it is generally not an optimal stress to put on the database. You should store them on the file system or in something like Azure blob storage.
BLOBs and Base64 EncodingBLOBs are supported and stored in the XM_TYPE_STRING hash data dictionary format. The reason is that BLOBs are treated in the same manner as strings because they have already been encoded by using base64 encoding before storage into a dictionary file.
As @Sjoerd and @zerkms correctly point out, you do not need to do this - a blob column is be used to store raw binary data, so you can bypass the Base64 process and insert the raw data of the file.
If you want to store images in a database (which, by the way, I personally don't like to do) it is better to store the raw data - Base64 encoding the data makes it larger, and means that it must be decoded before the image is rendered, which adds processing overhead.
This is how you can insert the raw binary data (assuming the MySQL extension):
$data = file_get_contents($_FILES['name_of_control']['tmp_name']);
$data = mysql_real_escape_string($data);
$query = "
INSERT INTO table
(`blob_column`)
VALUES
('$data')
";
mysql_query($query);
If you really do want to Base64 encode it (in which case it could just be stored in a varchar), just just add a base64_encode()
call:
$data = file_get_contents($_FILES['name_of_control']['tmp_name']);
$data = base64_encode($data);
// There is an argument that this is unnecessary with base64 encoded data, but
// better safe than sorry :)
$data = mysql_real_escape_string($data);
$query = "
INSERT INTO table
(`varchar_column`)
VALUES
('$data')
";
mysql_query($query);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With