Speed up development with full-stack environments for every branch.

Learn More

Curl module example - Fetching url and displaying the HTTP response

Forked from Hello World.

335 Runs 1154 Views 426 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?php

/**
 * Curl example - Fetching an url and displaying the HTTP Response
 */
//initializes a new session and return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions.
$ch = curl_init();

// set the url to fetch 
curl_setopt($ch, CURLOPT_URL, "google.com");

//return the transfer (the result of curl_exec()) as a string instead of outputing directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//return the HTTP Response header using the callback function readHeader
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'readHeader');

// execute the curl session
curl_exec($ch);

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

//the callback function used to retreive the header info
function readHeader($ch, $string) {
    $length = strlen($string);
    //only display the headers with content
    if (trim($string) != '')
        echo "<center>Header: $string</center><br />\n";
    return $length;
}

?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).