2014-01-14 39 views
-1

我試圖將現有圖像文件從臨時文件夾移動到具有適當文件名的適當位置,出於某種原因它總是失敗。用新名稱將文件移動到新位置

function move_temp_image($article_id) 
{ 
    global $db, $config; 

    if (($image_load = [email protected]($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.jpg", 'r+')) && ($image_load = [email protected]($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.png", 'r+')) && ($image_load = [email protected]($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.gif", 'r+'))) 
    { 
     $this->error_message = "Could not find temp image to load?"; 
     return false; 
    } 

    else 
    { 
     $image_info = getimagesize($image_load); 
     $image_type = $image_info[2]; 
     $file_ext = ''; 
     if($image_type == IMAGETYPE_JPEG) 
     { 
      $file_ext = 'jpg'; 
     } 

     else if($image_type == IMAGETYPE_GIF) 
     { 
      $file_ext = 'gif'; 
     } 

     else if($image_type == IMAGETYPE_PNG) 
     { 
      $file_ext = 'png'; 
     } 

     // give the image a random file name 
     $imagename = rand() . 'id' . $article_id . 'gol.' . $file_ext; 

     // the actual image 
     $source = $image_load; 

     // where to upload to 
     $target = $_SERVER['DOCUMENT_ROOT'] . "/uploads/articles/topimages/" . $imagename; 

     if (rename($source, $target)) 
     {   
      // remove old temp image 
      if ($image['article_top_image'] == 1) 
      { 
       unlink($_SERVER['DOCUMENT_ROOT'] . '/uploads/temp/' . $image_load); 
      } 

      unset($_SESSION['temp_tagline']); 

      $db->sqlquery("UPDATE `articles` SET `article_top_image` = 1, `article_top_image_filename` = ? WHERE `article_id` = ?", array($imagename, $article_id)); 
      return true; 
     } 

     else 
     { 
      $this->error_message = 'Could not move temp file to tagline uploads folder!'; 
      return false; 
     } 
    } 
} 

我不知道我在做什麼錯,我讀重命名是這樣做的方式,但我顯然忽略了一些東西。

+0

你檢查你的目標目錄的權限替換你的條件?您的網絡服務器用戶是否允許寫入? –

+0

是的,權限是可以接受的,因爲我一直上傳到其他地方。 – NaughtySquid

+0

您是否收到任何警告?是[錯誤報告打開](http://stackoverflow.com/questions/6575482/how-do-i-enable-error-reporting-in-php)到最大? –

回答

1

您不必在$source文件名 - 在您的代碼,$source包含一個文件資源...

重命名不僅與文件名,所以你必須改變你的代碼。

即用下面的代碼

$types = array('jpg', 'png', 'gif'); 
$file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline."; 
$image_load = false; 
foreach ($types as $type) { 
    if (file_exists($file . $type)) { 
     $image_load = $file . $type; 
     break; 
    } 
} 

if (!file_exists($image_load)) 
+0

它可能是一個.jpg,.png或.gif文件,因此無法正常工作,爲什麼我會在開始時進行三重檢查。 – NaughtySquid

+0

你的答案的第一行是這個問題,但我沒有意識到使用字符串的fopen不會將它設置爲文件名。 – NaughtySquid

相關問題