Posted By

benjaminpearson on 09/15/09


Tagged

curl php rest


Versions (?)

PHP REST


 / Published in: PHP
 

A set of drop in rest methods for php. Curl options can be added/removed/modified, but this gets you going.

Various sources were used to build this code snippet - I can't remember all of them. At least one of the sources was http://snipplr.com/view/17733/php-curl-post/

  1. function construct_query_string($data_array) {
  2. $output = array();
  3. foreach($data_array as $key => $value) {
  4. $output[] = urlencode($key).'='.urlencode($value);
  5. }
  6. return implode("&",$output);
  7. }
  8.  
  9. function http_get($url) {
  10. $c = curl_init();
  11. curl_setopt($c, CURLOPT_URL, $url);
  12. curl_setopt($c, CURLOPT_HTTPGET, true);
  13. // SSL verifier should be set to true for higher
  14. // security, but causes issues on some platforms
  15. curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
  16. curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  17. $output = curl_exec($c);
  18. curl_close($c);
  19. return $output;
  20. }
  21.  
  22. // $data_string should be in the format of something like "name=fred&age=12"
  23. // use the "construct_query_string" method above to build this string from an array
  24. function http_post($url, $data_string) {
  25. $c = curl_init();
  26. curl_setopt($c, CURLOPT_URL, $url);
  27. curl_setopt($c, CURLOPT_POST, 1);
  28. // SSL verifier should be set to true for higher
  29. // security, but causes issues on some platforms
  30. curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
  31. curl_setopt($c, CURLOPT_POSTFIELDS, $data_string);
  32. curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  33. $output = curl_exec($c);
  34. curl_close($c);
  35. return $output;
  36. }
  37.  
  38. function http_delete($url) {
  39. $c = curl_init();
  40. curl_setopt($c, CURLOPT_URL, $url);
  41. // SSL verifier should be set to true for higher
  42. // security, but causes issues on some platforms
  43. curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
  44. curl_setopt($c, CURLOPT_CUSTOMREQUEST, 'DELETE');
  45. curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  46. $output = curl_exec($c);
  47. curl_close($c);
  48. return $output;
  49. }

Report this snippet  

You need to login to post a comment.