In some of the other PHP tutorials we already covered how to make HTTP Requests using the file functions such as file_get_contents and stream_get_contents – but if your host supports it you might also be able to use cURL – not that it will matter which method you use as long as it gets the job done in your situation.
The curl_init function initializes the request, usually assigning it to a variable – in this case $ch – we are going to use this when we add options to the request, such as whether we want the transfer/result returned directly, and the user agent string we want to use.
The curl_setopt function is used to set many different options – not to be covered in this tutorial.
The curl_exec function performs the request, with whatever options we have set. By default it should only return true or false – according to the manual – so we set the CURLOPT_RETURNTRANSFER option to a value of true in order to make it return the content instead of just returning true. Note. it should still return false if something went wrong with the request.
Using CURL for HTTP Requests
Using CURL to make HTTP Requests is not much different than using file_get_contents, the principles are the same.
A working example script to perform a GET request is included below:
<?php // URL to fetch $url = "http://beamtic.com/"; // Initialize cURL session $ch = curl_init($url); // Option to Return the Result, rather than just true/false curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Perform the request, and save content to $result $result = curl_exec($ch); // Close the cURL resource, and free up system resources! curl_close($ch); // Shows the result! echo $result; ?>
It can be a good idea to close – curl_close – the session if looping, unless you are going to overwrite the same session with a new one, or unless you are sure the script is done. In any case, all open sessions will be closed automatically when the script stops, so often it doesn't matter.