2014-10-12 26 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