PHP - 直接从URL将图像复制到我的服务器

Ian*_*Ian 65 php

可能重复:
使用php从php url保存图像

我想拥有以下PHP代码.

假设我有一个图片网址,例如http://www.google.co.in/intl/en_com/images/srpr/logo1w.png

如果我运行一个脚本,该图像将被复制并放在我的服务器上具有777权限的文件夹中.

可能吗?如果是的话,请你指点一下吗?

谢谢,

伊恩

dot*_*tty 133

有两种方法,如果你使用的是PHP5

copy('http://www.google.co.in/intl/en_com/images/srpr/logo1w.png', '/tmp/file.jpeg');
Run Code Online (Sandbox Code Playgroud)

如果没有,请使用file_get_contents

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
Run Code Online (Sandbox Code Playgroud)

这篇SO帖子

  • 在此示例中,源文件和目标文件的文件扩展名不同.文件是否会从png转换为jpg? (3认同)
  • 非常感谢!`copy()`做了伎俩 (2认同)

Mic*_*son 31

将图像从URL复制到服务器,删除之后的所有图像

function getimg($url) {         
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';              
    $headers[] = 'Connection: Keep-Alive';         
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';         
    $user_agent = 'php';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);         
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here         
    curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);         
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
} 

$imgurl = 'http://www.foodtest.ru/images/big_img/sausage_3.jpg'; 
$imagename= basename($imgurl);
if(file_exists('./tmp/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('tmp/'.$imagename,$image);       
Run Code Online (Sandbox Code Playgroud)


Sha*_*ngh 15

$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);
Run Code Online (Sandbox Code Playgroud)

你必须allow_url_fopen设置为on


Tha*_*ama 8

这个SO线程将解决您的问题.简而言之:

$url = 'http://www.google.co.in/intl/en_com/images/srpr/logo1w.png';
$img = '/my/folder/my_image.gif';
file_put_contents($img, file_get_contents($url));
Run Code Online (Sandbox Code Playgroud)