polarexpress

  • Aug 10, 2018
  • Joined Apr 22, 2012
  • In upload.php i have the following form

    <form action="upload.php" method="POST" id="upload" enctype="multipart/form-data">
    
    <input type="file" name="file" id="file"/>
    
    <input type="button"  value="Insert" onclick='$.post("file.php", { command: "upload", file:$("input[type=file]#file").val()}, function(data){ $("#message").html(data); });'/>
    
    </form>
    
    <span id="message"></span>

    In file.php the upload syntax in as following:

    if($_POST['command'] == 'upload'){
    
    $dir = "/public_html/";
    if (!is_dir($dir)) mkdir($dir, 0777);
    
    $file = $_FILES['file']['name'];
    $path = $dir . '/'. $file;
    
    if (move_uploaded_file ($_FILES['file']['tmp_name'], $path)) {    
    echo $file. 'was successfully uploaded'; }else{ echo $file. 'was not uploaded'; } }

    I'm unable to get the name and data of file through onclick event. Any comment shall be well appreciated. This is a quite simple and very basic upload syntax but I want to know if the file name along with file data can be parsed this way from html form for processing in application server.

    • Hi Weedpacket,

      I'm using foreach() statement now. I had to define the index in file upload input. Now I can retrieve the path as desisred.

      Anyway, thanks for your effort for trying to bring up the thing in light.

      Weedpacket;11062873 wrote:

      Since you want them all in one array my first thought is to put them all into one array (instead of putting each one in a different array).
      Maybe what you're trying to say is (I've also tidied up the formatting):

      $updir = "/public_html/";
      
      if (isset($_FILES['upload'])) {
      	$dir = array();
      	for($f=0; $f<count($_FILES['upload']['name']); $f++) { // Yes, I'd use foreach() as well.
      		$file = $_FILES['upload']['name'][$f];     
      
      	$file_name = pathinfo($file, PATHINFO_FILENAME);        
      	$new_file_name = basename($file_name.'.'.'pdf');
      	$path = ($updir . $new_file_name);
      
      
      	if (move_uploaded_file ($_FILES['file_up']['tmp_name'][$f], $path)) {
      
      		echo "Success";
      		$dir[] = array($path);
      	}
      }
      // Now try var_dump($dir);
      }  
      • it returns two blank arrays with two values where each one has a numeric index 0.

        I want to extract the paths so that I can use these as value of a single array or use in another array

        • Hi Nog,

          How foreach loop makes the difference than for loop when $path isn't an array. Have you seen the output of var_dump in my question? In this case shall not the foreach loop brings the same result like,

          var_dump($path);
          string(23) "/public_html/image1.pdf"  
          string(23) "/public_html/image2.pdf"

          Here we only have two isolated strings in result returned by [$f] loop in upload process which we want use as a numeric array inside the [$f] loop execution like.

          $filearray = array($path) ;
          foreach ($filearray  as filelist){
          var_dump($filelist);
          }
          
          array(1) { 
          [0]=> 
          string(23) "/public_html/image1.pdf"  
          [1]=> string(23) "/public_html/image2.pdf" }

          It's not obvious that the array has to be an associative array. Let's share your idea with my perception.

          NogDog;11062865 wrote:

          I'd start by using a foreach() loop instead of a for() loop.

          foreach($_FILES['upload']['name'] as $ix => $name) {
              // Now you have the current index for each piece in $ix,
              // and the file name is already in $name.
          }
          
          • How to index and extract array values inside a PHP for loop? Is there a way to do it?

            I have included var_dump output and asked my question inside the following PHP upload script in comment out section.

            My upload script is as following:

            $updir = "/public_html/";
            
            if (isset($_FILES['upload'])) {
              for($f=0; $f<count($_FILES['upload']['name']); $f++) {
                $file = $_FILES['upload']['name'][$f];     
            
            $file_name = pathinfo($file, PATHINFO_FILENAME);		
            $new_file_name = basename($file_name.'.'.'pdf');
            $path = ($updir . $new_file_name);
            
            
            if (move_uploaded_file ($_FILES['file_up']['tmp_name'][$f], $path)) {
            
             echo "Success";
            
            
            
             var_dump($path);
            //				$path output here is as following:
            
            //				string(23) "/public_html/image1.pdf" 
            //				string(23) "/public_html/image2.pdf" 
            //				
                 $dir = array($path);
                 var_dump($dir);		
            //				$dir output here is as following:
            //				
            //				
            //				array(1) { 
            //				[0]=> string(23) "/public_html/image1.pdf" 
            //				} 
            //				
            //				array(1) { 
            //				[0]=> string(23) "/public_html/image2.pdf" 
            //				} 
            //				
            //				HOW TO MERGE THE ABOVE TWO ARRAYS WITH AN INDEX  HERE LIKE
            //				
            //				array(1) {
            //				[0]=>
            //				string(23) "/public_html/image1.pdf" 
            //				[1]=>
            //				string(23) "/public_html/image2.pdf"
            //				}
            //				
            //				AND OUTPUT THE ARRAY KEY VALUES INDIVIDUALLY?
            
            
            
            
            }
            }
            }
            
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
              <input type="file" class="file_up" name="file_up[]" multiple>
              <input type="submit" value="UPLOAD" id="submit" />
            </form>

            The example current $_FILES array for two uploaded files are as following:

            array(1) {
              ["upload"]=>
              array(5) {
                ["name"]=>
                array(2) {
                  [0]=>
                  string(10) "image1.pdf"
                  [1]=>
                  string(10) "image2.pdf"
                }
                ["type"]=>
                array(2) {
                  [0]=>
                  string(9) "image/pdf"
                  [1]=>
                  string(9) "image/pdf"
                }
                ["tmp_name"]=>
                array(2) {
                  [0]=>
                  string(14) "/tmp/phprHDGH2"
                  [1]=>
                  string(14) "/tmp/phpHGGFjH"
                }
                ["error"]=>
                array(2) {
                  [0]=>
                  int(0)
                  [1]=>
                  int(0)
                }
                ["size"]=>
                array(2) {
                  [0]=>
                  int(46556)
                  [1]=>
                  int(37747)
                }
              }
            }
            • polarexpress;11041379 wrote:

              The following recursive function copy files from one destination folder to another destination folder. How can i use the same function for copying file from multiple destination folders to destination folders?

              if (isset($_POST['submit'])) {
              
              function recurse_copy($src,$dst) { 
                  $dir = opendir($src);
                  while(false !== ( $file = readdir($dir)) ) {
                      if (( $file != '.' ) && ( $file != '..' )) {
                          if ( is_dir($src . '/' . $file) ) {
                              recurse_copy($src . '/' . $file,$dst . '/' . $file);
                          }
                          else {
                              copy($src . '/' . $file,$dst . '/' . $file);
                          }
                      }
                  }
                  closedir($dir);
                  //echo "$src";
              }
              $src = "/home/user/public_html/dir/subdir/source_folder/"; 
              $dst = "/home/user/public_html/dir/subdir/destination_folder/"; 
              recurse_copy($src,$dst);
              }

              Readers, my code is in unintentional incorrect state. It should be read as:

              if (isset($_POST['submit'])) {
                  function recurse_copy($src,$dst) { 
                      $dir = opendir($src);
              		@mkdir($dst); 
                      while(false !== ( $file = readdir($dir)) ) {
                          if (( $file != '.' ) && ( $file != '..' )) {
                              if ( is_dir($src . '/' . $file) ) {
                                  recurse_copy($src . '/' . $file,$dst . '/' . $file);
                              }
                              else {
                                  copy($src . '/' . $file,$dst . '/' . $file);
                              }
                          }
                      }
                      closedir($dir);
                      //echo "$src";
                  }
              if (!is_dir($dst)) mkdir($dst, 0777);
              $src = "/home/user/public_html/dir/subdir/source_folder/"; 
              $dst = "/home/user/public_html/dir/subdir/destination_folder/"; 
              recurse_copy($src,$dst);
              }

              The edited code shall work perfectly based on copy and paste. It also shall create a destination directory on form submit. You only need to replace $scr & $dst variables according to your directory path.

              • Hmm, it's simple to check the conditions by arranging multiple source and destination directories in an array .

                but how can I target a single file or folder in source directory to be copied to destination directory in recurse_copy(); function if there are several files or folders are there in the source directory?

                I see no reference about it in PHP copy(); manual.

                Thanks,

                • Shall I have to? Can't I define multiple sources & destinations folders in a single call?

                  • The following recursive function copy files from one destination folder to another destination folder. How can i use the same function for copying file from multiple destination folders to destination folders?

                    if (isset($_POST['submit'])) {
                    
                    if (!is_dir($dst)) mkdir($dst, 0777);
                    
                    function recurse_copy($src,$dst) { 
                        $dir = opendir($src);
                        while(false !== ( $file = readdir($dir)) ) {
                            if (( $file != '.' ) && ( $file != '..' )) {
                                if ( is_dir($src . '/' . $file) ) {
                                    recurse_copy($src . '/' . $file,$dst . '/' . $file);
                                }
                                else {
                                    copy($src . '/' . $file,$dst . '/' . $file);
                                }
                            }
                        }
                        closedir($dir);
                        //echo "$src";
                    }
                    $src = "/home/user/public_html/dir/subdir/source_folder/"; 
                    $dst = "/home/user/public_html/dir/subdir/destination_folder/"; 
                    recurse_copy($src,$dst);
                    }
                    • I also assume that PHP hasn't developed any code to establish session or query string based interlinks between database & directory. May it's very hard to think that way.

                      I guess it's better to save user level files in a unique directory which shall remain unchanged.

                      Thanks,

                      • I'm not copier. Ultimately, I don't get any clue about how should a define the basename as a variable in this case.

                        You must know that rename function always looks for the directory name to be renamed before performs it task and a directory that has a constant variable value can't be renamed anymore when it is done once.

                        Thanks,

                        • dalecosp defined the variable $p as

                          $p = "/path/to/some/subdirectory/"; where "subdirectory" is a known directory name. In this case basename("/path/to/some/subdirectory/"); shall return "subdirectory" but I want something that returns $subdirectory as a base name as it shall be renamed dynamically. "subdirectory" itself in the above code should be a variable before doing anything.

                          My question is how can I extract "subdirectory" as a variable from directory path when the directory name is unknown? The predefined name of "subdirectory" can be anything on the contrary of "subdirectory" that I don't know.

                          The unknown folder "subdirectory" shall be empty primarily but later on there may be some files there but we have to extract this directory variable assuming that there is no file there in it. This is the directory that shall be renamed repeatedly after extracting as a variable.

                          Thanks,

                          • That's not it actually. May be I was unable to pin point the problem in my question.

                            I quoted the whole directory path

                            /home/user/public_html/directory/subdirectory/

                            for convenience of readers.

                            In fact, my question was how to get or define an empty directory as a variable when I only know the possible existence of a down most directory but I don't know it's name.

                            For example, in the path

                            /home/user/public_html/directory/subdirectory/

                            I'm only aware about

                            /home/user/public_html/directory/-->a  sub-directory is here but I don't know the name<--/

                            but actually there is a sub-directory there named "subdirectory" in the above path which is ever changing.

                            How shall I define the down most directory "subdirectory" as a variable either using basename or dirname or any other suitable function in this case?

                            Thanks,

                            • For example,

                              I have an empty directory named "subdirectory" path of which is as following:

                              Path:
                              
                              /home/user/public_html/directory/subdirectory/

                              How shall I get or define "subdirectory" as a variable as I shall be renaming it with a database value in the following example.

                              $existing = "subdirectory"; // This is what I want capture from the above path and define as a variable
                              $new = "database_value";
                              $renamed = rename($existing, $new);
                              • polarexpress;11041333 wrote:
                                <form id="uploadform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
                                <input type="text" name="predefined_value" value="<?php echo isset($_POST['predefined_value']);?>" size="5" />
                                <input name="upload_file[]" type="file" class="upload_file" size="50" />
                                <input type="submit" value="Upload" id="submit" />
                                </form>

                                Readers, the above HTML part of my question should be read as

                                <form id="uploadform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
                                <input type="text" name="predefined_value" value="<?php echo isset($_POST['predefined_value']);?>" size="5" />
                                <input name="file_upload[]" type="file" class="file_upload" size="50" />
                                <input type="submit" value="Upload" id="submit" />
                                </form>

                                Sorry for unwilling mistake.

                                • I had to get the desired value through text input field before I posted it to a directory via a variable

                                  <input type="text" name="predefined_value" value="<?php echo isset($_GET['predefined_value']);?>" size="5" /> 
                                  • I'm trying to create a predefined directory with mkdir();

                                    mkdir(); should create directory or folder as inserted in the text box. My code is as following:

                                    [ATTACH]5139[/ATTACH]

                                    if (isset($_FILES['file_upload']) && isset($_POST['predefined_value'])) {
                                    
                                    $dir = isset($_POST['predefined_value']) ;
                                    $directory = "site.com/$dir/";     
                                    
                                    if (!is_dir($directory)) mkdir($directory, 0777);  /// It always creates numeric directory "1" based on the variable $dir 
                                    
                                    $max_size = 1024;       
                                    
                                    $allowtype = array('bmp', 'gif', 'jpg', 'jpeg');
                                    
                                    $rezult = array();    
                                    
                                      for($f=0; $f<count($_FILES['file_upload']['name']); $f++) {
                                        $nume_f = $_FILES['file_upload']['name'][$f];    
                                    
                                    if (strlen($nume_f)>3) {
                                    
                                      $type = end(explode('.', strtolower($nume_f)));
                                      if (in_array($type, $allowtype)) {
                                    
                                        if ($_FILES['file_upload']['size'][$f]<=$max_size*1028) {
                                    
                                          if ($_FILES['file_upload']['error'][$f]==0) {
                                    
                                            $thefile = $directory . '/'. $nume_f;  
                                    
                                            if (!move_uploaded_file ($_FILES['file_upload']['tmp_name'][$f], $thefile)) {
                                              $result[$f] = 'The file '. $nume_f. 'Unable to copy, try again';
                                            }
                                            else {
                                    
                                              $result[$f] = ''.$nume_f.'';
                                            }
                                          }
                                        }
                                        else { $result[$f] = 'The file '. $nume_f. ' Unpermitted size, <i>'. $max_size. 'KB</i>'; }
                                      }
                                      else { $result[$f] = 'The file '. $nume_f. 'Invalid file type'; }
                                    }
                                      }
                                      $_SESSION['result'] = implode($result);
                                    
                                    header('Location: '.basename($_SERVER['PHP_SELF']).'?file=uploaded');
                                    }
                                    
                                    if (isset($_GET['file']) && isset($_SESSION['result'])) {
                                      echo 'Uploaded File: '. $_SESSION['result'];
                                      unset($_SESSION['result']);
                                    } else {
                                        echo "Select file to upload";
                                    }
                                    }
                                    
                                    <form id="uploadform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
                                    <input type="text" name="predefined_value" value="<?php echo isset($_POST['predefined_value']);?>" size="5" />
                                    <input name="upload_file[]" type="file" class="upload_file" size="50" />
                                    <input type="submit" value="Upload" id="submit" />
                                    </form>

                                    The problem is that mkdir(); always creates a numeric directory named "1" on form submit no matter whatever value I insert in the text field name="predefined_value"

                                    Are these the inappropriate from input name and value those causing the problem?

                                    What's going wrong here?

                                    fur.png
                                    • dalecosp;11041307 wrote:

                                      It does ... do we misunderstand your question?

                                      define('BASE_DIR',"/home/user/public_html/directory/$path/");

                                      Yes, double quote in the above code works fine.

                                      Though a directory is a part of url path, may be I could ask the question the other way like,

                                      "Extracting variable in url path"

                                      Anyway, the problem has been resolved finally with your assistance.

                                      Thanks,

                                      • I wish double quote could extract the variable in url path.

                                        Thanks,

                                        • How shall I define a base directory with predefined path variable?

                                          //Path variable
                                          $path = "sub-directory";

                                          If I define the directory in the following way

                                          define('BASE_DIR','/home/user/public_html/directory/$path/'); 

                                          It returns,

                                          string(8) "BASE_DIR" string(39) "/home/user/public_html/directory/$path/" 

                                          But it should return

                                          string(8) "BASE_DIR" string(47) "/home/user/public_html/directory/sub-directory/"

                                          When I echo or dump it.

                                          What's going wrong?