简体   繁体   English

PHP将图像从url复制到文件夹

[英]PHP copy image from url to folder

Why are my images not being copied from URL to local? 为什么我的图像没有从URL复制到本地? I get no errors or anything. 我没有任何错误。 I know there are a lot of similar questions - but I got no clue what is wrong. 我知道有很多类似的问题-但我不知道哪里出了问题。 Feels like I have tried everything. 感觉就像我已经尝试了一切。

Hope one of you might be able to tell me what is wrong. 希望你们中的一个能够告诉我出什么问题了。

$url = 'https://example.com/media/'.$fetch['img'].'?w=128&h=128';
$img = '/images/hoses/fittings/'.$fetch['img'];

copy($url, $img);
  • URL is valid 网址有效
  • Allow_url_fopen is set to true. Allow_url_fopen设置为true。
  • Local folder exist and permission is set to 755 本地文件夹存在且权限设置为755

I have also tried using cUrl, same problem. 我也尝试过使用cUrl,同样的问题。

$content = file_get_contents($url);
$fp = fopen($img, "w");
fwrite($fp, $content);
fclose($fp);

What can cause this problem? 什么会导致此问题? Not sure where to look :( 不知道在哪里看:(

UPDATE: @04FS found the error. 更新: @ 04FS发现错误。 If was the starting slash. 如果是起始斜线。

Working code: 工作代码:

$url = "https://example.com/media/".$fetch['img']."?w=128&h=128";
$img = "images/hoses/fittings/".$fetch['img'];

if(!copy($url, $img)) {
    print_r(error_get_last());
} else {
    echo "File copied from remote!";
}

$img = '/images/hoses/fittings/'.$fetch['img']; $ img ='/images/hoses/fittings/'.$fetch['img'];

/images/hoses/fittings/ would refer to the server file system root directory , because of the leading slash. /images/hoses/fittings/将引用服务器文件系统根目录 ,因为斜杠前导。

If you want this to be a relative path inside your project folder, then that leading slash needs to be removed. 如果要将其作为项目文件夹中的相对路径,则需要删除该前导斜线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM