A common annoyance in the world of AJAX is the ol’ cross-domain request error. That is, a script sitting on domain1.example.com can’t make AJAX calls to domain2.example.com. This is in place for the sake of security, but sometimes developers have legitimate reasons to do so.
A common workaround is writing a server-side script that will sit on domain1.example.com, and make proxy requests to domain2.example.com, and send the output back to the client. Many times, this is a “quick and dirty” solution to a common problem. You can find many of these short ‘n ugly procedural proxy scripts online.
But what if our needs are more complicated? What if our AJAX calls needed to be made over an authenticated session which requires forwarding of cookies? This is much harder to find online, and is a bit more complicated.
Lastly, just try and find an AJAX proxy that doesn’t rely entirely on cURL as it’s request mechanism. Developers using shared hosting or servers with draconian admins might not of the luxury of access to third-party fluff like cURL.
Over the past few weeks, I’ve developed ajax-proxy over at HUGE in Brooklyn, which is a class and script that solves both of the problems above. Additionally, it’s functionality is entirely encapsulated inside of a re-usable class. It was made so that it could stand alone on a server as proxy.php, or be incorporated into a larger framework like Zend, Kohana, or CodeIgniter.
Here are it’s features:
- Uses cURL, but falls back to the less-speedy fopen if the former sin’t available
- Forwards cookies and other headers in both directions
- Has optional error and exception handling for behavior as a standalone script (frameworks would likely not want this)
- Extremely well documented (I’m a documentation fanatic)
- Written entirely in OO PHP 5, to the Zend standards
Additionally, the proxy underwent 2 weeks of development and intensive code review by the HUGE development team before it’s v1.0 push to GitHub. This is by no means a “quick and dirty” solution — it’s a rock-solid, full featured ajax-proxy that’s dead easy to use. Assuming proxy requests were going to be made to a base url of domain2.example.com, the code to run the proxy looks like:
$proxy = new AjaxProxy('domain2.example.com'); $proxy->execute();
If there’s anyone that loves simplicity, it’s me. Of course, there are more constructor options, but that’s better left to the README.
Anyway, the project is posted on GitHub at: http://github.com/hugeinc/ajax-proxy, where there is also pretty extensive documentation on the class’ usage. For documentation about the internal class members and methods, everything is doc’d with PHPDoc.
As a side note, I think it’s about time that I add KLogger to github. I get a fair amount of emails from people telling me they’re using it, and it’s about time I incorporated some new features in, like rolling log files, etc. I’m tired of having dusty old zip files sitting around. I’ll make another post when I put it up there!