【发布时间】:2013-12-06 13:25:33
【问题描述】:
我有这个用于多个图像上传器的脚本,问题是重命名文件。好吧,我想给像 albumid_photoid.png 这样的图像命名(例如 4_1.png)。在循环中选择多个图像时,我总是得到相同的名称(查看最后一个变量 $newName)(例如:4_1.jpg、4_1.jpg、4_1.jpg - 假设我选择了 3 个文件)。
if (isset($_POST['upload'])) {
$count_files = count($_FILES['uploaded_file']['tmp_name']);
$sql_album_id = "SELECT * FROM albums WHERE title = '".$_GET['album']."'";
$res_album_id = mysql_query($sql_album_id) or die(mysql_error());
$row_album_id = mysql_fetch_assoc($res_album_id);
for ($i = 0; $i < $count_files; $i++) {
// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName = $_FILES["uploaded_file"]["name"][$i]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"][$i]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"][$i]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"][$i]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"][$i]; // 0 for false... and 1 for true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$fileTitle = $kaboom[0];
// START PHP Image Upload Error Handling --------------------------------------------------
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.<br />";
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than 5 Megabytes in size.<br />";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.<br />";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occurred while processing the file. Try again.<br />";
}
// END PHP Image Upload Error Handling ---------------------------------
$row_select = mysql_fetch_assoc($res_select);
// renaming images
$sql_count = "SELECT COUNT(id) FROM photos WHERE album_id = '".$row_album_id['id']."'";
$res_count = mysql_query($sql_count) or die(mysql_error());
$row_count = mysql_fetch_row($res_count);
$rc = $row_count[0] + 1;
$fileTitle = $row_album_id['id']."_".$rc;
$newName = $fileTitle.".".$fileExt;
echo $newName;
}
}
【问题讨论】:
-
你真的应该检查
['error']之前你做任何其他事情。另外,您很容易受到 sql 注入攻击。您的文件扩展名正则表达式无效,并将让foogif作为有效文件名通过。您从 $res_select 中获取,但从不运行查询来生成该句柄,等等等等 -
@marc-b $res_select 变量在我的其余代码中,并且 ['error'] 没有错误