PHP: fopen error handling

后端 未结 4 863
天涯浪人
天涯浪人 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";
    }
    
    0 讨论(0)
  • 2021-02-05 04:17
    [{"message":"Warning: fopen(uploads\/Team\/img\/1.png): failed to open stream: No such file or directory in C:\...
    

    the error is clear: you've put the wrong directory, you can try what you whant but it'll not work. you can make it work with this:

    1. take your file and put it in the same folder of your php file (you'll be able to move it after don't worry, it's about your error) or on a folder "higher" of your script (just not outside of your www folder)
    2. change the fopen to ('./$team_id.'png',"rb");
    3. rerun your script file

    don't forget this : you can't access a file that is'nt in your "www" folder (he doesn't found your file because he give you her name: the name come from the $team_id variable)

    0 讨论(0)
  • 2021-02-05 04:35

    You should first test the existence of a file by file_exists().

    try
    {
      $fileName = 'uploads/Team/img/'.$team_id.'.png';
    
      if ( !file_exists($fileName) ) {
        throw new Exception('File not found.');
      }
    
      $fp = fopen($fileName, "rb");
      if ( !$fp ) {
        throw new Exception('File open failed.');
      }  
      $str = stream_get_contents($fp);
      fclose($fp);
    
      // send success JSON
    
    } catch ( Exception $e ) {
      // send error message if you can
    } 
    

    or simple solution without exceptions:

    $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 error message if you can  
    }
    
    0 讨论(0)
  • 2021-02-05 04:36

    You can use the file_exists() function before calling fopen().

    if(file_exists('uploads/Team/img/'.$team_id.'.png')
    {
        $fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb");
        $str = stream_get_contents($fp);
        fclose($fp);
    }
    
    0 讨论(0)
提交回复
热议问题