Eric Nagel

Hosting Datafeed Images Locally

I have been, or can be if you click on a link and make a purchase, compensated via a cash payment, gift, or something else of value for writing this post. Regardless, I only recommend products or services I use personally and believe will be good for my readers.

I was asked today how to host datafeed images on your local server. Starting with the script given in Step 2 of the datafeed series, we’re just going to add some code after the MySQL query has been executed without errors:

mysql_query($cQuery);
if (mysql_error()) {
	echo("<p><b>MySQL Error: " . mysql_error() . "<br />\n");
	echo("$cQuery</p>");
	echo("<pre>");
	print_r($rsItem);
	echo("</pre>");
	break;
} // ends if (mysql_error())
else {
	$cThumbnail = $rsItem[$rsMap['Thumbnail']];
	if (!empty($cThumbnail)) {
		// http://feeds2.yourstorewizards.com/3365/images/100x500/1992-vintage-pu-er-tea.jpg

		// Get the image extension
		$aTemp = explode('.', $cThumbnail);
		$cExt = array_pop($aTemp);

		// Make this image name
		$cDestination = $rsItem[$rsMap['MerchantID']] . '-' . $rsItem[$rsMap['ProductID']] . '.' . $cExt;

		$cCommand = '/usr/bin/wget ' . $cThumbnail . ' --output-document=' . $baseDir . 'images/products/' . $cDestination;

		`$cCommand`;
	} // ends if (!empty($cThumbnail))
} // ends else from if (mysql_error())

What this does is, looks for a thumbnail image, gets the image file extension (jpg, png, gif), makes a new filename (I based it on the merchantID and productID) then gets the file and writes it back to your server. I’m using wget, because it’s easy to do, and the backtick operator because, again, it’s easy to use.

Then, edit browse.php and make a change to displaying the image:

echo("\t<td width=\"" . round(100/$nCols, 0) . "%\" align=\"center\"><a href=\"/" . simplify($rsData['Name']) . "-p" . $rsData['ProductID'] . ".php\"><img src=\"");

// Does the local file exist?
$aTemp = explode('.', $rsData['Thumbnail']);
$cExt = array_pop($aTemp);
// Make this image name
$cDestination = $rsData['MerchantID'] . '-' . $rsData['ProductID'] . '.' . $cExt;

if (is_file('images/products/' . $cDestination)) {
	echo("/images/products/" . $cDestination);
} // ends if (is_file('images/products/' . $cDestination))
else {
	echo($rsData['Thumbnail']);
} // ends else from if (is_file('images/products/' . $cDestination))
echo("\" style=\"max-width: 125px; max-height: 125px;\" onerror=\"ImgError(this)\" /><br />" . htmlentities($rsData['Name']) . "</a></td>\n");

Same idea, only this time we’re displaying the image, rather than fetching it. If you’re using the fullsize (big) image, too, you’ll need to duplicate the fetching of the images.

You can see this working on my Green White and Black Tea site.

If you really wanted to get fancy, make the image name keyword-rich 🙂