简体   繁体   中英

suppress error using fread()

I wrote a script for screen pops from our soft phone that locates a directory listing for the caller but occasionally they get "Can't read input stream" and the rest of the script quits.

Does anyone have any suggestions on how to suppress error the error message and allow the rest of the script to run? Thanks!

$i=0;

    $open = fopen("http://www.411.ca/whitepages/?n=".$_GET['phone'], "r"); 
    $read = fread($open, 9024); 
    fclose($open); 
    eregi("'/(.*)';",$read,$got);
    $tv = ereg_replace('[[:blank:]]',' ',$got[1]);
    $url = "http://www.411.ca/".$tv;
    while ($name=="unknown" && $i < 15) { ## try 15 times before giving up
    $file = @ fopen($fn=$url,"r") or die ("Can't read input stream");
    $text = fread($file,16384);
    if (preg_match('/"name">(.*?)<\/div>/is',$text,$found)) {
            $name = $found[1];
    } 
    if (preg_match('/"phone">(.*?)<\/div>/is',$text,$found)) {
            $phone = $found[1];
    } 
    if (preg_match('/"address">(.*?)<\/div>/is',$text,$found)) {
            $address = $found[1];
    } 
    fclose($file);
    $i++;
    }

You need to check your return values, specifically for fopen .

Something like this:

$file = fopen($fn=$url,"r");
if ($file === false) {
    // Unable to open stream, handle error
}

Then you need to decide how to handle the error that occurs when fopen can't read from the URL you're giving it. I doubt you actually want to simply suppress the error and allow the script to continue without the data it needs to do something meaningful. You could pause briefly and attempt to re-open the file, or direct the user to a more friendly error page instead of dying with a bare "Cannot open file" message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM