Today I am going to demo you how to fetch images (attachments) from salesforce instance in to your PHP script and how you can show those imags on page as a portal or catalog way.
1) index.php script
The below code shows how you can query to attachment object in salesforce to fetch some attachment records. For example i have query the pics (attachment) for my two SFDC contact records in sample code. The concept is simple. You need to query the Id of attachment in your main page, then you will have one another php script which will fetch the SFDC attachment (image) binary data and show the image on screen as embedded. We can wrap/embed that image in <img /> tag directly.
<?php
error_reporting(E_ALL);
require_once ('soapclient/SforcePartnerClient.php');
require_once('connection.php');
$ids = array();
$ids[] = '00390000006IUVK';
$ids[] = '00390000001lwbd';
getPhotos($ids);
function getPhotos($contactids){
$mySforceConnection = getConnection();
$query = "SELECT Id, Name from Attachment Where ParentId in (";
foreach($contactids as $id){
$query .= "'". $id . "',";
}
$query = substr($query , 0, strlen($query) - 1);
$query .= ")";
$queryResult = $mySforceConnection->query($query);
$records = $queryResult->records;
if(count($records) > 0){
echo "<table cellspacing='5' cellpadding='5'><tr>";
foreach($records as $rec){
echo "<td style='text-align:center;font-size:12px;'>".
"<img src='image.php?id=".$rec->Id."' ".
"style='width:200px;height:200px;border:1px solid #ccc;padding:10px'/> <br/>"
. $rec->fields->Name.
"</td>";
}
echo "</table>";
}
return NULL;
}
?>
2) image.php script
This code simply accepts one Id of the attachment record and fetch the binary body of attachment, then it shows that image on the screen as image content. To view this image in other page you simply need to wrap/embed its call into <img /> html tag. Like below:
<img src="image.php?id=00P9000000185ioEAA" />
<img src="image.php?id=00P9000000185ioEAA" />
<?php
error_reporting(E_ALL);
header('content-type: image/jpeg');
require_once ('soapclient/SforcePartnerClient.php');
require_once('connection.php');
getPhotos($_GET['id']);
function getPhotos($id){
$mySforceConnection = getConnection();
$query = "SELECT Id, Name, Body from Attachment Where Id ='" .$id ."'";
$queryResult = $mySforceConnection->query($query);
$records = $queryResult->records;
print_r(base64_decode($records[0]->fields->Body));
return NULL;
}
?>
Here is the demo of the scripts where i am fetching two contact's images from Salesforce and showing on simple PHP page.
http://labs.aslambari.com/sfdc_photos_demo/
Thanks
Aslam Bari