2014-10-07 25 views
0

我想用PHP做一个上传类。所以这是我的第一个PHP类:无法复制图像从PHP中的URL与上传类

//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新手,并试图学习它。

谢谢。

回答

1

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

代替。

+0

谢谢你我的朋友,一切都很好现在 – Alireza 2014-10-07 16:07:16

1

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); 
} 
+0

我需要修理我的朋友! – Alireza 2014-10-07 16:01:33

+0

@Alireza我编辑它,所以你可以看到什么样的功能。 – helllomatt 2014-10-07 16:04:35

+0

仍然无法正常工作... – Alireza 2014-10-07 16:05:41

1

既然你想下载一个图片,你也可以使用PHP的imagejpeg - 方法,以确保你不与任何损坏的文件格式之后(http://de2.php.net/manual/en/function.imagejpeg.php)结束:

  • 下载目标为“字符串”
  • 创建一个图像资源。
  • 将其保存为JPEG格式,使用适当的方法:

你的方法里面:

​​

为了有file_get_contents正常工作,你需要确保allow_url_fopen在你的PHP设置为1 ini: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"; 
} 
+0

感谢所有这些信息 – Alireza 2014-10-07 16:13:18

1

你描述的是更多的下载(服务器),然后上传。 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"); 
+0

谢谢我的朋友 – Alireza 2014-10-07 16:12:56