We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 23050
    • 1,842 Posts
    @toshchris : when using this formit call :

    [[!FormIt? 
         &hooks=`spam,formit2file,formit2resource,email,redirect`
         &emailSubject=`Nouvelle inscription Annonceurs`
         &emailTpl=`formItInscriptionAnnonceur`
         &emailTo=`[email protected]`
         &redirectTo=`17`
         &customValidators=`isSiret,isMore800,isCP`
         &validate=`pagetitle:required,
                    societe_siret:required:isSiret,
                    content:required::stripTags:isMore800,
                    societe_adresse1:required,
                    societe_cp:isCP,
                    societe_ville:required,
                    societe_tel:required,
                    societe_email:required:email,
                    societe_logo:required`
    ]]


    with this formit2file hook :

    <?php
    // initialize output;
    $output = true;
     
    // valid extensions
    $ext_array = array('jpg', 'jpeg', 'gif', 'png');
     
    // create unique path for this form submission
    //$uploadpath = 'assets/img-annonceurs/';
     
    // 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/img-annonceurs/'.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)) {
         
                // clean up file name and make unique
                $filename = mb_strtolower($filename); // to lowercase
                $filename = str_replace(' ', '_', $filename); // spaces to underscores
                //$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
                 
                // 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);
                 
                // 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)
                    $modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
                    // 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;


    formit2resources is running, but email and redirect are not. If placing formit2file at the end of &hooks, it runs fine ... except that if the file is not uploaded or has wrong extension, the resource is still created and I stille receive the mail.

    So, I think the problem comes from how formit deals with formit2file... I tried to compare with other hook but no chance :/
      • 23050
      • 1,842 Posts
      I noticed the same error as ToshChris in the error log : File Error: Could not open file

      In core/components/formit/model/formit/fomit.class.php the way to handle files in email is :

              /* handle file fields */
              foreach ($origFields as $k => $v) {
                  $attachmentIndex = 0;
                  if (is_array($v) && !empty($v['tmp_name']) && isset($v['error']) && $v['error'] == UPLOAD_ERR_OK) {
                      if (empty($v['name'])) {
                          $v['name'] = 'attachment'.$attachmentIndex;
                      }
                      $this->modx->mail->mailer->AddAttachment($v['tmp_name'],$v['name'],'base64',!empty($v['type']) ? $v['type'] : 'application/octet-stream');
                      $attachmentIndex++;
                  }
              }


      Any reason why the files are handling differently if we use formit2file or not ? Maybe after the file is uploaded on server, the tmp is deleted by formit2file ? and then the email can't handle it ??

      Just suggestions sorry, I don't write PHP sad
        • 23050
        • 1,842 Posts
        Me again laugh

        In formit2file, there is :

        if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {


        Does this code move the file from /tmp/ to $myTarget ? If so, that could explain why email can't send files in /tmp/ it doesn't exist anymore ?

        How to get the new path to file and send it to email hook ?
          • 36625
          • 2 Posts
          Managed to get my previous problem working, without errors. All I changed was to declare the
          $filename = basename( $_FILES[$sf]['name'] );

          BEFORE the
          foreach ($submittedfiles as $sf) {
          ...
          }
          

          So, in full:
          <?php
          $output = true; // initialize output;
          $ext_array = array('JPG', 'jpg', 'JPEG', 'jpeg', 'gif', 'GIF', 'PNG', 'png'); // valid extensions
          $uploadpath = 'assets/uploads/MYDIIR/'.date('Y-m-d').'/'; // create unique path for this form submission
           
          $target_path = $modx->config['base_path'] . $uploadpath; // get full path to unique folder
           
          $submittedfiles = array_keys($_FILES); // get uploaded file names:
               // Get Filename and make sure its good.
              $filename = basename( $_FILES[$sf]['name'] );
          foreach ($submittedfiles as $sf) { // loop through files
           
              // 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)) {
               
                      // clean up file name and make unique
                      $filename = mb_strtolower($filename); // to lowercase
                      $filename = str_replace(' ', '_', $filename); // spaces to underscores
                      $filename = date("G:i:s_") . $filename; // add date & time
                       
                      // 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);
                       
                      // 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)
                          //$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
                          $modx->setPlaceholder('target', $myTarget);
                          // 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;

          Everything works fine when using the following hook call:
          &hooks=`math,spam,formit2file,email,redirect`

          Only issue I am left with is outputting the file path onto the email using [[+target]] placeholder tag. I have not had to use $modx->setPlaceholder yet so I'm a bit lost. I have tried several ways to do this, all with no luck.
            • 4172
            • 5,888 Posts
            try

            $hook->setValue('target',$myTarget);
              -------------------------------

              you can buy me a beer, if you like MIGX

              http://webcmsolutions.de/migx.html

              Thanks!
              • 19153
              • 53 Posts
              Hi guys

              I see that this is solved and working, however would somebody be able to take the time to repost the complete working solution? It's rather hard for non developer types like me to follow every slight change of code! I currently have formit2resource working but nothing is happening with formit2file

              I have seen other versions of formit2file in the forum, is this the latest version? What is a complete solution both with formit2file and formit2resource for creating a user form uploaded to a resource with a file (image?) Do i need to modify my original formit snippet?

              Also if someone could add this to the rtfm it would help a lot of people like me! Thanks for taking time to get this code working
                • 23050
                • 1,842 Posts
                Hello messyp,

                I've not been working on this for a long time. Here is the code I use :

                <?php
                // initialize output;
                $output = true;
                 
                // valid extensions
                $ext_array = array('jpg', 'jpeg', 'gif', 'png');
                 
                // create unique path for this form submission
                //$uploadpath = 'assets/img-annonceurs/';
                 
                // 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/img-annonceurs/'.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)) {
                     
                            // clean up file name and make unique
                            $filename = mb_strtolower($filename); // to lowercase
                            $filename = str_replace(' ', '_', $filename); // spaces to underscores
                            //$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
                             
                            // full path to new file
                            $myTarget = $target_path . $filename;
                             
                            // create directory to move file into if it doesn't exist
                            if(!is_dir($target_path)) {
                				mkdir($target_path, 0755, true);
                				} else {
                				$modx->log(modX::LOG_LEVEL_ERROR, 'dossier existe' );	
                				}
                             
                            // 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)
                                $modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
                                // 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;


                I'm not a developer PHP and I've tried many solutions... I remember that formit2file doens't work with email hook butt it should work without email
                  • 19153
                  • 53 Posts
                  Thanks for this but stil no joy!

                  My form goes to the success page but i don't see any files or new folders in my ftp, formit2resource appears to be working perfectly though.....I also don't get any error messages

                  Here is my complete code if anybody point out any errors

                  Formit Call

                  [[!FormIt? &hooks=`formit2file,formit2resource,redirect` &preHooks=`resource2formit`
                  &resource2formitfields=`parent,pagetitle,content` &emailTpl=`myEmailChunk` &emailTo=`[email protected]`
                  &redirectTo=`11`
                  &validate=`parent:required,
                    pagetitle:required,
                    content:required:stripTags,
                    nomination_file:required,
                     
                  `]]
                   


                  Form

                  <h2>Resource Form</h2>
                  <p>[[+fi.error.error_message]]</p>
                  
                  
                  <form class="form" action="[[~[[*id]]]]" method="post">
                      <input name="nospam:blank" type="hidden" />
                      <input name="resource_id" type="hidden" value="[[+fi.id]]" />
                      <label for="parent">
                          Parent:
                          <span class="error">[[+fi.error.parent]]</span>
                      </label>
                  <select id="parent" name="parent:required" value="[[+fi.parent]]">
                     <option value="2" [[!+fi.color:FormItIsSelected=`2`]] >2</option>
                     <option value="15" [[!+fi.color:FormItIsSelected=`15`]] >15</option>
                     <option value="16" [[!+fi.color:FormItIsSelected=`16`]] >16</option>
                  </select>
                     <label for="pagetitle">
                          Pagetitle:
                          <span class="error">[[+fi.error.pagetitle]]</span>
                      </label>
                      <input id="pagetitle" name="pagetitle:required" type="text" value="[[+fi.pagetitle]]" />
                       
                      <label for="content">
                          Content:
                          <span class="error">[[+fi.error.content]]</span>
                      </label>
                      <textarea id="content" cols="55" rows="7" name="content:required:stripTags">[[+fi.content]]</textarea>
                  <br class="clear" />
                  
                  <div class="row clearfix">
                          <div class="label">Supplementary Files <span class="error">[[+fi.error.nomination_file]]</span></div> <!-- end of .label -->
                          <div class="input"><input id="nomination_file" name="nomination_file:required" type="file" value="[[+fi.nomination_file]]" maxlength="100000" /></div> <!-- end of .input -->
                      </div> <!-- end of .row -->
                  <div class="form-buttons">
                          <input type="submit" value="Create Resource" />
                      </div>
                  </form>


                  formit2file snippet

                  <?php
                  // initialize output;
                  $output = true;
                    
                  // 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)) {
                        
                              // clean up file name and make unique
                              $filename = mb_strtolower($filename); // to lowercase
                              $filename = str_replace(' ', '_', $filename); // spaces to underscores
                              //$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
                                
                              // full path to new file
                              $myTarget = $target_path . $filename;
                                
                              // create directory to move file into if it doesn't exist
                              if(!is_dir($target_path)) {
                                  mkdir($target_path, 0755, true);
                                  } else {
                                  $modx->log(modX::LOG_LEVEL_ERROR, 'dossier existe' );    
                                  }
                                
                              // 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)
                                  $modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
                                  // 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;
                    • 23050
                    • 1,842 Posts
                    You can use

                    $modx->log(modX::LOG_LEVEL_ERROR, 'your error' ); 


                    to test different parts of your code. The errors are logged in MODx manager

                    I used it here :
                    } else {
                                    $modx->log(modX::LOG_LEVEL_ERROR, 'dossier existe' );   
                                    }


                    With that you can check where the hook code fails smiley
                      • 19153
                      • 53 Posts
                      hmmm no errors appear to be coming through which is even more confusing sad