以下是我到目前为止,我通过microtime重新命名上传的文件,然后将其移动到名为" pdf-cv"的文件夹中,但是,我需要做的是移动它根据选择输入做一个文件夹(另外,如果我可以在目录中创建该文件夹,如果它还没有存在,那将会很棒。)非常感谢任何帮助。
示例:如果用户选择"选项1"然后上传一个文件,然后该文件将被移动到名为" Option1"的目录中的文件夹中。
选择输入:
<select id="categories" name="categories" class="categories">
<option value="">-- Select --</option>
<option value="">option 1</option>
<option value="">option 2 </option>
<option value="">option 3 </option>
</select>
上传表单:
<form action ="pdf_upload.php" id="cv_upload_form" method="post" enctype="multipart/form-data">
<div class="fileUpload text-center cv_select">
<span>Select File</span>
<input type="file" name="file" class="upload" id="pdf_input" />
</div>
<canvas class="center-block pdf_canvas" id="the-canvas" style=""><p class="preview_text">Preview</p></canvas>
<input class="cv_upload" type="submit" value="Upload">
</form>
pdf_upload.php内容:
<?php
$uploaddir = "pdf-cv/";
$allowed_ext = "pdf";
$max_size = "5000000";
$extension = pathinfo($_FILES['file'] ['name']);
$extension = $extension[extension];
$allowed_paths = explode(", ", $allowed_ext);
for($i = 0; $i < count($allowed_paths); $i++) {
if ($allowed_paths [$i] == "$extension") {
$ok = "1";
}
}
if ($ok == "1") {
if($_FILES['file']['size'] > $max_size)
{
print "File is too big!";
exit;
}
if(is_uploaded_file($_FILES['file']['tmp_name']))
{
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"],$uploaddir.''. $newfilename);
header("Location: new_begining_index.php#home");
}
print "Your CV has been successfully uploaded!";
} else {
print "Incorrect file extension!";
}
?>
答案 0 :(得分:1)
首先,您需要为选择输入提供实际值:
<select id="categories" name="categories" class="categories">
<option value="">-- Select --</option>
<option value="Option1">option 1</option>
<option value="Option2">option 2 </option>
<option value="Option3">option 3 </option>
</select>
然后验证输入,检查目录是否存在或创建它。我在下面的示例中使用die()
进行错误检查,这不是最优雅的方式,但无论如何应该回答您的问题:
$uploaddir = "pdf-cv/";
// make sure a category was selected
if (!isset($_POST['categories']) || trim($_POST['categories']) == '') {
die("no category selected");
}
// validate input against a whitelist
if (!in_array($_POST['categories'], array('Option1', 'Option2', 'Option3'))) {
die("don't hack me bruh");
}
// make directory if it doesn't exist
$newdir = $uploaddir . $_POST['categories'];
if (!file_exists($newdir)) {
mkdir($newdir, 0755, true);
}
现在您可以正常移动文件:
move_uploaded_file($_FILES["file"]["tmp_name"], $newdir . '/' . $newfilename);
请注意,对于$uploaddir
,您可能需要使用绝对路径而不是相对路径。例如:/var/www/public_html/my_project/pdf-cv/
。如果你不知道你的绝对路径是什么,通常可以在$_SERVER
超全球中找到:
echo '<pre>';
var_dump($_SERVER);
echo '</pre>';