DaniWeb IT Discussion Community

Code Snippets (http://www.daniweb.com/code/)
-   php (http://www.daniweb.com/code/php.html)
-   -   PHP Proxy Solution for cross-domain AJAX scripting (http://www.daniweb.com/code/snippet494.html)

Troy php syntax
May 23rd, 2006
This is a PHP script that allows javascript clients to request content they otherwise would not be able to. With the popularity of AJAX (using the XmlHttpRequest object in the browser), many developers are becoming aware of the cross-domain scripting limitation. This is a security feature that prevents client-side scripts from accessing content on domains other than the current website domain.

My PHP Proxy is the solution. Simply place this PHP script on your PHP-enabled webserver. Then have your javascript make cross-domain requests through the proxy. Simple, fast, elegant--a perfect solution.

PHP Proxy makes use of my class_http object. Details and code available at http://www.troywolf.com/articles. Full source for PHP Proxy is below.

  1. <?php
  2. // FILE: proxy.php
  3. //
  4. // LAST MODIFIED: 2006-03-23
  5. //
  6. // AUTHOR: Troy Wolf <troy@troywolf.com>
  7. //
  8. // DESCRIPTION: Allow scripts to request content they otherwise may not be
  9. // able to. For example, AJAX (XmlHttpRequest) requests from a
  10. // client script are only allowed to make requests to the same
  11. // host that the script is served from. This is to prevent
  12. // "cross-domain" scripting. With proxy.php, the javascript
  13. // client can pass the requested URL in and get back the
  14. // response from the external server.
  15. //
  16. // USAGE: "proxy_url" required parameter. For example:
  17. // http://www.mydomain.com/proxy.php?proxy_url=http://www.yahoo.com
  18. //
  19.  
  20. // proxy.php requires Troy's class_http. http://www.troywolf.com/articles
  21. // Alter the path according to your environment.
  22. require_once("class_http.php");
  23.  
  24. $proxy_url = isset($_GET['proxy_url'])?$_GET['proxy_url']:false;
  25. if (!$proxy_url) {
  26. header("HTTP/1.0 400 Bad Request");
  27. echo "proxy.php failed because proxy_url parameter is missing";
  28. exit();
  29. }
  30.  
  31. // Instantiate the http object used to make the web requests.
  32. // More info about this object at www.troywolf.com/articles
  33. if (!$h = new http()) {
  34. header("HTTP/1.0 501 Script Error");
  35. echo "proxy.php failed trying to initialize the http object";
  36. exit();
  37. }
  38.  
  39. $h->url = $proxy_url;
  40. $h->postvars = $_POST;
  41. if (!$h->fetch($h->url)) {
  42. header("HTTP/1.0 501 Script Error");
  43. echo "proxy.php had an error attempting to query the url";
  44. exit();
  45. }
  46.  
  47. // Forward the headers to the client.
  48. $ary_headers = split("\n", $h->header);
  49. foreach($ary_headers as $hdr) { header($hdr); }
  50.  
  51. // Send the response body to the client.
  52. echo $h->body;
  53. ?>