如何在PHP中上传多个带有重命名的图像并插入数据库

jhkqcmku  于 2023-03-11  发布在  PHP
关注(0)|答案(1)|浏览(114)

我想图像重命名上传前和重命名后的图像名称应该插入到PHP数据库。我正在使用下面的代码上传图像和插入到数据库中的一些其他数据。请帮助我重命名图像,因为我是PHP初学者。

$uploadDir = 'uploads/';
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg'); 
$response = array( 
    'status' => 0, 
    'message' => 'Form submission failed, please try again.' 
); 
$errMsg = ''; 
$valid = 1;
if(isset($_POST['name'])){ 
    $name         = $_POST['name'];  
    $filesArr     = $_FILES["images"];
    if(empty($name)){ 
        $valid = 0; 
        $errMsg .= '<br/>Please enter your name.'; 
    } 
    if($valid == 1){ 
        $uploadStatus = 1; 
        $fileNames = array_filter($filesArr['name']); 
        $uploadedFile = ''; 
        if(!empty($fileNames)){  
            foreach($filesArr['name'] as $key=>$val){  
                $fileName = basename($filesArr['name'][$key]);  
                $targetFilePath = $uploadDir . $fileName;  
                $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); 
                if(in_array($fileType, $allowTypes)){  
                    // Upload file to server  
                    if(move_uploaded_file($filesArr["tmp_name"][$key], $targetFilePath)){  
                        $uploadedFile .= $fileName.','; 
                    }else{  
                        $uploadStatus = 0; 
                        $response['message'] = 'Sorry, there was an error uploading your file.'; 
                    }  
                }else{  
                    $uploadStatus = 0; 
                    $response['message'] = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.'; 
                }  
            }  
        } 
        if($uploadStatus == 1){ 
            // Insert form data in the database 
            $uploadedFileStr = trim($uploadedFile, ','); 
            $insert = $conn->query("INSERT INTO firmware 
                        (cat_id, name, description, 
                        images, file_link, 
                        youtube_link, file,tags) 
                VALUES ('".$cat_id."', '".$name."', '".$description."', 
                        '".$uploadedFileStr."', '".$file_link."', 
                        '".$youtube_link."', '".$file."', '".$tags."')"); 
              
        } 
    }else{ 
         $response['message'] = 'Please fill all the mandatory fields!'.$errMsg; 
    } 
} 
echo json_encode($response);
xdnvmnnf

xdnvmnnf1#

重命名问题

**您的代码存在许多严重问题,包括SQL注入漏洞。**但如果是简单的培训,您应该了解:

move_uploaded_file($filesArr["tmp_name"][$key], $targetFilePath)

$targetFilePath是你的文件的新路径和名称。所以你可以重命名你的文件!
让我们尝试更改这一行:

$fileName = basename($filesArr['name'][$key]);

收件人:

$fileName = basename('myname('.$key.').'.$fileType);

SQL注入漏洞

尝试使用预准备语句,而不是query()
Read Here

相关问题