We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 8168
    • 1,118 Posts
    Hi, I am uploading a file as part of a Login register / updateprofile process and I want to add a random set of characters / numbers to the end of the users uploaded file... Is this possible? The preHook snippet I use to upload the file to a folder called "assets/temp/" and then save the filename to the "cvdoc" extended userfield is below.... Anyone know how to amend this code to add the random "gdfgerDCVe2342r3ew" (e.g. random set of characters/numbers) to the filename on upload and then rename the file and ensure the filename in the extended "cvdoc" field includes the added random string?

    $output = true;
        $fields = $hook->getValues();
        /* User's photo */
        if (!empty($fields['cvdoc'])) {
            // valid extensions
            $extArray = array('doc', 'docx', 'pdf');
            // create temporary path for this form submission
            $uploadPath = 'assets/uploads/temp/';
            $targetPath = $hook->modx->config['base_path'] . $uploadPath;
            // get uploaded file names:
            $submittedFiles = array_keys($_FILES);
            // loop through files
            foreach ($submittedFiles as $sf) {
                // Get Filename and make sure its good.
                $filename = basename($_FILES[$sf]['name']);
                // Get file's extension
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                
                // case insensitive
                $ext = mb_strtolower($ext);
                
                // is the file name empty (no file uploaded)
                if ($filename != '') {
                    // is this the right type of file?
                    if (in_array($ext, $extArray)) {
                        //create file called the user name
                        $filename = mb_strtolower($filename);
                        // full path to new file
                        $uploadFilePath = $targetPath . $filename;
                        // create directory to move file into if it doesn't exist
                        @mkdir($targetPath, 0755, true);
                        if (file_exists($uploadFilePath)) {
                            // Change the file permissions if allowed
                            chmod($uploadFilePath, 0755);
                            // remove the file
                            unlink($uploadFilePath);
                        }
                        // is the file moved to the proper folder successfully?
                        if (move_uploaded_file($_FILES[$sf]['tmp_name'], $uploadFilePath)) {
                            $hook->setValue($sf, $uploadPath . $filename);
                            if (!chmod($uploadFilePath, 0644)) {
                                /* some debug function */
                            }
                        } else {
                            
                            // File not uploaded
                            $errorMsg = 'There was a problem uploading the file.';
                            $hook->addError($sf, $errorMsg);
                            
                            // generate submission error
                            $output = false; 
                        }
                    } else {
                        
                        // File type not allowed
                        $errorMsg = 'Type of file not allowed.';
                        $hook->addError($sf, $errorMsg);
                        
                        // generate submission error
                        $output = false;
                    }
                } else {
                    
                    // if no file, don't give error, but just return blank
                    $hook->setValue($sf, '');
                }
            }
        }
        return $output;
    


    Many thanks guys!

    dubbs

    This question has been answered by BobRay. See the first response.

      • 3749
      • 24,544 Posts
      You can get a unique number with time(), though there's a very slight chance that two files could be uploaded in the same second if the server is very fast. A guaranteed unique string can be generated by uniqid();

      $uniqueName = $filename . '-' . time() would also be pretty safe, as would $uniqueName = $filename . '-' . str_replace(' ', '-', strftime('%c'));

      The last one would add the date and time the file was uploaded to the filename. See this for other formatting options.
        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting
        • 8168
        • 1,118 Posts
        Quote from: BobRay at Sep 24, 2015, 04:06 AM
        You can get a unique number with time(), though there's a very slight chance that two files could be uploaded in the same second if the server is very fast. A guaranteed unique string can be generated by uniqid();

        $uniqueName = $filename . '-' . time() would also be pretty safe, as would $uniqueName = $filename . '-' . str_replace(' ', '-', strftime('%c'));

        The last one would add the date and time the file was uploaded to the filename. See this for other formatting options.

        Thanks Bob - and where in the code should I add this?
          • 3749
          • 24,544 Posts
          Here:

          foreach ($submittedFiles as $sf) {
              // Get Filename and make sure its good.
              $filename = basename($_FILES[$sf]['name']);
              $filename = $filename . ...;
            Did I help you? Buy me a beer
            Get my Book: MODX:The Official Guide
            MODX info for everyone: http://bobsguides.com/modx.html
            My MODX Extras
            Bob's Guides is now hosted at A2 MODX Hosting
          • Line 27, where you define the filename, add the random part to the filename. You can generate your random string by whatever method you like anywhere before that. I'd do it on line 26, so it's only done if the conditionals are met, and not just wasting time.
            $filename = mb_strtolower($filename).$randomstring;
              Studying MODX in the desert - http://sottwell.com
              Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
              Join the Slack Community - http://modx.org
              • 8168
              • 1,118 Posts
              Quote from: sottwell at Sep 24, 2015, 04:49 PM
              Line 27, where you define the filename, add the random part to the filename. You can generate your random string by whatever method you like anywhere before that. I'd do it on line 26, so it's only done if the conditionals are met, and not just wasting time.
              $filename = mb_strtolower($filename).$randomstring;

              Thanks Susan...

              Just tried that - code example below... but its coming back with an error File Type not allowed... Am I adding the time string after the file suffix? e.g. making "example.pdf" become "example.pdf122001" - in which case - the error is correct... How can I add the random time string to the end of the filename BEFORE the file suffix?

              Cheers

              // JWD
              $randomstring = time();
              $filename = mb_strtolower($filename).$randomstring;
              
              • discuss.answer
                • 3749
                • 24,544 Posts
                This should do it:

                if (strpos($filename, '.') === false) {
                   // no extension
                } else {
                    /* Get extension (including the dot) */
                    $ext = substr($filename, strrpos($filename, '.'));
                    /* remove extension */
                    $filename = str_replace($ext, '', $filename);
                
                    $randomstring = time();
                    $filename = mb_strtolower($filename).$randomstring . $ext;
                }
                


                This will work even if there are other dots in the filename.
                  Did I help you? Buy me a beer
                  Get my Book: MODX:The Official Guide
                  MODX info for everyone: http://bobsguides.com/modx.html
                  My MODX Extras
                  Bob's Guides is now hosted at A2 MODX Hosting
                  • 8168
                  • 1,118 Posts
                  Quote from: BobRay at Sep 24, 2015, 05:40 PM
                  This should do it:

                  if (strpos($filename, '.') === false) {
                     // no extension
                  } else {
                      /* Get extension (including the dot) */
                      $ext = substr($filename, strrpos($filename, '.'));
                      /* remove extension */
                      $filename = str_replace($ext, '', $filename);
                  
                      $randomstring = time();
                      $filename = mb_strtolower($filename).$randomstring . $ext;
                  }
                  


                  This will work even if there are other dots in the filename.

                  YYYYYYEEEEEEEEEEEEEEEEEEEEESSSSSSSSSSSSSSSSSSSSSSSSSSSS !!!!! Thanks Bob/Susan! You have made my day! Many evenings trying to get this to work... wink
                  • Dumb. I forgot about the dot.
                      Studying MODX in the desert - http://sottwell.com
                      Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                      Join the Slack Community - http://modx.org