curl request in php

To send a curl request in PHP, you can use the curl function that comes bundled with PHP. Here's an example of how to make a simple GET request using curl:

main.php
// create a new curl resource
$curl = curl_init();

// set the URL and other options
curl_setopt_array($curl, array(
    CURLOPT_URL => 'http://example.com/api',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json'
    )
));

// execute the request
$response = curl_exec($curl);

// check for errors
if(curl_error($curl)){
    echo 'Request Error:' . curl_error($curl);
}

// close curl resource and free up system resources
curl_close($curl);

// display the response
echo $response;
542 chars
26 lines

In this example, we first create a new curl resource using curl_init(). We then set the URL we want to make the request to and any other options we need using curl_setopt_array(). Here, we are setting the CURLOPT_RETURNTRANSFER option to true so that we can capture the response in a variable. We're also setting the CURLOPT_HTTPHEADER option to include a header of Content-Type: application/json.

Once we have set all the options, we execute the request using curl_exec(). We then check for any errors using curl_error() and then close the curl resource and free up any system resources using curl_close().

Finally, we display the response using echo.

related categories

gistlibby LogSnag