Posted By

wnasich on 11/24/10


Tagged

curl php client rest


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

vehler


Simple PHP Rest Cient using curl


 / Published in: PHP
 

URL: http://singletonio.blogspot.com/2009/07/simple-php-rest-client-using-curl.html

  1. <?php
  2. $url = 'https://www.google.com';
  3. $method = 'POST';
  4.  
  5. # headers and data (this is API dependent, some uses XML)
  6. $headers = array(
  7. 'Accept: application/json',
  8. 'Content-Type: application/json',
  9. );
  10. $data = json_encode(array(
  11. 'firstName'=> 'John',
  12. 'lastName'=> 'Doe'
  13. ));
  14.  
  15. $handle = curl_init();
  16. curl_setopt($handle, CURLOPT_URL, $url);
  17. curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
  18. curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
  19. curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
  20. curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
  21.  
  22. switch($method) {
  23. case 'GET':
  24. break;
  25. case 'POST':
  26. curl_setopt($handle, CURLOPT_POST, true);
  27. curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
  28. break;
  29. case 'PUT':
  30. curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
  31. curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
  32. break;
  33. case 'DELETE':
  34. curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
  35. break;
  36. }
  37.  
  38. $response = curl_exec($handle);
  39. $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);

Report this snippet  

You need to login to post a comment.