2014-10-07 57 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