我有来自外部网址的下载图片代码。
$content = file_get_contents("http://shoecompany.in/wp-content/uploads/2015/06/new.jpg");
$fp = fopen("assets/img/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
如果外部网址中没有图片,那么我想显示错误信息。那我该怎么办?
答案 0 :(得分:2)
<强> file_get_contents 强>
该函数返回读取数据或失败时返回FALSE。
因此您可以将错误检查为
$content = file_get_contents("http://shoecompany.in/wp-content/uploads/2015/06/new.jpg");
if ($content === FALSE) {// check here
// handle error here...
} else {
$fp = fopen("assets/img/image.jpg", "w");
if ($fp) {// fopen check here
fwrite($fp, $content);
fclose($fp);
} else {
// handle error here...
}
}
答案 1 :(得分:1)
if(@$content = file_get_contents("http://shoecompany.in/wp-content/uploads/2015/06/new.jpg") !== false){
$content;
//Store in the filesystem.
$fp = fopen("assets/img/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
}else{
echo "error";
}
答案 2 :(得分:1)
此函数在字符串的情况下返回文件,在失败时返回false。 函数返回布尔值为FALSE但也可能返回非布尔值,这就是为什么你必须使用&#34; ===&#34;
$result=file_get_contents("http://shoecompany.in/wp-content/uploads/2015/06/new.jpg");
if ($result === false)
{
print "Not Found. You Can handle error here";
}
else
{
print " handle good case ";
}
答案 3 :(得分:0)
尝试使用if条件
if(file_get_contents("http://shoecompany.in/wp-content/uploads/2015/06/new.jpg"))
{
$content = file_get_contents("http://shoecompany.in/wp-content/uploads/2015/06/new.jpg");
$fp = fopen("assets/img/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
}
else
{
...Some content to display
}