Advertisement
khlau

HTTP POST using CURL with HTTP Status Code Checking

Oct 6th, 2013
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.89 KB | None | 0 0
  1. //set POST variables
  2. $url = 'http://domain.com/get-post.php';
  3. $fields = array(
  4.                         'lname' => ($last_name),
  5.                         'fname' => ($first_name),
  6.                         'title' => ($title),
  7.                         'company' => ($institution),
  8.                         'age' => ($age),
  9.                         'email' => ($email),
  10.                         'phone' => ($phone),
  11.                         // Upload a file, by prepend @ followed by file full path
  12.                         'photo' => sprintf('@%s', '/home/abc/pic/cat.jpg')
  13.                 );
  14.  
  15. //open connection
  16. $ch = curl_init();
  17. //set the url, number of POST vars, POST data
  18. curl_setopt($ch,CURLOPT_URL, $url);
  19. curl_setopt($ch,CURLOPT_POST, count($fields));
  20. curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
  21. curl_setopt($ch, CURLOPT_HEADER, 1);
  22. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  23.  
  24. //execute post
  25. $strContents = curl_exec($ch);
  26. // Get the header and body
  27. $intHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  28. $strHeader = substr($strContents, 0, $intHeaderSize);
  29. $strBody = substr($strContents, $intHeaderSize);
  30.  
  31. // handle error; error output
  32. if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
  33.   var_dump($strBody);
  34. }
  35.  
  36. //close connection
  37. curl_close($ch);
  38.  
  39. /*
  40. $strHeader can be exploded for further use
  41. $arrHeader = explode("\r\n", $strHeader);
  42. */
  43.  
  44. /*
  45. curl_getinfo($ch) returns an array similar to the following:
  46. Array
  47. (
  48.     [url] => http://www.example.com/path/to/form
  49.     [content_type] => text/html; charset=UTF-8
  50.     [http_code] => 200
  51.     [header_size] => 516
  52.     [request_size] => 197
  53.     [filetime] => -1
  54.     [ssl_verify_result] => 0
  55.     [redirect_count] => 0
  56.     [total_time] => 2.256708
  57.     [namelookup_time] => 0.672754
  58.     [connect_time] => 0.899986
  59.     [pretransfer_time] => 0.900012
  60.     [size_upload] => 240
  61.     [size_download] => 18717
  62.     [speed_download] => 8293
  63.     [speed_upload] => 106
  64.     [download_content_length] => 0
  65.     [upload_content_length] => 240
  66.     [starttransfer_time] => 1.12957
  67.     [redirect_time] => 0
  68. )
  69.  
  70. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement