PHP文件路径命名问题

PHP文件路径命名问题

问题描述:

我尝试创建一个脚本来上传多张照片,重命名照片并添加数据库条目。数据库文件名条目是正确的,但图像上传文件名是复合JPG名称。PHP文件路径命名问题

即。数据库条目正确命名文件:photo_1,photo_2,photo_3

将正在上传文件命名错误:photo_1.jpg,photo_1.jpgphoto_2.jpg,photo_1.jpgphoto_2.jpgphoto_3.jpg

不知道如何解决这是因为我的数据库条目是正确的。

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

    $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", "JPG", "PNG", "JPEG"); //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 





     //MYSQL Handling 

      mysql_query("INSERT INTO post_images(`image_filename`, `image_post_id`) VALUES('0', '".addslashes($image_post_id)."')"); 
          $new_id = mysql_insert_id(); 

          $target_path = $target_path . "post_". $new_id . "." . strtolower($ext[count($ext) - 1]);//set the target path with a new name of image 
          mysql_query("UPDATE post_images SET image_filename='post_".addslashes($new_id).".".strtolower($ext[count($ext) - 1])."' WHERE image_id='".addslashes($new_id)."'"); 












     $j = $j + 1;//increment the number of uploaded images according to the files in array  

     if (($_FILES["file"]["size"][$i] < 1000000) //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/>'; 
     } 
    } 
} 
?> 
+0

停止你正在做什么,NOW。您正在使用已弃用的,未维护且不安全的数据库API。 PDO等替代品已有十多年的历史。请参阅http://*.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – miken32

+0

为了帮助人们回答您的问题,我可以提出两点建议:1-格式化您发布的代码更具可读性。 2-告诉你期望的结果(应该得到的最终名称,即使我可以从你的代码中得到它,总是很明确的)。 –

你的问题是这条线在你的for循环:

$target_path = $target_path . "post_". $new_id . "." . strtolower($ext[count($ext) - 1]); 

此代码实际上是说“追加新的文件名到前值”,这显然不是你想要的。

要解决,只是删除$target_path=的权利:

$target_path = "post_". $new_id . "." . strtolower($ext[count($ext) - 1]); 
+0

谢谢!像魅力一样工作,非常感谢。我不擅长php。我想我将不得不弄清楚如何切换到mysqli。 – Jason

+0

不客气..!请接受答案:-) – BizzyBob