How to get fopen to timeout properly?

后端 未结 1 599
情歌与酒
情歌与酒 2021-01-05 12:21

I have the following snippet of php code

if($fp = fopen($url, \'r\')) {
    stream_set_timeout($fp, 1); 
    stream_set_blocking($fp, 0);

}
$info = stream_g         


        
相关标签:
1条回答
  • 2021-01-05 13:04

    You can use stream_context_create() and the http context option timeout. But fopen() will still return false if a timeout occurs, and stream_get_meta_data() won't work.

    $url = 'http://...';
    $context = stream_context_create( array(
      'http'=>array(
        'timeout' => 2.0
      )
    ));
    $fp = fopen($url, 'r', false, $context);
    if ( !$fp ) {
      echo '!fopen';
    }
    else {
      $info = stream_get_meta_data($fp);
      var_dump($info);
    }
    
    0 讨论(0)
提交回复
热议问题