Simple Request and Response Handling

<?php
$ch = curl_init('http://localhost.example/');
curl_setopt($ch, CURLOPT_RETURNTRANSER, true);
$response = curl_exec($ch);
curl_close($ch);
?>

Let’s look at this line by line.

  • curl_init is called and passed ’http://localhost.example/path/to/form’ as the URL for the request. Note this parameter is optional and can also be specified by calling curl_setopt with the cURL session handle ($ch in this case), the CURLOPT_URL constant, and the URL string.
  • curl_setopt is called to set the configuration setting represented by the CURLOPT_RETURNTRANSFER parameter to have a value of true. This setting will cause cu rl_exec to return the HTTP response body in a string rather than outputting it directly, the latter being the default behavior.
  • curl_exec is called to have it execute the request and return the response body.
  • curl_close is called to explicitly close the cURL session handle, which will no longer be reusable after that point.

A useful setting worth mentioning early on is CURLOPT_VERBOSE, which outputs debugging information when set to true. This output is sent to either stderr (the default) or the file referenced by the value of the CURLOPT_STDERR. 


© cURL Extension — Web Scraping

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (30.08.2014)
Views: 334 | Rating: 0.0/0
Total comments: 0
avatar