Please tell me how I can check for an error in the fopen function, namely, whether the file is located at this link. The link may or may not work.
$url = "https://test.com/file/";
if (fopen($url, "r")) {
file_put_contents("test.mp3", fopen($url, "r"));
}
else {
}
So for some reason it doesn't work.
CodePudding user response:
Why not simply use try catch ?
try {
file_put_contents("test.mp3", fopen($url, "r"));
} catch(Exception $e) {
echo($e->getMessage()); // Whatever handling you want if the fopen fails
}
CodePudding user response:
You have two solutions, or you will wrap it in a try - catch
block or you can previously check if the file is available via curl
$ch = curl_init("https://test.com/file/");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Check the retcode, if is 200 the file is there and you can proceed, otherwise you need to handle it