We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 41583
    • 29 Posts
    Hi Guys,

    Here is a solution someone helped me with on stackoverflow.

    The Snippet

    <?php
    // initialize output;
    $output = true;
      // get the current user name to create the file name as  
    $userName = $modx->user->get('username');
     
    // valid extensions
    $ext_array = array('jpg', 'jpeg', 'gif', 'png');
     
    // create unique path for this form submission
    $uploadpath = 'assets/uploads/';
     
    // you can create some logic to automatically
    // generate some type of folder structure here.
    // the path that you specify will automatically
    // be created by the script if it doesn't already
    // exist.
     
    // EXAMPLE:
    // this would put all file uploads into a new,
    // unique folder every day.
    // $uploadpath = 'assets/'uploads/'.date('Y-m-d').'/';
     
    // get full path to unique folder
    $target_path = $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);
      $ext = mb_strtolower($ext); // case insensitive
     
      // is the file name empty (no file uploaded)
      if($filename != '') {
           
        // is this the right type of file?
        if(in_array($ext, $ext_array)) {
           
          //create file called the user name + pic
          $filename = $userName . "pic".'.'.$ext  ;
      
          // full path to new file
          $myTarget = $target_path . $filename;
           
          // create directory to move file into if it doesn't exist
          mkdir($target_path, 0755, true);
          if(file_exists($myTarget)) {
          chmod($myTarget,0755); //Change the file permissions if allowed
          unlink($myTarget); //remove the file
      }
           
          // is the file moved to the proper folder successfully?
          if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
            // set a new placeholder with the new full path (if you need it in subsequent hooks)
            $hook->setValue($sf, $uploadpath . $filename);
            // set the permissions on the file
            if (!chmod($myTarget, 0644)) { /*some debug function*/ }
             
              } else {
            // File not uploaded
            $errorMsg = 'There was a problem uploading the file.';
            $hook->addError($sf, $errorMsg);
            $output = false; // generate submission error
          }
           
          } else {
          // File type not allowed
              $errorMsg = 'Type of file not allowed.';
          $hook->addError($sf, $errorMsg);
          $output = false; // generate submission error
            }
       
      // if no file, don't error, but return blank
      } else {
          $hook->setValue($sf, '');
      }
     
    }
     
    return $output;


    In my Update Profile Resource


    [[!UpdateProfile? &useExtended=`1`  &postHooks=`redirect_profile_update` &preHooks=`user_profile_image`]]
      
    
      <div class="label"><img src="[[+nomination_file:phpthumbof=`w=120&h=120&zc=1&fltr[]=ric|20|20`]]" /></div> <span class="error">[[+fi.error.nomination_file]]</span>
            <div class="input"><input id="nomination_file" name="nomination_file" type="file" value="[[+fi.nomination_file]]" maxlength="100000" /></div>
       
    </div>
    • For a form to upload anything, you have to make sure it has the enctype attribute

      <form ... enctype="multipart/form-data">


      Does the registration form have this?
        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
        • 41583
        • 29 Posts
        Sorry all, here is the entire resource.

        [[!UpdateProfile? &useExtended=`1`  &postHooks=`redirect_profile_update` &preHooks=`user_profile_image`]]
          
        <div class="update-profile">
            <div class="updprof-error">[[+error.message]]</div>
            [[+login.update_success:if=`[[+login.update_success]]`:is=`1`:then=`[[%login.profile_updated? &namespace=`login` &topic=`updateprofile`]]`]]
          
            <form class="form" enctype="multipart/form-data" action="[[~[[*id]]]]" method="post">
                <input type="hidden" name="nospam:blank" value="" />
          
                <label for="fullname"><i class="icon-user"></i> <strong>[[!%login.fullname? &namespace=`login` &topic=`updateprofile`]]</strong>
                    <span class="error">[[+error.fullname]]</span>
                </label>
                <input type="text" name="fullname" id="fullname" value="[[+fullname]]" />
          
                <label for="email"><i class="icon-envelope"></i> <strong>[[!%login.email]]</strong>
                    <span class="error">[[+error.email]]</span>
                </label>
                <input type="text" name="email" id="email" value="[[+email]]" />
                
        
               <div class="row clearfix">
                <div class="label"><img src="[[+nomination_file:phpthumbof=`w=120&h=120&zc=1&fltr[]=ric|20|20`
        ]]" /></div> <span class="error">[[+fi.error.nomination_file]]</span>
                <div class="input"><input id="nomination_file" name="nomination_file" type="file" value="[[+fi.nomination_file]]" maxlength="100000" /></div>
            </div>
          
                <br class="clear" />
          
               <button class="btn-info btn btn-large" type="submit" name="login-updprof-btn">Update Profile</button>
            </form>
        </div>
          • 41583
          • 29 Posts
          The only problem is this.

          Whenever the user updates his/her profile and does not upload a picture the form blanks the extended field and the profile picture dissapears. Not sure how to get around this. Might remove it from the form and make it a separate page.
            • 42146
            • 73 Posts
            Thanks, i'll give that a try. sekusergalleries, has issues for me, and has way more going on than what i need. can trim it down if need be, but perhaps user galleries will be a upgrade feature.

            for your issue of form clearing. try something like this?
                <label for="sex">Gender
                  <span class="error">[[+error.sex]]</span>
                </label>
                <select name="sex">
                 <option value="Male" [[+sex::is=`Male`:then=`selected`]]>Male</option>
                 <option value="Female" [[+sex:is=`Female`:then=`selected`]]>Female</option>
               </select>


            how i got my fields to keep original values from being changed in option bozes, and check boxes
              • 42146
              • 73 Posts
              Since i'll have multiple images for people to update i dont want the file name always be usernamepic.ext plus to help with security and friendly urls i added this piece to help sanitize the img file name

              line 46 and 47
              //create file called the user name + pic
                    $filename = $userName . "pic".'.'.$ext  ;


              to

                    //create file called the filename that has been sanitized
                  $filename = strtolower(preg_replace("/[^a-z0-9\-]+/i", "-", $filename));
              
                    $filename = $filename . '.'.$ext  ;
                • 41583
                • 29 Posts
                In the snippet the following code seems to be responsible for removing the original file if none file is provided. Any ideas how one could change this to keep original instead of returning a blank.

                // if no file, don't error, but return blank
                  } else {
                      $hook->setValue($sf, '');
                  }
                  • 42146
                  • 73 Posts
                  Quote from: ankh2054 at Dec 18, 2012, 07:10 AM
                  In the snippet the following code seems to be responsible for removing the original file if none file is provided. Any ideas how one could change this to keep original instead of returning a blank.

                  // if no file, don't error, but return blank
                    } else {
                        $hook->setValue($sf, '');
                    }

                  doesn't work for me yet but i believe i'm on the right track, i get syntax errors currentl but change your above to something like

                   
                   // if no file, don't error, but return blank
                    } 
                          $fields = $profile->get('extended');  // no clue how to get and or check the users.profile.extended.value
                          $Profile_Photos = $fields['Profile_Photos'];
                          
                          if ($Profile_Photos != '' ) 
                          {
                            $hook->$Profile_Photos  //return the already have value for the photo field
                      }  else{
                            // if no file and no prior user value, don't error, but return blank
                        $hook->setValue($sf, '');
                  
                       }
                    }
                  }
                  return $output;
                  [ed. note: jstump last edited this post 11 years, 3 months ago.]
                    • 42146
                    • 73 Posts
                    Wow took long me enough trying to figure out how to get the user profile extended parmaters. i now know how to inject echos to the modx error log for debugging (not included below.... dont think it's quite perfect, in how i called the
                     if ($Photo_fields != '')
                    brains to fuzzy now.. may be a few {} missing o.... when i cleaned out the debugging, and documentate and format then things no longer worked.. so where is what was working with debugging info

                    will have to change file location dir... and profile photo placeholder to as needed

                    but here is the working code if a user doesn't input a image, and updates, that it doesn't reset the photo place holder to null.
                    does include file name sanitation.

                    <?php
                    // initialize output;
                    $output = true;
                      // get the current user name to for dicroty placement
                    $userName = $modx->user->get('username');
                    
                    // valid extensions
                    $ext_array = array('jpg', 'jpeg', 'gif', 'png');
                    
                    // create unique path for this form submission
                    $uploadpath = 'assets/userfiles/' . $userName .'/';
                    
                    // get full path to unique folder
                    $target_path = $modx->config['base_path'] . $uploadpath;
                    
                    // get uploaded file names:
                    $submittedfiles = array_keys($_FILES);
                    
                    //get exsisting user profile data for Profile_Photos
                    // ************************************
                    //$profile = $modx->user->Profile->get('extended');
                    // $profile = $profile->get('extended');
                    // $Photo_fields = $profile.[Profile_Photos];
                    
                    //
                    // $user = $modx->getObjectGraph('modUser',array('Profile' => array()),array('username'));
                    // $extFields = $user->Profile->get('extended');
                    // $Photo_fields = $extFields['Profile_Photos'];
                    $fields = $modx->user->getOne('Profile')->get('extended');
                    
                    $Photo_fields = $fields['Profile_Photos'];
                    
                        $modx->log(modX::LOG_LEVEL_ERROR,'what is the user profile photo -'.$fields['Profile_Photos']);
                        $modx->log(modX::LOG_LEVEL_ERROR,'linsting var is the user profile photo -'.$Photo_fields);
                    
                    // 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);
                      $ext = mb_strtolower($ext); // case insensitive
                      
                    
                      if ($Photo_fields != '')
                      {
                        $modx->log(modX::LOG_LEVEL_ERROR,'in the $Photo_fields != -'.$Photo_fields);
                     // is the file name empty (no file uploaded)
                        if($filename != '') {
                    $modx->log(modX::LOG_LEVEL_ERROR,'in file name loop'.$filename);
                                        // is this the right type of file?
                          if(in_array($ext, $ext_array)) {
                    
                                    //create file called the filename that has been sanitized
                            $modx->log(modX::LOG_LEVEL_ERROR,'before sanitization'.$filename);
                            $filename = strtolower(preg_replace("/[^A-Za-z0-9.]+/i", "-", $filename));
                            //$filename = $filename . '.'.$ext  ;
                            $modx->log(modX::LOG_LEVEL_ERROR,'after sanitization and.ext'.$filename);
                                          // full path to new file
                            $myTarget = $target_path . $filename;
                    
                                          // create directory to move file into if it doesn't exist
                            mkdir($target_path, 0755, true);
                            if(file_exists($myTarget)) {
                                          chmod($myTarget,0755); //Change the file permissions if allowed
                                          unlink($myTarget); //remove the file
                                        }
                    
                                          // is the file moved to the proper folder successfully?
                                        if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
                                            // set a new placeholder with the new full path (if you need it in subsequent hooks)
                                          $hook->setValue($sf, $uploadpath . $filename);
                                            // set the permissions on the file
                                        if (!chmod($myTarget, 0644)) { /*some debug function*/ }
                    
                                      } else {
                                            // File not uploaded
                                        $modx->log(modX::LOG_LEVEL_ERROR,'here was a problem uploading the file? -'.$Photo_fields);
                                        $errorMsg = 'There was a problem uploading the file.';
                                        $hook->addError($sf, $errorMsg);
                                            $output = false; // generate submission error
                                          }
                    
                                        } else {
                                          // File type not allowed
                                            $modx->log(modX::LOG_LEVEL_ERROR,'Type of file not allowed. -'.$Photo_fields);
                                          $errorMsg = 'Type of file not allowed.';
                                          $hook->addError($sf, $errorMsg);
                                        $output = false; // generate submission error
                                      }
                    
                                      // if no file, don't error, but return blank
                                    } else {
                                       $hook->setValue($sf, $Photo_fields);
                                
                                             $modx->log(modX::LOG_LEVEL_ERROR,'Photo field was populated and should not of changed.? -'.$Photo_fields);
                                    }
                     $hook->$Photo_fields;
                                             $modx->log(modX::LOG_LEVEL_ERROR,'Completed file upload-'.$filename);
                                  }else{
                    
                                                      $hook->setValue($sf, '');
                                    $modx->log(modX::LOG_LEVEL_ERROR,'at a last else hook should have a no known value for photofields -'.$Photo_fields);
                                  }
                                }
                    
                                return $output;
                    [ed. note: jstump last edited this post 11 years, 3 months ago.]
                      • 41583
                      • 29 Posts
                      Hi jstump, I am probably being a dummy here, but I cant it to work on mine. What does your <form> resource look like ?