Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert jpg image to proper blob data type using php

Tags:

php

blob

fread

<?php
$file_name = $_FILES['files']['name'];
$tmp_name  = $_FILES['files']['tmp_name'];
$file_size = $_FILES['files']['size'];
$file_type = $_FILES['files']['type'];

// The codes written above work fine and have proper information.

$fp = fopen($tmp_name, 'r'); // This one crashes.
$file_content = fread($fp, $file_size) or die("Error: cannot read file");
$file_content = mysql_real_escape_string($file_content) or die("Error: cannot read file");
fclose($fp);

....

I'm a newbie to PHP stuff. I'm trying to store a jpg image as blob in a database but terribly struggling with it :( I tried many tutorials and read documents but still no luck. Any suggestions or tutorials that might help me out..?

like image 603
Raccoon Avatar asked Dec 07 '25 09:12

Raccoon


1 Answers

When opening binary files with fopen(), use the rb mode, ie

$fp = fopen($tmp_name, 'rb');

Alternatively, you may simply use file_get_contents(), eg

$file_content = file_get_contents($tmp_name);

To enable better error reporting, place this at the top of your script

ini_set('display_errors', 'On');
error_reporting(E_ALL);
like image 172
Phil Avatar answered Dec 08 '25 21:12

Phil