简体   繁体   English

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

[英]PHP - Upload image from external server

I'm trying to post a photo to Facebook and it works as long as the image is in the same folder as the PHP script: 我正在尝试将照片发布到Facebook,只要图像与PHP脚本位于同一文件夹中,它就可以正常工作:

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

What do I need to change to make it work for external images , eg: 我需要更改什么才能使其适用于外部图像 ,例如:

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

You must first download the image to your server then use that path. 您必须首先将映像下载到服务器,然后使用该路径。 Here's an example of downloading the image to a temporary file: 这是将图像下载到临时文件的示例:

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

To be sure file is downloaded without damage I prefer this way. 为了确保文件下载没有损坏,我更喜欢这种方式。

$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);

I recommend using uniqid() to generate the path. 我建议使用uniqid()生成路径。

Then pass the path to your code. 然后将路径传递给您的代码。

Since the file will now be local it should upload just fine. 由于该文件现在将是本地文件,因此应该可以正常上传。

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

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