2014-10-12 47 views
0

腳本:move_uploaded_file - 圖像的文件名?

<?php 
if (isset($_POST['submit'])) { 
    $j = 0; //Variable for indexing uploaded image 

    $target_path = "uploads/"; //Declaring Path for uploaded images 
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array 

     $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed 
     $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
     $file_extension = end($ext); //store extensions in the variable 

     $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image 
     $j = $j + 1;//increment the number of uploaded images according to the files in array  

     if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. 
       && in_array($file_extension, $validextensions)) { 
      if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder 
       echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; 
      } else {//if file was not moved. 
       echo $j. ').<span id="error">please try again!.</span><br/><br/>'; 
      } 
     } else {//if file size and file type was incorrect. 
      echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; 
     } 
    } 
} 
?> 

這個腳本也可以使用多個圖像上傳的JavaScript。

這個腳本工作正常,但是當多個的文件無法移動到「上傳」文件夾中的文件名出來是這樣的:

"2f594262c1f8fb56c39cc01d4543bcb9.jpg" 
"2f594262c1f8fb56c39cc01d4543bcb9.jpgf00008a16882f01d2bd7ed6d9805a4bf.jpg" 
"2f594262c1f8fb56c39cc01d4543bcb9.jpgf00008a16882f01d2bd7ed6d9805a4bf.jpge967f7fbaea4e2aee9b6f56067739aed.jpg" 

如何解決這個問題?

+0

什麼是問題? did not get u – 2014-10-12 12:34:03

+0

與您的問題無關,但要檢查上傳的文件是否屬於某種類型,請不要相信該擴展名。請檢查mime類型。順便說一下,要解決您的問題,請在'for'循環中移動'$ target_path =「uploads /」;'。 – Bjorn 2014-10-12 12:34:05

回答

1

在for循環中重置您的$target_path。現在你只是不斷追加它。

for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array 
    $target_path = "uploads/"; //Declaring Path for uploaded images 
+0

非常感謝你們。有效! – ftxn 2014-10-12 13:14:14