diff --git a/reference/curl/examples.xml b/reference/curl/examples.xml index 71d6f7847110..538211210454 100644 --- a/reference/curl/examples.xml +++ b/reference/curl/examples.xml @@ -4,17 +4,80 @@ &reftitle.examples;
- Basic curl example + Basic curl examples Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init, then you can set all your options for the transfer via the curl_setopt, - then you can execute the session with the - curl_exec and then you finish off - your session using the curl_close. - Here is an example that uses the cURL functions to fetch the + and then send the request with the curl_exec. + + + Here is a simple example that uses the cURL functions to send + a POST request: + + Using PHP's cURL module to send a POST request + + 'bar', 'baz' => 48]; +$url = "http://www.example.com/handler.php"; + +$ch = curl_init($url); + +// tell CURL to return the response instead of sending it to stdout +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + +// set the POST data, corresponding method and headers +curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); + +// send the request and get the response +$response = curl_exec($ch); + +if(curl_error($ch)) { + // handle the error, or just + throw new RuntimeException(curl_error($ch)); +} +]]> + + + + + Another example that uses the cURL functions to send a raw JSON + POST request: + + Using PHP's cURL module to send a JSON POST request + + 'bar', 'baz' => 48]; +$url = "http://www.example.com/api/endpoint"; + +$ch = curl_init($url); + +// tell CURL to return the response instead of sending it to stdout +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + +// set the POST data and corresponding method +curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data)); + +// set the required header +curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); + +// send the request and get the response +$response = curl_exec($ch); + +if(curl_error($ch)) { + // handle the error, or just + throw new RuntimeException(curl_error($ch)); +} +]]> + + + + + Here is another example that uses the cURL functions to fetch the example.com homepage into a file: Using PHP's cURL module to fetch the example.com homepage @@ -32,9 +95,7 @@ curl_exec($ch); if(curl_error($ch)) { fwrite($fp, curl_error($ch)); } -curl_close($ch); fclose($fp); -?> ]]>