要使用PHP上传一个文件并根据其名称创建一个文件夹,然后将文件移动到该文件夹中,可以按照以下步骤操作:
以下是一个简单的示例,展示了如何实现上述功能:
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, 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 {
// Create folder if it doesn't exist
$folder_name = pathinfo($target_file, PATHINFO_FILENAME);
$folder_path = $target_dir . $folder_name;
if (!file_exists($folder_path)) {
mkdir($folder_path, 0777, true);
}
// Move file to the created folder
$new_target_file = $folder_path . '/' . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $new_target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
upload_max_filesize
和post_max_size
的值。通过上述步骤和代码示例,你可以实现文件上传并根据文件名创建文件夹,然后将文件移动到该文件夹中。
领取专属 10元无门槛券
手把手带您无忧上云