2009-10-06 15 views
-1

似乎沒有人將各種StackOverflow問題中的所有示例代碼都捆綁在一起,如何處理照片上傳的一個很好的,放在一起的示例。這是我的開始......請幫助改進它。PHP照片上傳的一些很好的示例代碼在哪裏?

這裏是我們的設置:

  • 我們的文件上傳控件名爲$file,例如<input type="file" name="<?= $file ?>" />
  • 我們希望將照片保存到$photosPath,例如, $photosPath = "/photos/"
  • 我們希望文件名是$targetFilename . ".jpg",例如, $targetFilename可能來自我們上傳表單中的用戶名文本字段。
  • 我們希望將結果文件路徑存儲在$filePath中,例如,用於插入到數據庫中。
  • 我們只想接受.jpgs。
  • 我們只想接受最多$maxSize字節的文件。

回答

0

這裏是我的鏡頭吧:

// Given: $file, $targetFilename, $photosPath, $maxSize 
$filePath = NULL; 
if (array_key_exists($_FILES, $file) 
    && $_FILES[$file]['size'] != 0 
    && $_FILES[$file]['error'] == UPLOAD_ERR_OK) 
{ 
    if ($_FILES[$file]['size'] > $maxSize) 
    { 
     throw new Exception("The uploaded photo was too large; the maximum size is $maxSize bytes."); 
    } 

    $imageData = getimagesize($_FILES[$file]['tmp_name']); 
    $extension = image_type_to_extension($imageData[2]); 
    if ($extension != ".jpg" && $extension != ".jpeg") 
    { 
     throw new Exception("Only .jpg photos are allowed."); 
    } 

    $possibleFilePath = $photosPath . $targetFilename . ".jpg"; 
    if (!move_uploaded_file($_FILES[$file]['tmp_name'], 
          $_SERVER['DOCUMENT_ROOT'] . $possibleFilePath) 
    { 
     throw new Exception("Could not save the uploaded photo to the server."); 
    } 

    $filePath = $possibleFilePath; 
} 
相關問題