2013-05-28 35 views
0

我正在使用php的簡單文件上傳功能。PHP file_exist工作不正常?

我用This功能上傳三個文件:

而且這裏是我存儲我的文件,我的目錄內在張力結構:

ROOT- 
    -notes- 
     -demo- 
      -demo_file1.jpg 
     -main- 
      -main_file1.jpg 
     -thumb- 
    -manage.php //file which handle uploading code 

我打電話這樣的上傳功能:

$demo_path="notes\demo"; 
list($demo_file_name,$error)=upload('demo_file',$demo_path,'pdf'); 
if($error!=""){ 
    echo 'error-demo'.$error; 
    exit; 
} 
//uploading main file 
$main_path="notes\main"; 
list($file_name,$error)=upload('main_file',$main_path,'pdf'); 
if($error!=""){ 
    echo 'error-main'.$error; 
    exit; 

} 

//uploadnig thumbnail 
$thumb_path="notes\thumb"; 
list($thumb_file_name,$error)=upload('file_thumb',$thumb_path,'jpg,gif,jpeg,png'); 
if($error!=""){ 
    echo 'error-thumb'.$error; 
    exit; 

} 

此代碼對於演示文件和主文件工作正常,但給予拇指錯誤說

error-thumb無法上載文件{文件名}:文件夾不存在。

請你幫我弄清楚問題嗎?

在此先感謝。

注意:$ _FILES顯示所有三個文件。

+3

你在哪裏,即使使用'file_exists()'爲你的標題所暗示? –

+0

@ØHankyPankyØ有一個至少在鏈接,OP提到... – BlitZ

+0

所以不是錯誤信息非常清楚,該文件夾,你試圖上傳這個文件,不存在? –

回答

6

使用正斜槓(/)分隔目錄名:

$thumb_path='notes/thumb'; 

否則\t被解釋爲雙引號製表符。

+2

使用單引號而不是雙引號可能也會工作,但斜槓更好。 – Arjan

+1

@Arjan是的,更好地結合這兩者。 – meze

2

通常,直接定義文件路徑被認爲是不好的做法。您應該解析路徑,如果該路徑不存在則創建目錄,然後檢查該目錄是否可讀。例如:

function get_the_directory($dir) { 
    $upload_dir = trim($dir); 
    if(!file_exists($upload_dir)){ // Check if the directory exists 
     $new_dir = @mkdir($upload_dir); // Create it if it doesn't 
    }else{ 
     $new_dir = true; // Return true if it does 
    } 
    if ($new_dir) { // If above is true 
     $dir_len = strlen($upload_dir); // Get dir length 
     $last_slash = substr($upload_dir,$dir_len-1,1); // Define trailing slash 
     if ($last_slash <> DIRECTORY_SEPARATOR) { // Add trailing slash if one is not present 
      $upload_dir = $upload_dir . DIRECTORY_SEPARATOR; 
     } else { 
      $upload_dir = $upload_dir; 
     } 
     $handle = @opendir($upload_dir); 
     if ($handle) { // Check if dir is readable by the PHP user 
      $upload_dir = $upload_dir; 
      closedir($handle); 
      return $upload_dir; 
     } else { 
      return false; 
     } 
    } else { 
     return false; 
    } 
} 

* 注:*上述代碼是僅用於說明的點,並且不應當是 複製粘貼或在生產中使用。

解析路徑,檢查是否存在,創建一個新的目錄,如果沒有,再加入尾隨斜線,如果不存在,應該是辦法完全消除服務器故障,捕獲錯誤並返回假。開發利用將意味着只是傳遞一個絕對路徑,以你的函數:

$dir = ''; 
if(!your_dir_function('/path/to/upload/dir/')){ 
    $dir = 'Sorry, directory could not be created'; 
}else{ 
    $dir = your_dir_function('/path/to/upload/dir/'); 
} 

// Write upload logic here 

echo $dir; 

希望這有助於