2017-08-23 28 views
-1

我是新來的php,並試圖將文件上傳到指定的目錄。 但是當我檢查的條件如下:上傳文件到指定目錄時出錯

 if(file_exists($target_dir))//check if file already exists in uploads folder 
    { 
    echo "sorry! file already exists"; 
    $uploadOK=0; 
    } 

它表明「對不起文件已經存在!」; 但我從C:\ mypictures \中選取我的圖像文件,目標目錄的路徑是C:\ xampp \ htdocs \ uploads。 我不知道爲什麼會發生這種情況。 如果有人能澄清這一點,這將是非常好的。

這裏是我的upload.php的文件的全碼:

<?php 
$target_dir="C:/xampp/htdocs/uploads/"; 
$target_file=$target_dir.basename($_FILES["fileToUpload"]["name"]); 
$uploadOK=1; 
$ImageFileType=pathinfo($target_file,PATHINFO_EXTENSION); 
if(isset($_POST["submit"])) 
    $check=getimagesize($_FILES["fileToUpload"]["tmp_name"]);//check if a file is an image or not 
     if($check == true) 
     echo "file is an image"; 
     else 
     { 
     echo "file is not an image"; 
     $uploadOK=0; 
     } 
if(file_exists($target_dir))//check if file already exists in uploads folder 
    { 
    echo "sorry! file already exists"; 
    $uploadOK=0; 
    } //doubt 
if(filesize($target_file>500000))//check if the file is too large 
    { 
    echo "file too large"; 
    $uploadOK=0; 
    } 
if($ImageFileType!="jpg" && $ImageFileType!="png" && $ImageFileType!="jpeg" && $ImageFileType!="png")//check file type 
    { 
    echo "file type not supported"; 
    $uploadOK=0; 
    } 
if($uploadOK==0)//checking for any errors 
    { 
    echo "some error occured."; 
    } 
else{ 
    if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) 
    { 
     echo "file uploaded"; 
    } 
    else{ 
     echo "file not uploaded....there was some error."; 
    } 
} 


?> 
+1

'if(file_exists($ target_file))'如果你想檢查文件,爲什麼要使用'dir'? –

回答

0

因爲你正在檢查目錄而不是文件。改變你的代碼爲

if(file_exists($target_file))//check if file already exists in uploads folder 
    { 
    echo "sorry! file already exists"; 
    $uploadOK=0; 
    } //do 
+0

是啊,我是多麼愚蠢的。我解釋了函數「file_exists」我錯了。感謝清除它。 – User96

+0

爲什麼它被降低了? @Downvoter能否請你解釋一下,以便我能糾正我的錯誤 –