PHP: fopen error handling

后端 未结 4 865
天涯浪人
天涯浪人 2021-02-05 03:33

I do fetch a file with

$fp = fopen(\'uploads/Team/img/\'.$team_id.\'.png\', \"rb\");
$str = stream_get_contents($fp);
fclose($fp);

and then the

4条回答
  •  春和景丽
    2021-02-05 04:16

    Generically - This is probably the best way to do file-io in php (as mentioned by @Cendak here)

    $fileName = 'uploads/Team/img/'.$team_id.'.png';
    if ( file_exists($fileName) && ($fp = fopen($fileName, "rb"))!==false ){
        $str = stream_get_contents($fp);
        fclose($fp);
        // send success JSON    
    }else{
        // send an error message if you can  
    }
    

    But it does not work with PHP 7.3, these modifications do,

    if(file_exists($filename) && ($fp = fopen($filename,"r") !== false)){
            $fp = fopen($filename,"r");
            $filedata = fread($fp,filesize($filename));
            fclose($fp);
    }else{
            $filedata = "default-string";
    }
    

提交回复
热议问题