aishazafar
aishazafar

Reputation: 1110

Download image from blob field to hard disk using php

I have a mysql blob field in which our team stored an image for every record. Now I want to download all images on my hard disk through php script. A prompt response will be appreciated.

Best Regards...

Aisha

Upvotes: 0

Views: 5811

Answers (3)

fnkr
fnkr

Reputation: 10065

$result=mysql_query("SELECT * FROM test WHERE 1");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $filename = rand(1, 100).'.txt';
    file_put_contents('./'.$filename, $row['blob']);
}

This is working (tested).
It wil save the file under a random filename (1-100.txt).
You can change the filename by changing $filename.

And here is a simple sample MySQL-table with 2 demo files with content Test #1 and Test #2:

CREATE TABLE IF NOT EXISTS `test` (`blob` blob NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `test` (`blob`) VALUES(0x5468697320697320746573742023312e), (0x5468697320697320546573742023322e);

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 4305

You can try this also........

function save_file($file_id, $target_folder) {
$result       = $DB->get_file($file_id);   
$file_content = $result->fields['your_file_content_field'];
$name         = $result->fields['name'];

/* Decode only if the file contents base64 encoded 
 * before inserting to database.
 */
$file_content = base64_decode($file_content);

return file_put_contents($target_folder.'/'.$name, $file_content);
}

Upvotes: 0

ogres
ogres

Reputation: 3690

you can use file_put_contents,

fetch rows from your database and foreach row write blob/data to file

Error in Writing to Image file from PHP

http://php.net/manual/en/function.file-put-contents.php

Upvotes: 0

Related Questions