PHP文件上传:如何将文件名中的空格替换为横杠
Fixing Filename Space-to-Dash Replacement in PHP File Upload
Hey there! The issue here is that you’re using the original filename directly without modifying any spaces. Let’s fix this easily with PHP’s str_replace() function, which lets you swap spaces for dashes in just one line.
Step-by-Step Fix Breakdown
The core change is modifying the original filename before using it in your file path and success message. We’ll use str_replace(' ', '-', $_FILES["fileToUpload"]["name"]) to replace every space in the filename with a dash (-).
Modified Full Code
<?php $target_dir = "uploads/"; // Create a cleaned filename with spaces replaced by dashes $clean_filename = str_replace(' ', '-', $_FILES["fileToUpload"]["name"]); $target_file = $target_dir . date('d_m_Y_H_i_s') . '_'. $clean_filename; if($target_file == null) { echo"nada"; } $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { // Use the cleaned filename in the success message too echo "The file ". basename(date('d_m_Y_H_i_s') . '_'. $clean_filename). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?>
Key Changes Explained
- Cleaned Filename Variable: We added
$clean_filenameto store the modified version of the original filename, ensuring all spaces are replaced with dashes. - Updated Target Path:
$target_filenow uses this cleaned filename, so the saved file on your server will have no spaces. - Consistent Success Message: The success message uses the same cleaned filename, so the user sees the exact name of the file that was stored.
Bonus Optional Cleanup
If you want to make filenames even more standardized (like avoiding case-sensitive duplicates), you can add strtolower() to convert the filename to lowercase:
$clean_filename = strtolower(str_replace(' ', '-', $_FILES["fileToUpload"]["name"]));
内容的提问来源于stack exchange,提问作者Gustavo Gbn
相关产品推荐
相关产品推荐

