Lucy
Lucy

Reputation: 1852

Fetching URL contents using PHP and Curl

I am trying to fetch contents of a url using the curl library in php. I have written the below code to do this. Even though I'am not getting an error in the code, nothing is being printed in the output. As there is no error message being displayed, I'm not able to figure out what I'm doing wrong. I'm trying to print details of url response like headers, body, time, size, errors (if any). I'm using xampp to run the below code.

<?php
    function url_get_contents($url="google.com",$useragent='cURL',$headers=false,
    $follow_redirects=false,$debug=false) {

        # initialise the CURL library
        $ch = curl_init();

        # specify the URL to be retrieved
        curl_setopt($ch, CURLOPT_URL,$url);

        # we want to get the contents of the URL and store it in a variable
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

        # specify the useragent: this is a required courtesy to site owners
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

        # ignore SSL errors
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        # return headers as requested
        if ($headers==true){
            curl_setopt($ch, CURLOPT_HEADER,1);
        }

        # only return headers
        if ($headers=='headers only') {
            curl_setopt($ch, CURLOPT_NOBODY ,1);
        }

        # follow redirects - note this is disabled by default in most PHP installs from 4.4.4 up
        if ($follow_redirects==true) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }

        # if debugging, return an array with CURL's debug info and the URL contents
        if ($debug==true) {
            $result['contents']=curl_exec($ch);
            $result['info']=curl_getinfo($ch);
        }

        # otherwise just return the contents as a variable
        else $result=curl_exec($ch);

        # free resources
        curl_close($ch);

        # send back the data
        return $result;
    }
?> 

Upvotes: 2

Views: 1929

Answers (2)

Jigar
Jigar

Reputation: 3322

Agree with above answer. Also check, if you are running this in browser, you might have to view the source of the page for output.

Upvotes: 1

Sriraman
Sriraman

Reputation: 7937

Your code is working perfectly.

Just call the function.

echo url_get_contents();

Check whether Curl is switched ON.

Upvotes: 3

Related Questions