【问题标题】:PHP - Upload image from external serverPHP - 从外部服务器上传图片
【发布时间】:2013-06-07 19:59:42
【问题描述】:

我正在尝试将照片发布到 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";

【问题讨论】:

标签: php curl


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    为了确保下载的文件没有损坏,我更喜欢这种方式。

    $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() 来生成路径。

    然后将路径传递给您的代码。

    由于该文件现在是本地文件,因此应该可以正常上传。

    【讨论】:

    • 您好,请您解释一下我正在尝试使用您的代码上传图片,但没有成功。谢谢
    • 代码下载它不上传。门票名称令人困惑。上传文件比较复杂,因为您可能还需要进行身份验证。
    猜你喜欢
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2011-05-16
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    相关资源
    最近更新 更多