PHP cross domain ajax Proxy
I received a javascript application, that made cross domain calls to a webservice using the flensed library, this was pretty neat, but filling the dropdown boxes was very slow. Not to mention unnecessary, because I was going to embed the dropdown values into this modal window.
What I did was to refactor the javascript app, into php code to fill the values, and left the important webservice requests alone, I didn’t want to use the flXHR library, because the widget was so simple, so what I did was a php json-rpc proxy client, winch its work would be to post the data received from the client to a remote webservice.
I’m using Zend_Json to encode/decode json, because the php version on production is 5.1, and the php json extensions are not available.
First I create an object that will hold the data to be sent.
01 $re = new stdClass();02 $re->brand_id = $_POST['brand_id'];03 $names = $_POST['domains'];04 05 $domains = explode(",", $names);06 $filteredDomains = array();07 foreach ($domains as $domain) {08 $domainParts = parse_url($domain);09 if (isset($domainParts['host']) && $domainParts['host'] != '') {10 $filteredDomains[] = $domainParts['host'];11 }12 }13 $re->domains = $filteredDomains;
That was simple, I didn’t have to worry about filtering the user input, because the webservice will take care of that, the only thing I do, is create an array of domains, with has only the host part.
after I have my Object ready I encode it as a json string, open a socket and make the request, here is how I did it:
01 $request = Zend_Json::encode($re);02 $opts = array ('http' => array (03 'method' => 'POST',04 'header' => 'Content-type: application/json',05 'content' => $request06 ));07 $context = stream_context_create($opts);08 $conection = $fp = fopen($url, 'r', false, $context);09 if ($conection) {10 $reply = '';11 while($row = fgets($fp)) {12 $reply.= trim($row)."\n";13 }14 $reply = Zend_Json::decode($reply);
Pretty simple no?