从外部链接获取文件并存储到本地服务器

时间:2016-03-04 11:08:10

标签: php

我需要从外部链接获取图像文件并存储到我的本地文件夹中。

我使用了以下内容:

 $value1 = "https://images.airlist.com/0008459/Listing/129128/3350520160227084506.JPG%3Fv=1?v=1";

 $img_file = file_get_contents(str_replace("?v=1","",$value1));
 $file_handler = fopen($file_loc,'w');
 if(fwrite($file_handler,$img_file)== false)
    {
            echo 'error';
    }
    fclose($file_handler);
   }

图像以如下格式存储:

  

3308420160227084509.JPG%3Fv = 1-50x50.jpg%3fv = 1

2 个答案:

答案 0 :(得分:0)

我会做类似的事情:

$url = "https://images.airlist.com/0008459/Listing/129128/3350520160227084506.JPG%3Fv=1?v=1";
$file = explode('?', $url)[0]; // get everything on the left site from the ?
$file = explode('%', $file)[0]; // get everything on the left site from %
$filename = basename($file); // get only the filename
$fileContent = file_get_contents($url); // get image content
file_put_contents($filename, $fileContent); // write image content to filename

答案 1 :(得分:0)

一小时前你没有回答我的评论,但我会假设您要下载 https://images.airlist.com/0008459/Listing/129128/3350520160227084506.JPG%3Fv=1‌​?v=1保存 3350520160227084506.JPG

<?php

$value1 = "https://images.airlist.com/0008459/Listing/129128/3350520160227084506.JPG%3Fv=1?v=1";

// Take the basename (3350520160227084506.JPG%3Fv=1?v=1)
// And remove anything starting from either a percent sign (%) or a question mark (?)
$fileName = preg_replace('~[%?].*$~', '', basename($value1));

// $fileName = string(23) "3350520160227084506.JPG"

file_put_contents($fileName, file_get_contents($value1));