首页 > 解决方案 > 如何通过 php 将图像下载到我的笔记本电脑路径?

问题描述

如何在此 C:/Users/AlexBoey/Pictures/images/ 中将此图像指向我的本地驱动器

  $url_to_image = 'http://cleversoft.co/wp-content/uploads/2013/08/senior-php-developer.jpg';

$ch = curl_init($url_to_image);

$my_save_dir = 'C:/Users/AlexBoey/Pictures/images/';
$filename = basename($url_to_image);
$complete_save_loc = $my_save_dir . $filename;

$fp = fopen($complete_save_loc, 'wb');

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

标签: php

解决方案


怎么样file_get_contents()http://php.net/manual/en/function.file-get-contents.php

$image = file_get_contents('http://cleversoft.co/wp-content/uploads/2013/08/senior-php-developer.jpg');

那么file_put_contents()呢?http://php.net/manual/en/function.file-put-contents.php

file_put_contents('C:/Users/AlexBoey/Pictures/images/image.jpg', $image);

更新 - 如果您从笔记本电脑本身运行 PHP,那么上面的内容是适用的。事实并非如此。因此,除此之外,您需要标头附件内容并回显内容($file 是保存在服务器上的路径,将 file_put_contents 更改为服务器上的某个临时位置,您可以unlink()在回显之前进行):

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);

// you can `unlink($file)` the image saved on the server
echo $image;

推荐阅读