我有一个上传按钮,当用户点击上传按钮时,用户选择的文件会上传到特定目录。上传按钮调用upload.php文件。
我有一个页面,对于一个问题,在创建测验时可以填写最多5个选项答案,并为每个输入的选项上传音频音轨。
upload.php的
<?php
$count=0;
$count++;
$target_dir = "Uploads/Question".$count."/Options/";
$target_file = "Uploads/Question".$count."/Options/".$count.".mp3"; //renames file as 1, 2, 3 etc.
$uploadOk = 1;
$audioFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "<br/>Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 50000000) {
echo "<br/>Sorry, your file is too large.";
$uploadOk = 0;
}
//Allow certain file formats
if($audioFileType != "avi" && $audioFileType != "mp3" && $audioFileType != "mp4"
&& $audioFileType != "wma" ) {
echo "<br/>Only AVI, mp3, mp4 & WMA files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "<br/>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)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "<br/>Sorry, there was an error uploading your file.";
}
}
?>
这部分代码$target_file = "Uploads/Question".$count."/Options/".$count.".mp3";
应该将文件保存为1.mp3,我希望每次将1增加为1,2,3等。如您所见,在文件本身的开头将计数设置为0。
我的问题是,每次调用upload.php文件时如何增加计数?
有点长,因为很难解释。感谢您的帮助。
答案 0 :(得分:0)
增加计数的一种简单方法是计算该目录中已存在的文件数。
更新了upload.php
<?php
$count=0;
$count++;
$i = 1;
$dir = "Uploads/Question".$count."/Options/"; //count files in that directory
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
$target_dir = "Uploads/Question".$count."/Options/";
$target_file = "Uploads/Question".$count."/Options/".$i.".mp3"; //renames file as 1, 2, 3 etc.
$uploadOk = 1;
$audioFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "<br/>Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 50000000) {
echo "<br/>Sorry, your file is too large.";
$uploadOk = 0;
}
//Allow certain file formats
if($audioFileType != "avi" && $audioFileType != "mp3" && $audioFileType != "mp4"
&& $audioFileType != "wma" ) {
echo "<br/>Only AVI, mp3, mp4 & WMA files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "<br/>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)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "<br/>Sorry, there was an error uploading your file.";
}
}
?>