Hello,

I have a script that allows me to upload a new directory into the main area of my website but I would like to create a sub directory one level deeper than the main area but I can't seem to get it to work. I don't know where to tell the script where to start.

I am sure I am missing something very simple but.....I am very new at PHP and found this script so I am learning as I go.

Here is the code I am using for file uploads so there is more here than just creating a directory. I have the uploading working to a specified directory but just testing creating a new one for now with the hopes of having the files upload to the new sub directory each time someone uploads files.

Thanks,

Dave


<?php 
  if(isset($_POST['submit'])){ 
    $create_directory = $_POST['create_directory']; 
    if(mkdir($create_directory)); 
  } 
?> 

    <?php
include ($_SERVER['DOCUMENT_ROOT']."/classes/upload/upload_class.php"); //classes is the map where the class file is stored (one above the root)
//error_reporting(E_ALL);
$max_size = 10485760; // the max. size for uploading (10mb)

class muli_files extends file_upload {

var $number_of_files = 0;
var $names_array;
var $tmp_names_array;
var $error_array;
var $wrong_extensions = 0;
var $bad_filenames = 0;

function extra_text($msg_num) {
	switch ($this->language) {
		case "de":
		// add you translations here
		break;
		default:
		$extra_msg[1] = "Error for: <b>".$this->the_file."</b>";
		$extra_msg[2] = "You have tried to upload ".$this->wrong_extensions." file(s) with an invalid extension, only the following extensions are allowed: <b>".$this->ext_string."</b>";
		$extra_msg[3] = "Please select at least one file to upload.";
		$extra_msg[4] = "Please click the upload button only once.";
		$extra_msg[5] = "You have tried to upload <b>".$this->bad_filenames." file(s)</b> with invalid characters inside the filename.";
	}
	return $extra_msg[$msg_num];
}
// this method checks the number of files for upload
// this example works with one or more files
function count_files() {
	foreach ($this->names_array as $test) {
		if ($test != "") {
			$this->number_of_files++;
		}
	}
	if ($this->number_of_files > 0) {
		return true;
	} else {
		return false;
	} 
}
function upload_multi_files () {
	$this->message = "";
	if ($this->count_files()) {
		foreach ($this->names_array as $key => $value) { 
			if ($value != "") {
				$this->the_file = $value;
				$new_name = $this->set_file_name();
				if ($this->check_file_name($new_name)) {
					if ($this->validateExtension()) {
						$this->file_copy = $new_name;
						$this->the_temp_file = $this->tmp_names_array[$key];
						if (is_uploaded_file($this->the_temp_file)) {
							if ($this->move_upload($this->the_temp_file, $this->file_copy)) {
								$this->message[] = $this->error_text($this->error_array[$key]);
								if ($this->rename_file) $this->message[] = $this->error_text(16);
								sleep(1); // wait a seconds to get an new timestamp (if rename is set)
							}
						} else {
							$this->message[] = $this->extra_text(1);
							$this->message[] = $this->error_text($this->error_array[$key]);
						}
					} else {
						$this->wrong_extensions++;
					}
				} else {
					$this->bad_filenames++;
				}
			} 
		}
		if ($this->bad_filenames > 0) $this->message[] = $this->extra_text(5);
		if ($this->wrong_extensions > 0) {
			$this->show_extensions();
			$this->message[] = $this->extra_text(2);
		}
	} else {
		$this->message[] = $this->extra_text(3);
	}
}
}

$multi_upload = new muli_files;

$multi_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/contest2009/"; // "contest2009" is the folder for the uploaded files (you have to create this folder)
$multi_upload->extensions = array(".png", ".jpg", ".bmp", ".gif", ".jpeg", ".tif", ".tiff"); // specify the allowed extensions here
$multi_upload->message[] = $multi_upload->extra_text(4); // a different standard message for multiple files
//$multi_upload->rename_file = true; // set to "true" if you want to rename all files with a timestamp value
$multi_upload->do_filename_check = "y"; // check filename ...

if(isset($_POST['Submit'])) {
	$multi_upload->tmp_names_array = $_FILES['upload']['tmp_name'];
	$multi_upload->names_array = $_FILES['upload']['name'];
	$multi_upload->error_array = $_FILES['upload']['error'];
	$multi_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true
	$multi_upload->upload_multi_files();
	$multi_upload->create_directory();
}
?> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
  <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> 
  <title></title> 
  </head> 
  <body> 
    <?php 
      if(isset($advise)) 
        echo $advise; 
    ?> 
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 
      Create Sub Directory: <input type="text" name="create_directory" value="" /><br /><br /> 
      <input type="submit" name="submit" value="Submit" /> 
    </form> 
  </body> 
</html> 

    This works for me. Looks like you need the "0777, true" to make the command recursive.

    But,if you create a dir called "apple" and then create "apple/orange", your code works here.

    <?php 
      if(isset($_POST['submit'])){ 
        echo mkdir($_POST['create_directory'], 0777, true) ? 
        "Success" : "Fail";
      } 
    ?> 
    
    <form  method="post"> 
    Create Sub Directory: <input type="text" name="create_directory" value="" /><br /><br /> 
    <input type="submit" name="submit" value="Submit" /> 
    </form> 

      Thanks for the quick reply.

      When I update to what you have provided I still get the same result. Perhaps I did not word my problem correctly.

      I have a directory now which is named: contest2009\

      This is where I need the sub directories to go. How would I do that?

      I do see what happens when I enter "apple/orange". I get a subdirectory under apple. Perhaps I need to hide the directory contest2009\ so that whatever is entered in the text box is created beneath this directory?

      Thanks,

      Dave

        Sounds like a plan. Something like:

        mkdir("contest2009/" . $_POST['create_directory'], 0777, true);

        Look out for permissions and foreward vs backslashes.

        Im unsure how PHP handles portable file system paths, but I always use forward slashes, and that seems to work. Backslashes can also do some weird special string charactors.

        have fun.

        Ooo, One last one. Look out for "..". People can type in "../apple/orange" and you end up with directories in places you dont want them

          Thank you...that did the trick.

          Now that this is working I will try to incorporate that code into the uploading code so it does all of this at once. I hope.

          Thanks again.

          Dave

            As I noted last night I was able to create a sub directory with your help. Now I am trying to create a sub directory and upload to that directory from the same Submit button to do both functions at the same time. The file uploads but in the main directory and the sub directory is not created.

            Could you point out where I have gone wrong?

            Thanks,

            Dave

            
                <?php
            include ($_SERVER['DOCUMENT_ROOT']."/classes/upload/upload_class.php"); //classes is the map where the class file is stored (one above the root)
            //error_reporting(E_ALL);
            $max_size = 10485760; // the max. size for uploading (10mb)
            
            class muli_files extends file_upload {
            
            var $number_of_files = 0;
            var $names_array;
            var $tmp_names_array;
            var $error_array;
            var $wrong_extensions = 0;
            var $bad_filenames = 0;
            
            function extra_text($msg_num) {
            	switch ($this->language) {
            		case "de":
            		// add you translations here
            		break;
            		default:
            		$extra_msg[1] = "Error for: <b>".$this->the_file."</b>";
            		$extra_msg[2] = "You have tried to upload ".$this->wrong_extensions." file(s) with an invalid extension, only the following extensions are allowed: <b>".$this->ext_string."</b>";
            		$extra_msg[3] = "Please select at least one file to upload.";
            		$extra_msg[4] = "Please click the upload button only once.";
            		$extra_msg[5] = "You have tried to upload <b>".$this->bad_filenames." file(s)</b> with invalid characters inside the filename.";
            	}
            	return $extra_msg[$msg_num];
            }
            // this method checks the number of files for upload
            // this example works with one or more files
            function count_files() {
            	foreach ($this->names_array as $test) {
            		if ($test != "") {
            			$this->number_of_files++;
            		}
            	}
            	if ($this->number_of_files > 0) {
            		return true;
            	} else {
            		return false;
            	} 
            }
            function upload_multi_files () {
            	$this->message = "";
            	if ($this->count_files()) {
            		foreach ($this->names_array as $key => $value) { 
            			if ($value != "") {
            				$this->the_file = $value;
            				$new_name = $this->set_file_name();
            				if ($this->check_file_name($new_name)) {
            					if ($this->validateExtension()) {
            						$this->file_copy = $new_name;
            						$this->the_temp_file = $this->tmp_names_array[$key];
            						if (is_uploaded_file($this->the_temp_file)) {
            							if ($this->move_upload($this->the_temp_file, $this->file_copy)) {
            								$this->message[] = $this->error_text($this->error_array[$key]);
            								if ($this->rename_file) $this->message[] = $this->error_text(16);
            								sleep(1); // wait a seconds to get an new timestamp (if rename is set)
            							}
            						} else {
            							$this->message[] = $this->extra_text(1);
            							$this->message[] = $this->error_text($this->error_array[$key]);
            						}
            					} else {
            						$this->wrong_extensions++;
            					}
            				} else {
            					$this->bad_filenames++;
            				}
            			} 
            		}
            		if ($this->bad_filenames > 0) $this->message[] = $this->extra_text(5);
            		if ($this->wrong_extensions > 0) {
            			$this->show_extensions();
            			$this->message[] = $this->extra_text(2);
            		}
            	} else {
            		$this->message[] = $this->extra_text(3);
            	}
            }
            }
            
            $multi_upload = new muli_files;
            
            $multi_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/contest2009/"; // "contest2009" is the folder for the uploaded files (you have to create this folder)
            $multi_upload->extensions = array(".png", ".jpg", ".bmp", ".gif", ".jpeg", ".tif", ".tiff"); // specify the allowed extensions here
            $multi_upload->message[] = $multi_upload->extra_text(4); // a different standard message for multiple files
            //$multi_upload->rename_file = true; // set to "true" if you want to rename all files with a timestamp value
            $multi_upload->do_filename_check = "y"; // check filename ...
            
            if(isset($_POST['Submit'])) {
            	$multi_upload->tmp_names_array = $_FILES['upload']['tmp_name'];
            	$multi_upload->names_array = $_FILES['upload']['name'];
            	$multi_upload->error_array = $_FILES['upload']['error'];
            	$multi_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true
            	$multi_upload->upload_multi_files();
            }
            ?> 
            
            <!-- <p>Maximum Filesize = <?php echo $max_size; ?> bytes. (100mb each) </p> -->
            <p>Maximum Filesize = 10,485,760 bytes (10mb each file). </p>
            
            <?php 
              if(isset($_POST['submit'])){ 
                mkdir("contest2009/" . $_POST['create_directory'], 0777, true);
              } 
            ?>
            
            
            <?php 
              if(isset($advise)) 
                echo $advise; 
            ?> 
            
            <form name="form1" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
              <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>">
            
            Please enter your first and last name: <input type="text" name="create_directory" value="" /><br /><br /> 
            <p><?php echo $multi_upload->show_error_string(); ?></p>  
            
              <label for="upload[]">Photo &nbsp;&nbsp;1:</label>
              <input type="file" name="upload[]" size="30"><br>
              <label for="upload[]">Photo &nbsp;&nbsp;2:</label>
              <input type="file" name="upload[]" size="30"><br>
              <label for="upload[]">Photo &nbsp;&nbsp;3:</label>
              <input type="file" name="upload[]" size="30"><br>
              <label for="upload[]">Photo &nbsp;&nbsp;4:</label>
              <input type="file" name="upload[]" size="30"><br>
              <label for="upload[]">Photo &nbsp;&nbsp;5:</label>
              <input type="file" name="upload[]" size="30"><br>
              <label for="upload[]">Photo &nbsp;&nbsp;6:</label>
              <input type="file" name="upload[]" size="30"><br>
              <label for="upload[]">Photo &nbsp;&nbsp;7:</label>
              <input type="file" name="upload[]" size="30"><br>
              <label for="upload[]">Photo &nbsp;&nbsp;8:</label>
              <input type="file" name="upload[]" size="30"><br>
              <label for="upload[]">Photo &nbsp;&nbsp;9:</label>
              <input type="file" name="upload[]" size="30"><br>
              <label for="upload[]">Photo 10:</label>
              <input type="file" name="upload[]" size="30"><br>
            
            <br>  <input type="submit" name="Submit" value="Click to Upload File(s)">
            
            </form>
            
            <p><?php echo $multi_upload->show_error_string(); ?></p>
            
            
            

              Um, you have $_POST['submit'] but the name of the submit button is "Submit". Captital letters count.

              Always remember to echo a message just to make sure code actually runs. ie: echo "Creating directory". and echo "Directory created".

              Plus, you need to add the destination folder to the filename of the uploaded file.

              Try using basename() for this:
              http://us2.php.net/manual/en/function.basename.php

              Hope that helps.

                Thank you again, I am slowly learning bits and pieces as I go which is great. I corrected the "Submit" vs "submit" issue that you noticed.

                I don't really want to tell the uploader that the directory was created as this is just for my use. As far as they know I just want their name. They do get an echo message that the files uploaded or they did not so I am ok on this part.

                I reviewed the link for basename() that you provided and looked at the examples but I am not getting this into my head. I don't really know how to apply this to my script.

                I hope this is the last time I need to bother you.

                Thanks,

                Dave

                  This code works for me. There is some more good advice here:

                  http://www.tizag.com/phpT/fileupload.php

                  <?php 
                    if ($_POST["upload"])
                    {
                      $path = "files/" . $_POST["dst"] . "/";
                      mkdir($path, 0777, true);
                      foreach ($_FILES["file"]["tmp_name"] as $key => $src)
                      {
                        move_uploaded_file($src, $path . basename($_FILES["file"]["name"][$key]));
                      }
                    }
                  ?> 
                  <form method=post enctype=multipart/form-data>
                  Destination: <input type=text name=dst><br>
                  File 1: <input type=file name=file[]><br>
                  File 2: <input type=file name=file[]><br>
                  File 3: <input type=file name=file[]><br>
                  File 4: <input type=file name=file[]><br>
                  <input type=submit name=upload value=Upload>
                  </form>

                  As far as error messages, its just a programming method of confirming code is running as expected. Some people call it "logging messages" or "verbose-ing".

                  Its easy to have a log function that you disable when you go live.

                  The above is lacking error checking, but I tried to make it as simple as possible. Note, mkdir() will fail if the directory exists, so, use file_exists() as well.

                  I would log messages to the user of successfully uploaded file. Maybe give them a list of files already uploaded to their account names.

                  Hope that helps you.

                    Write a Reply...