I have a basic upload form
<html>
<head>
<title>Upload a File</title>
</head>
<body>
<font face=verdana size=2>
<form enctype="multipart/form-data" method="post" action="upload_file.php">
<input type="hidden" name="MAX_FILE_SIZE" value="25000">
<p><strong>File to Upload:</strong><br>
<input type="file" name="our_file" size="30"></p>
<P><input type="submit" name="submit" value="Upload File"></p>
</form>
</font></body>
</html>
And the php file
<?
if ($our_file != "") {
copy($our_file, "upload/$our_file_name") or die("Couldn't Upload the file!");
} else {
die("No input file specified");
}
?>
<html>
<head>
<title>Successful File Upload!</title>
<body><font face=verdana size=2>
<B>Success!</B>
<P>You sent: <? echo "$our_file_name"; ?>, a <? echo "$our_file_size"; ?>
byte file with a mime type of <? echo "$our_file_type"; ?>.</p>
</font></body>
</html>
I would like the user to be able to choose what directory he uploads the file to. I assume I would need a form for the HTML side of it but I don't know what to add in the PHP. Any help?
Assuming you only have a fixed number of directories, include a select in your HTML.
@thephpdeveloper, As long as your permissions are set right for your directories, I don't think selecting where you upload is going to be anymore dangerous than any other upload. I am by no means a security expert. Just make sure you're preventing injection, etc.
<select name="selectDir">
<option value="1">This Directory</option>
<option value="2">That Directory</option>
</select>
// on your submit
if( $_POST['selectDir'] === '1' ){
$dir = './thisdir/';
}elseif( $_POST['selectDir'] === '2' ){
$dir = './thatdir/';
}else{
die('You did not enter a valid value');
}
if ($our_file != "") {
copy($our_file, $dir."".$our_file_name) or die("Couldn't Upload the file!");
}else{
die("No input file specified");
}
In your call to copy()
you need to modify "upload/$our_file_name"
to be the directory where you want the file to end up.
This is probably a very bad idea unless you know how to restrict what can end up in there. If you don't care at all about security, you can do something like this:
/* THIS NEXT LINE IS A BAD IDEA. DO NOT DO THIS. */
copy($our_file, $_POST['path_from_user'] . '/' . $our_file_name) /* BAD IDEA. DON'T DO IT THIS WAY */
/* DID I MENTION THAT THIS IS A BAD IDEA AND YOU SHOULD NOT DO IT THIS WAY? */
Of course, as you guessed, you'd need to set up the HTML form properly for that to work.
There are a number of ways one might try to make this more secure. One would be to use realpath()
to check that the file will end up somewhere you expect. Another would be to provide the user with a small number of choices where the file can end up and, on the PHP side, make sure that no matter what is sent by the form (since users can mess with it) that you only send the file to one of those small number of choices. Actually, if you can do both of those, even better.