Question

I am trying to create a custom function to get remote url data in variable. but i am doing this with fallback system so what are the available functions to get the remote data.

i would like to see if i am not missing something. I am creating script to run on my clients machine so , if they dont have specific functions enabled, it should fallback to another available function ,

function url_get_contents ($url) {
    if (function_exists('curl_exec')){ 
        $conn = curl_init($url);
        curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($conn, CURLOPT_FRESH_CONNECT,  true);
        curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1);
        $url_get_contents_data = (curl_exec($conn));
        curl_close($conn);
    }elseif(function_exists('file_get_contents')){
        $url_get_contents_data = file_get_contents($url);
    }elseif(function_exists('fopen') && function_exists('stream_get_contents')){
        $handle = fopen ($url, "r");
        $url_get_contents_data = stream_get_contents($handle);
    }else{
        $url_get_contents_data = false;
    }
return $url_get_contents_data;
} 

so later i can check like this

$data = url_get_contents("http://www.google.com");
if($data){
echo "bravo";
}else{
echo "oops";
}

What are more available method/functions to get remote file data.

Was it helpful?

Solution

Your code and approach is excellent. It seemed to me safe with most of the versions of PHP.

A thing regarding the curl. Its better to use this option for ssl

curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, false);

Otherwise you'll get the following error for the https protocol in some systems.

* SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

You can also try fsockopen() to get the remote content. But for this one, you have to change the for number for different protocols.

$fp = fsockopen($domain, $portno, $errno, $errstr);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top