How to use cURL in PHP, Working examples of cURL in PHP

What is cURL?

cURL is a computer software project providing a code library (libcurl) and command-line tool (curl) for transferring data using various network protocols. Usually PHP comes loaded with libcurl library by default.

Check if cURL is enabled in PHP

Use the following code in your PHP script.

if(function_exists('curl_version')) {
    echo 'cURL is enabled';
} else {
    echo 'cURL is not enabled';
}

Using cURL in PHP- Examples

  1. Writing web page contents to a file

    Use the following code to read an URL and write its contents to a text file in same folder. Create txt file manually if not created already. By default cURL outputs content read from an URL to currently open file buffers.

    $ch = curl_init('http://www.example.com');
    $fp = fopen("sample_output.txt", "w");
    curl_setopt($ch, CURLOPT_FILE, $fp);
    $data = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);
    fclose($fp);
    
    if ($curl_errno > 0) {
        echo "cURL Error ($curl_errno): $curl_error\n";
    }
  2. Return Method – Outputing via CURLOPT_RETURNTRANSFER

    If set to true the CURLOPT_RETURNTRANSFER option makes curl_exec function to return actual content instead of default boolean true/false

    $ch = curl_init('http://www.example.com');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $contents = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_errno > 0) {
        echo "cURL Error ($curl_errno): $curl_error\n";
    } else {
        echo $contents;
    }
  3. Direct Output Method

    In this minimal method all you need to do is to call curl_exec function and it will output read content directly to the browser. This is good quick solution acting as a standalone script that is supposed to respond back to an api call with data.

    $ch = curl_init('http://www.example.com');
    curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_errno > 0) {
        echo "cURL Error ($curl_errno): $curl_error\n";
    }

Conclusion

cURL is a command line tool and code library in most programming languages and operating systems and it is available in PHP as well. Using cURL you can get contents of any public web URL. In PHP you can use curl_setopt settings to either write content into files or return and output them to the console or browser.

 

Leave a Reply