PHP -从外部服务器上传图像


PHP - Upload image from external server

我试图发布一张照片到Facebook,它的工作只要图像是在同一文件夹的PHP脚本:

  $file= "myimage.png";
    $args = array(
        'message' => 'Photo from application',
        );
      $args[basename($file)] = '@' . realpath($file);
    $ch = curl_init();

我需要做些什么来让外部图像工作,例如:

$file= "http://www.example.com/myimage.png";

必须先将图像下载到服务器,然后使用该路径。下面是将图像下载到临时文件的示例:

$temp_name = tempnam(sys_get_temp_dir(), "external");
copy($file, $temp_name);
// ...
$args[basename($file)] = '@' . realpath($temp_name);

为了确保文件下载完好无损,我更喜欢这种方式。

$path = '/where/to/save/file';
$url = 'http://path.to/file';
$remote = fopen($url, "rb");
if($remote) {
    $local = fopen($path, "wb");
    if($local) {
        while(!feof($remote)) {
            fwrite($local, fread($remote, 1024 * 8 ), 1024 * 8);
        }
    }
}
if ($remote) fclose($remote);
if ($local)  fclose($local);

我建议使用uniqid()来生成路径。

然后将路径传递给代码。

由于文件现在是本地的,它应该可以上传。