One of the nice things about PHP is how extremely quick it is to hack together a script that will save your day.
Today, I needed to throw together a script for converting some images stored as BLOBs in an old MySQL database of mine, to JPEG files stored on the file system (obviously, I knew that my database only contained JPEGs). It was a one time job, and so I set out to create a quick and dirty script to get the job done.
The job only took me about 20 lines of code, due to PHP’s built-in MySQL support and file handling support. I’ve cleaned it up a bit before posting it here, though, so now it takes a whole lot of 27 lines due to the verboseness of the somewhat cleaned up code.
In cases like this, hard coding the DB credentials and directory paths wont make me loose sleep. Neither does doing it the procedural way. The script did it’s job, and I got what I wanted … without spending a single calorie too much.
<?php
$conn = mysql_connect('localhost', 'myuser', 'mypass');
mysql_select_db('mydb', $conn);
// returns rows of id, img_name and img_data
$sql = 'select * images';
$queryResult = mysql_query( $sql, $conn );
while( $row = mysql_fetch_object( $queryResult )) {
processRow( $row );
}
mysql_close($conn);
function processRow( $row ) {
$basedir = 'images/';
$imagename = makeSafeImageName( $row->img_name );
// in my case, file names are not unique, so I add the id
$filename = $basedir . $imagename . '-' . $row->id . '.jpg';
file_put_contents( $filename, $row->img_data );
echo 'done dumping ' . $filename ."\n";
}
function makeSafeImageName( $source ) {
return strtolower(preg_replace('/([^\w\d\-_]+)/', '-', $source));
}
?>
(Execute from command line with php my-script.php, or web server).
Rob
/ 08/04/2011You Rock! Exactly what I was looking for. (How often does that happen on the web?). Worked like a charm. -thx.
snovyda
/ 14/04/2011Thank you so much!!!
I’m a beginner and looked for this stylish and simple solution too long (almost 2 hours!)