Ramblings

November 23, 2009

Flash and Salesforce: HTTP POST using PHP but with no access to cURL

Filed under: cool, php, salesforce, tip — michaelangela @ 11:53 pm

Have a client who needs some Flash to HTTPS webservice functionality. Flash and HTTPS are a difficult pair when not on the same host and all the policy files aren’t in place. The simple solution is a proxy. But this particular client’s webserver doesn’t have cURL. What to do? Making streams with a custom context is really simple. Looks good too. In the end I didn’t use fopen, stream_get_contents, etc. though. I used file_get_contents.

HTTP POST from PHP, without cURL – Evil, as in Dr.

I don’t think we do a very good job of evangelizing some of the nice things that the PHP streams layer does in the PHP manual, or even in general. At least, every time I search for the code snippet that allows you to do an HTTP POST request, I don’t find it in the manual and resort to reading the source. (You can find it if you search for “HTTP wrapper” in the online documentation, but that’s not really what you think you’re searching for when you’re looking).

And there is also a note on php.net about doing this with https.

So in the end my code looked like (no closing php tag intentional):

<?php
$url = "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8";
$data = $_POST;
$data = http_build_query($data);
$result = do_post_request($url, $data);
echo $result;

function do_post_request($url, $data, $optional_headers = null)
{
   $params = array('http' => array(
                'method' => 'POST',
                'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
	                . "Content-Length: " . strlen($data) . "\r\n",
                'content' => $data
             ));
   if ($optional_headers !== null) {
      $params['http']['header'] = $optional_headers;
   }
   $ctx = stream_context_create($params);
   $response = file_get_contents($url, false, $ctx);
   if ($response === false) {
      throw new Exception("Problem reading data from $url, $php_errormsg");
   }
   //var_dump($response);
   return $response;
}
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: