无法使用上载类从PHP中的URL复制图像


Unable to copy image from URL in PHP with upload class

我正在尝试用PHP制作一个上传类。这是我的第一个PHP类:

//Create Class
class Upload{
  //Remote Image Upload
  function Remote($Image){
    $Content = file_get_contents($Image);
    if(copy($Content, '/test/sdfsdfd.jpg')){
      return "UPLOADED";
    }else{
      return "ERROR";
    }
  }
}

和用法:

$Upload = new Upload();
echo $Upload->Remote('https://www.gstatic.com/webp/gallery/4.sm.jpg');

问题是,这门课不起作用。问题出在哪里?我是PHP类的新手,正在努力学习。

谢谢。

copy需要文件系统路径,例如

copy('/path/to/source', '/path/to/destination');

你正在传递你获取的文字图像,所以它将是

copy('massive pile of binary garbage that will be treated as a filename', '/path/to/destination');

你想要

file_put_contents('/test/sdfsdfg.jpg', $Content);

相反。

PHP的copy()函数用于复制您有权复制的文件。

由于您首先获取文件的内容,因此可以使用fwrite()。

<?php
//Remote Image Upload
function Remote($Image){
    $Content = file_get_contents($Image);
    // Create the file
    if (!$fp = fopen('img.png', 'w')) {
        echo "Failed to create image file.";
    }
    // Add the contents
    if (fwrite($fp, $Content) === false) {
        echo "Failed to write image file contents.";
    }
    fclose($fp);
}

由于您想要下载图像,您也可以使用php的imagejpeg方法来确保之后不会出现任何损坏的文件格式(http://de2.php.net/manual/en/function.imagejpeg.php):

  • 将目标下载为"字符串"
  • 用它创建一个图像资源
  • 使用正确的方法将其保存为jpeg:

在你的方法内部:

$content = file_get_contents($Image);
$img = imagecreatefromstring($content);
return imagejpeg($img, "Path/to/targetFile");

为了使file_get_contents正常工作,您需要确保在php.ini中将allow_url_fopen设置为1:http://php.net/manual/en/filesystem.configuration.php

大多数托管主机默认情况下都会禁用此功能。因此,请联系支持人员,或者如果他们不启用allow_url_fopen,则需要使用另一种尝试,例如使用cURL下载文件。http://php.net/manual/en/book.curl.php

U可以使用以下代码段来检查其是否已启用:

if ( ini_get('allow_url_fopen') ) {
   echo "Enabled";
} else{
   echo "Disabled";
}

您所描述的是更多的下载(到服务器)然后上传。stream_copy_to_stream。

class Remote
{
    public static function download($in, $out)
    {
        $src = fopen($in, "r");
        if (!$src) {
            return 0;
        }
        $dest = fopen($out, "w");
        if (!$dest) {
            return 0;
        }
        $bytes = stream_copy_to_stream($src, $dest);
        fclose($src); fclose($dest);
        return $bytes;
    }
}
$remote = 'https://www.gstatic.com/webp/gallery/4.sm.jpg';
$local = __DIR__ . '/test/sdfsdfd.jpg';
echo (Remote::download($remote, $local) > 0 ? "OK" : "ERROR");