所有图像都以 40 字节和 php file_put_contents保存 - 图像无效



我正在使用这个php代码从url抓取图像并将其保存到我的服务器。 文件已创建,权限为 755。 该过程使用产品名称重命名文件。 当我尝试访问文件时,我在浏览器中收到以下消息:The image cannot be displayed because it contains errors,所有文件都以 40 字节的大小保存。 据我所知,输入数据是正确的,我怀疑file_put_contents有什么问题......

// converting strings that have HR diacritics 
function replaceHRznakove($string){
$hr_slova=array("Č","Ć","Ž","Š","Đ","č","ć","ž","š","đ", "\", "/","''",'"',"'","`",',',';',';','&','¸','!','#','$','%','=','<','>','?','*','@','§',"(",")","[","]","{","}");
$asci_slova=array("C","C","Z","S","D","c","c","z","s","d","-", "-","",'',"","",'','','','','','','','','','','','','','','','','','','','','','');
$converted_string=str_replace($hr_slova, $asci_slova, $string);
return $converted_string;
}// end of function replaceHRznakove
// creating file with the product name
function createImage($product_name, $image_url, $image_location,$prod_code,$path_to_shop){
$img_url = str_replace("https://","http://",$image_url);
// checking if url returns 200 (exists) 
if(urlExists($img_url)){
// change blanks with dash
$name_frags= explode(" ", $product_name);
$filename= strtolower(implode("-", $name_frags));
// calling function to replace strings
$filename=replaceHRznakove($filename);
// find file type (extension)
$format_datoteke=pathinfo($img_url, PATHINFO_EXTENSION);
$filename=$prod_code."-".$filename.".".$format_datoteke;
// save file with new name and extension
// checking if file already exists on server, if not we are creating new
$file_location=$_SERVER['DOCUMENT_ROOT'].$path_to_shop.$image_location.$filename;
if(file_exists($file_location)){
$finfo = finfo_open(FILEINFO_MIME_TYPE);
}
else{
file_put_contents($file_location, $img_url);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
}
$mime_type=finfo_file($finfo, $file_location);
finfo_close($finfo);    
}
else{
$filename="";
$mime_type="";
}
return array($filename, $mime_type);
} // kraj funkcije createImate

// funkcija koja provjerava da li postoji datoteka iz URL-a
function urlExists($url){
$headers=get_headers($url);
return stripos($headers[0],"200 OK")?true:false;
} // kraj funkcije urlExists

任何帮助,不胜感激。


编辑

正如评论中所建议的,我已经查看了文件中实际存储的内容,似乎图像的URL不是存储在文件中。因此,当在文本编辑器中打开文件image.jpg时,我会看到以下内容:

http://www.somedomain.com/image.jpg

这是因为您将图像 url 作为内容保存到文件中:

file_put_contents($file_location, $img_url);

相反,您应该致电:

$image_data = file_get_contents($img_url);
...
file_put_contents($file_location, $image_data);

最新更新