Jquery AJAX cross-domain proxy with php


/ Published in: PHP
Save to your folder(s)

A PHP proxy for jQuery AJAX cross-domain requisitions, created to support friendly-url API\\\\\\\'s.


Copy this code and paste it in your HTML
  1. <?php
  2. $base_url = 'http://www.yoursite.com/api/';
  3. $chamada = explode('/', $_SERVER['PHP_SELF']);
  4. $chamada = $chamada[2]; // if this php file is in a subdirectory you may change this key
  5. $url = $base_url.$chamada;
  6. $method = (!empty($_POST)) ? 'post' : 'get';
  7.  
  8. $ch = curl_init();
  9.  
  10. if ($method == 'get')
  11. {
  12. if ($_SERVER['QUERY_STRING']) $url .= '?' . $_SERVER['QUERY_STRING'];
  13.  
  14. curl_setopt($ch, CURLOPT_HEADER, 0);
  15. curl_setopt($ch, CURLOPT_URL, $url);
  16. }
  17. else
  18. {
  19. curl_setopt($ch, CURLOPT_POST, true);
  20. curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
  21. curl_setopt($ch, CURLOPT_URL, $url);
  22. }
  23.  
  24. $data = curl_exec($ch);
  25. ?>
  26.  
  27. <!-- Example -->
  28. $.get('proxy.php/my_api_call');
  29. $.post('proxy.php/my_post_api', {id:user_id});

URL: http://www.lsouza.pro.br

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.