PHP Code:
<?php
// This is the root uploads folder from which users can add new folders / files
// E.g. uploads/dave/foo.gif
define('UPLOAD_DIR', 'uploads/');
// On form submission
if(isset($_POST['submit'])) {
// Trim the user input for the directory
$dir = trim($_POST['dir']);
// If it's not an empty string
if(!empty($dir)) {
// If the files array is not empty
if(!empty($_FILES)) {
// Do the following if no errors occurred on the file upload
if(!$_FILES['fileUpload']['error']) {
// $path will contain the full path to the directory (relative to the current working file)
// For example, if this file is in /admin/, uploads will go to /admin/uploads/DIRECTORY_NAME/
$path = UPLOAD_DIR . $dir;
// Find out if a directory already exists with the same name
if(file_exists($path)) {
$error = $dir . ' already exists in the uploads folder.';
// You may want to allow the user to just add the file to the pre-existing directory
// Instead of returning an error.
} else {
// Attempt to make the directory
if(mkdir($path)) {
// Get the temp name, and the destination file name
$src = $_FILES['fileUpload']['tmp_name'];
$dst = $_FILES['fileUpload']['name'];
// Try to upload the file in the newly created folder
if(move_uploaded_file($src, $path . '/' . $dst)) {
echo 'Successfully created the new directory and uploaded the file.';
} else {
$error = 'Failed to upload the file.';
}
} else {
$error = 'An error occurred while trying to make the new directory.';
}
}
} else {
// Code for catching errors with file uploads here
}
}
} else {
$error = 'Please specify a directory to upload to.';
}
}
?>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<?php
if(isset($error))
echo '<p>' . $error . '</p>';
?>
<input type="file" name="fileUpload">
<p>
Directory Name: <input type="text" name="dir">
</p>
<p>
<input type="submit" name="submit" value="Upload File">
</p>
</form>
</body>
</html>
I've written the above to help you understand how the file upload process should work. THIS IS IN NO WAY SAFE!. The code above needs a lot more error checking and sanitizing before it's fit for purpose. It should give you a better idea of how to code it though. Since it's just a text box, obviously the directory name could be abused in its current state, but again, this is just to give you a nudge in the right direction.
Let me know if you have any questions.
P.S : Make sure whatever you specify as the "UPLOAD_DIR" is already present on your system, as the code does not check for this. Working on the code above, you should already have a folder called "uploads" in the folder where you're running the code from.
Bookmarks