PHP/cURL

Below is a simple example for GET and POST Request.

GET Request

// Get cURL resource
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, 'http://yourtargeturl.com');

// Send the request & save response to $resp
$resp = curl_exec($curl);

// Close request to clear up some resources
curl_close($curl);

If you want to send a parameter along in the request, simply append them in the URL.

ex: http://yourtargeturl.com/?var1=value1&var2=value2

POST Request

Simply set the CURLOPT_POST option to true. If you want to send parameters, just add CURLOPT_POSTFIELDS option with an array of data.

// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://www.example.com',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        item1 => 'value',
        item2 => 'value2'
    )
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
Categories PHP

Leave a Reply