Search code examples
phpcurlfopenfwrite

why does this code work without an fwrite statement?


I am trying to understand curl/fopen in PHP. the Following function works fine, but I expected at some point to see fwrite.

function cURLdownload($url, $file) 
{ 
  if( !cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions"; 
  $ch = curl_init(); 
  if($ch) 
  { 
    $fp = fopen($file, "w"); 
    if($fp) 
    { 
      if( !curl_setopt($ch, CURLOPT_URL, $url) ) 
      { 
        fclose($fp); // to match fopen() 
        curl_close($ch); // to match curl_init() 
        return "FAIL: curl_setopt(CURLOPT_URL)"; 
      } 
      if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)"; 
      if( !curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)"; 
      if( !curl_exec($ch) ) return "FAIL: curl_exec()"; 
      curl_close($ch); 
      fclose($fp); 
      return "SUCCESS: $file [$url]"; 
    } 
    else return "FAIL: fopen()"; 
  } 
  else return "FAIL: curl_init()"; 
} 

Solution

  • if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)"; tells the library to write the output to a file. So when you use curl_exec() the file is immediately written.