我创建了一个成功的文件上传系统。
但如何将上传的文件移动到具有随机名称的文件夹? (当前时间)
的index.php:
<!doctype html>
<body>
<form action="file-up.php" method="post" enctype="multipart/form-data">
<table>
<tr><td>File:</td><td><input type="file" name="myfile"></td></tr>
<tr><td> </td><td><input type="submit" value="Upload"></td></tr>
</table>
</div>
</form>
</body>
</html>
文件up.php:
<?php
$time = new DateTime();
$time->format('YmdHis');
$upload_dir = "uploads/";// . $time;
if (isset($_FILES["myfile"])) {
if ($_FILES["myfile"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
move_uploaded_file($_FILES["myfile"]["tmp_name"], $upload_dir . $_FILES["myfile"]["name"]);
echo "Uploaded File: " . $_FILES["myfile"]["name"];
}
}
?>
答案 0 :(得分:3)
试试此工作代码
<?php
$time = new DateTime();
$time->format('YmdHis');
//$upload_dir = "uploads/";// . $time;
$folder_name=date('mds');
$new_folder=mkdir($folder_name, 0777, true);
if(file_exists($new_folder)){
echo "Folder already exist";
}
$upload_dir = $folder_name.'/';
if (isset($_FILES["myfile"])) {
if ($_FILES["myfile"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
if(move_uploaded_file($_FILES["myfile"]["tmp_name"], $upload_dir. $_FILES["myfile"]["name"])){
echo "Uploaded File: " . $_FILES["myfile"]["name"];
} else {
echo $new_folder .'/'. $_FILES["myfile"]["name"];
echo "Folder created file not uploaded";
}
}
}
?>
答案 1 :(得分:0)
检查date()
mkdir()
功能和if directory already exists功能
$upload_dir = "uploads/".date('YmdHis');
if(!is_dir($upload_dir))
{
mkdir($upload_dir);
}
if (isset($_FILES["myfile"])) {
if ($_FILES["myfile"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
move_uploaded_file($_FILES["myfile"]["tmp_name"], $upload_dir . $_FILES["myfile"]["name"]);
echo "Uploaded File: " . $_FILES["myfile"]["name"];
}
}