Being Binary in SOAP

Well, it might not be the best way to do it, but here’s a way I found to send binary data via PHP’s SOAP extension from one place to another:

Server:

function recieveFile($data){
	$data=base64_decode($data);
	$path='/my/file/path/img_out.gif';
	$fp=fopen($path,'w+');
	if($fp){ fwrite($fp,$data); fclose($fp); }

	return strlen($data).' written';
}
$input	= file_get_contents("php://input");
$server = new SoapServer(
	'http://[my url here]/binary.wsdl',
	array('encoding'=>'ISO-8859-1')
);
$server->addFunction('recieveFile');
$server->handle();

and the Client:

ini_set("soap.wsdl_cache_enabled", "0");

//send binary data
$client=new SoapClient(
	'http://[my url here]/binary.wsdl',
	array('encoding'=>'ISO-8859-1')
);

$data=file_get_contents('/my/file/path/img_to_send.gif');
$ret=$client->recieveFile(base64_encode($data));
print_r($ret);

It’s pretty basic – the client just reads in the file’s information, runs it through a call to base64_encode before it’s sent off to the server. Once it’s there a mirror call to base64_decode gets the content back to normal and it’s written out to the “img_out.gif” file on the remote server.

It’s probably not the best way to do it, but its one that I’ve found that works quickly and easily. I tried to just send the binary data without base64 encoding it and it didn’t want to cooperate (it was only getting the first chunk of data). I don’t know how well it’ll perform with larger files, though – we shall see.

Category: PHP 7 comments »

7 Responses to “Being Binary in SOAP”

  1. Lars Pohlmann

    I do something similar in a productive environment for some time now. If you have very large files you might want to split the base64-encoded data and transfer them as chunks.

    compressing before base64-encoding might also be a good idea, but that depends on the nature of the data.

  2. Lars Pohlmann

    oh, I have to add, there is the “official” way to do it as well, but I never got my head around it:
    http://www.w3.org/TR/SOAP-attachments

  3. Alternativa para anexos em SOAP at Renan de Lima

    [...] http://blog.phpdeveloper.org/?p=88 Posted in [...]

  4. Shelon Padmore

    Very interesting, I think i’ll give this a try

    - Shelon Padmore

  5. Adam

    I really do love SOAP!

  6. PHP Encoder

    SOAP is great, finally we have natural PHP support. Going to save your tip regarding transferring binary data!
    Thanks!

  7. Zashkaser

    @Laura many thanks. Afraid I don ‘t have time to sign up though it sounds interesting


Leave a Reply



Back to top