php函数的错误处理

How do I handle NULL returns on a function?

The below code is a basic curl function. I find there are times the $url will be NULL, for example if a website goes offline for some reason or a user types in a wrong url. In these instances I get an error "call to member function on null"

How do I return an empty result instead of a null result and stop the user from seeing this error?

function file_get_contents_curl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    $data = curl_exec($ch);

    curl_close($ch);

    return $data;
}

One potential avenue is Add:

$headers = curl_getinfo($ch);

then

if($headers['http_code'] < 400){
   $data = "whatever you need it to be...";

etc. and you can expand this for 300 (redirects) as necessary.