Reputation: 15
I'm new to this. How to NOT write to the file if CURLOPT_FAILONERROR is triggered?
$token = "123";
$url = "foo.com";
$fp = fopen("file.txt", "wb");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
curl_close($ch);
fclose($fp);
Upvotes: 0
Views: 577
Reputation: 728
I'm not sure that is possible in that way. I download the origin file first in /tmp and if there isn't error then I move it to whatever you want.
$tmpFp = null;
$token = '123';
$url = 'foo.com';
$source = '';
$dest = 'file.txt';
$meta = null;
try {
// creating tmp file
$tmpFp = tmpfile();
$meta = stream_get_meta_data($tmpFp);
// getting its name
$source = $meta['uri'];
if($tmpFp === false){
throw new Exception('Could not open Temporal File');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FILE, $tmpFp);
curl_exec($ch);
// download file
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($tmpFp);
if($statusCode != 200) {
// if the file don't exist or some other web error
throw new Exception('Status Code: '. $statusCode);
}
// copy to dest
if (!copy($source, $des)) {
throw new Exception('failed to copy file');
}
echo('Download success!');
} catch(Exception $e) {
echo($e->getMessage());
}
last note, make sure that you have permissions
regards
Upvotes: 1