Performing HTTP requests with cURL in PHP

These examples show how to perform GET and POST requests with the cURL extension for PHP.

<?php

    // Send a GET request to http://snipd.net
    $getExample = curlGET('http://snipd.net/');

    // Send a POST request to http://snipd.net
    $postExample = curlPOST('http://snipd.net/','foo=bar');

    // Print the results
    print $getExample;
    print $postExample;

    function curlGET($requestURL){
        $curlOptions = array(
             CURLOPT_RETURNTRANSFER => true,
             CURLOPT_HEADER         => false,
             CURLOPT_FOLLOWLOCATION => true,
             CURLOPT_AUTOREFERER    => true,
             CURLOPT_CONNECTTIMEOUT => 10,
             CURLOPT_TIMEOUT        => 20,
             CURLOPT_MAXREDIRS      => 20
         );

         $curlHandle = curl_init($requestURL);
         curl_setopt_array($curlHandle, $curlOptions);

         $getResponse = curl_exec($curlHandle);
         curl_close($curlHandle);

         return $getResponse;
    }

    function curlPOST($requestURL,$postFields){
        $postVars = "request=".$requestXML;

        $curlOptions = array(
             CURLOPT_RETURNTRANSFER => true,
             CURLOPT_HEADER         => false,
             CURLOPT_FOLLOWLOCATION => true,
             CURLOPT_AUTOREFERER    => true,
             CURLOPT_CONNECTTIMEOUT => 10,
             CURLOPT_TIMEOUT        => 20,
             CURLOPT_MAXREDIRS      => 20,
             CURLOPT_POST           => true,
             CURLOPT_POSTFIELDS     => $postFields
         );

         $curlHandle = curl_init($requestURL);
         curl_setopt_array($curlHandle, $curlOptions);

         $postResponse = curl_exec($curlHandle);
         curl_close($curlHandle);

         return $postResponse;
    }

?>

Server log:

[23/Jul/2011:15:08:29 +0200] "GET / HTTP/1.1" 200 35099 "-" "snipd.net"
[23/Jul/2011:15:08:30 +0200] "POST / HTTP/1.1" 200 35099 "-" "snipd.net"
This entry was posted in PHP and tagged , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?