GET Request using cURL
There will be times that you will need to pull out data from a web service using PHP’s GET method. In this tutorial I will be demonstrating how you can make a GET Request using cURL.
Example of GET Request:
You can test cURL in your own local server as it’s the same with using a regular form with an action.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $url = "https://website.com/api.php?action=get_data&x=1&y=2"; // Initiate curl $ch = curl_init(); // Disable SSL verification curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Will return the response, if false it print the response curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Set the url curl_setopt($ch, CURLOPT_URL,$url); // Execute $result=curl_exec($ch); // Closing curl_close($ch); // Print the return data print_r(json_decode($result, true)); |
Use json_decode if the return is in json format.
Function:
It’s best to put your cURL GET Request in a function if your a dealing with many get request in all parts of your website
1 2 3 4 5 6 7 8 9 10 11 12 | function cvf_curl_get($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL,$url); $result=curl_exec($ch); curl_close($ch); return json_decode($result, true); } |
Do you need help with a project? or have a new project in mind that you need help with?
Contact Me