2014-12-05 16 views
0

我從一個輸入上傳多個圖像並重命名所有上傳的文件。我的問題是;我需要有獨立的變量無法用多個變量回顯多個圖像

例如,顯示所有上傳的圖片:

If user upload 3 images, i need to echo as 

$upload1 = 1st file name 
$upload2 = 2nd file name 
$upload3 = 3rd file anme 

No of images uploaded (upload number of file) 

這裏是我當前的代碼:

<?php 
if (isset($_FILES['files'])) { 
    $uploadedFiles = array(); 
    foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) { 
     $errors = array(); 
     $file_name = md5(uniqid("") . time()); 
     $file_size = $_FILES['files']['size'][$key]; 
     $file_tmp = $_FILES['files']['tmp_name'][$key]; 
     $file_type = $_FILES['files']['type'][$key]; 

     if($file_type == "image/gif"){ 
      $sExt = ".gif"; 
     } elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){ 
      $sExt = ".jpg"; 
     } elseif($file_type == "image/png" || $file_type == "image/x-png"){ 
      $sExt = ".png"; 
     } 
     if (!in_array($sExt, array('.gif','.jpg','.png'))) { 
      $errors[] = "Image types alowed are (.gif, .jpg, .png) only!"; 
     } 
     if ($file_size > 2097152000) { 
      $errors[] = 'File size must be less than 2 MB'; 
     } 
     $desired_dir = "user_data/"; 
     if (empty($errors)) { 
      if (is_dir($desired_dir) == false) { 
       mkdir("$desired_dir", 0700);  // Create directory if it does not exist 
      } 
      if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) { 
       $uploadedFiles[$key] = array($_FILES['files']['name'][$key], 1); 
      } else { 
       echo "Couldn't upload file " . $_FILES['files']['name'][$key]; 
       $uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0); 
      } 
     } else { 
      print_r($errors); 
     } 
    } 

    foreach ($uploadedFiles as $key => $row) { 
     if (!empty($row[1])) { 
      $codestr = '$file' . ($key+1) . " = $row[0];"; 
      eval ($codestr); 
     } else { 
      $codestr = '$file' . ($key+1) . " = NULL;"; 
      eval ($codestr); 
     } 
    } 
} 

echo $file1; 
echo $file2; 
echo $file3; 
echo $file4; 
echo $file5; 
?> 

我嘗試這樣做,我得到的錯誤

Parse error: syntax error, unexpected 'png' (T_STRING) in C:\Users\logon\Documents\NetBeansProjects\upload file rename single and multiple\multiple file rename\method 2\process.php(43) : eval()'d code on line 1 

我做錯了什麼?可以有人幫我

回答

0

我認爲在線42上" = $row[0];"可能不會做你想做的事情。由於雙引號,變量$row[0]的值將打印在代碼中。

通過EVAL運行後會看起來像這樣的代碼:

$file0 = FILENAME.png;

取而代之的是:

$file0 = $row[0];

爲了解決這個問題,你可以簡單地把線42進如下:

$codestr = '$file' . ($key+1) . ' = $row[0];';

0關於單引號和雙引號之間的區別

的更多信息:http://php.net/manual/en/language.types.string.php

編輯:對於文件的正確名稱,你可以改變$_FILES['files']['name'][$key]$file_name . $sExt。希望能幫助到你!

+0

它工作的感謝,但它顯示原始文件名如何顯示重命名的文件名 – creator 2014-12-05 14:38:12

+0

我如何顯示上傳文件的數量 – creator 2014-12-05 16:20:59