title: PHP file upload with Ajax
body: <p>I am working on a form where we need to upload the file. The form is processing with Ajax and the data is being posted on the email with no problem except file upload.</p>
  
  <p>Now we want to allow user to upload multiple image files that will be stored on our server and we will get the link to the images in the email.</p>
  
  <p>Please have a look at the codes below:</p>
  
  <p><strong>Form HTML code:</strong>
      </p>
  
  <pre><code>    &lt;div class="col-sm-12"&gt;
        &lt;div class="well"&gt;
          &lt;form id="ajax-contact" action="http://websitename.com/mailer.php" method="post" enctype="multipart/form-data"&gt;
  
          &lt;h2&gt;Personal Details&lt;/h2&gt;
  
  
          &lt;div class="login-wrap"&gt;
  
            &lt;div class="form-group"&gt;
              &lt;label class="control-label" for="name"&gt;Name&lt;/label&gt;
              &lt;input name="name" placeholder="enter your name" id="name" class="form-control" type="text"&gt;
            &lt;/div&gt;
  
  
  
  
            &lt;div class="form-group"&gt;
              &lt;label class="control-label" for="tel"&gt;Telephone&lt;/label&gt;
              &lt;input name="tel" placeholder="enter your telephone" id="tel" class="form-control" type="text"&gt;
            &lt;/div&gt;
  
  
  
  
            &lt;div class="form-group"&gt;
              &lt;label class="control-label" for="email"&gt;Email&lt;/label&gt;
              &lt;input name="email" placeholder="enter your email" id="input-email" class="form-control" type="text"&gt;
            &lt;/div&gt;
  
  
  
  
            &lt;div class="form-group"&gt;
              &lt;label class="control-label" for="comments"&gt;Comments&lt;/label&gt;
              &lt;textarea name="comments" placeholder="your comments" id="comments" class="form-control" type="text"&gt;&lt;/textarea&gt;
            &lt;/div&gt;
  
  
         &lt;/div&gt;
  
  
  
          &lt;h2 style="margin-top:20px;"&gt;Product Details&lt;/h2&gt;
  
  
          &lt;div class="login-wrap"&gt;
  
            &lt;div class="form-group"&gt;
              &lt;label class="control-label" for="make"&gt;Make/Brand&lt;/label&gt;
              &lt;input name="make" placeholder="enter your make" id="make" class="form-control" required="" type="text"&gt;
            &lt;/div&gt;
  
  
  
  
            &lt;div class="form-group"&gt;
              &lt;label class="control-label" for="model"&gt;Model&lt;/label&gt;
              &lt;input name="model" placeholder="enter your model" id="model" class="form-control" required="" type="text"&gt;
            &lt;/div&gt;
  
  
  
  
            &lt;div class="form-group"&gt;
              &lt;label class="control-label" for="reference"&gt;Reference Number&lt;/label&gt;
              &lt;input name="reference" placeholder="enter your reference" id="reference" class="form-control" type="text"&gt;
            &lt;/div&gt;
  
  
  
            &lt;div class="form-group"&gt;
              &lt;label class="control-label" for="condition"&gt;Condition&lt;/label&gt;
                &lt;select id="condition" name="condition" required=""&gt;
                  &lt;option&gt;Mint&lt;/option&gt;
                  &lt;option&gt;Used&lt;/option&gt;
                &lt;/select&gt;
            &lt;/div&gt;
  
  
  
            &lt;div class="form-group"&gt;
              &lt;label for="images"&gt;Upload Images&lt;/label&gt;
              &lt;input id="images" name="images" multiple="" required="" type="file"&gt;
              &lt;p class="help-block"&gt;upload maximum 4 images&lt;/p&gt;
  
  
            &lt;/div&gt;
  
  
  
            &lt;div class="form-group"&gt;
              &lt;label class="control-label" for="price"&gt;Expected Price&lt;/label&gt;
              &lt;input name="price" placeholder="enter your price" id="price" class="form-control" required="" type="text"&gt;
            &lt;/div&gt;
  
  
  
            &lt;div class="checkbox"&gt;
              &lt;label&gt;
                &lt;input value="" type="checkbox"&gt;
                With Box
              &lt;/label&gt;
            &lt;/div&gt;
  
  
            &lt;div class="checkbox disabled"&gt;
              &lt;label&gt;
                &lt;input value="" type="checkbox"&gt;
                With Papers
              &lt;/label&gt;
            &lt;/div&gt;
  
  
  
         &lt;/div&gt;
  
  
  
          &lt;input value="Submit" class="btn btn-primary button" type="submit"&gt;
  
          &lt;/form&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  </code></pre>
  
  <p><strong>AJAX:</strong></p>
  
  <pre><code>$(function() {
  // Get the form.
  var form = $('#ajax-contact');
  
  // Get the messages div.
  var formMessages = $('#form-messages');
  
  // Set up an event listener for the contact form.
  $(form).submit(function(e) {
      // Stop the browser from submitting the form.
      e.preventDefault();
  
      // Serialize the form data.
      var formData = $(form).serialize();
  
      // Submit the form using AJAX.
      $.ajax({
          type: 'POST',
          url: $(form).attr('action'),
          data: formData
      })
      .done(function(response) {
          // Make sure that the formMessages div has the 'success' class.
          $(formMessages).removeClass('error');
          $(formMessages).addClass('success');
  
          // Set the message text.
          $(formMessages).text(response);
  
          // Clear the form.
          $('#name').val('');
          $('#email').val('');
          $('#message').val('');
          $('#tel').val('');
          $('#make').val('');
          $('#model').val('');
          $('#reference').val('');
          $('#condition').val('');
      })
      .fail(function(data) {
          // Make sure that the formMessages div has the 'error' class.
          $(formMessages).removeClass('success');
          $(formMessages).addClass('error');
  
          // Set the message text.
          if (data.responseText !== '') {
              $(formMessages).text(data.responseText);
          } else {
              $(formMessages).text('Oops! An error occured and your message could not be sent.');
          }
      });
  
  });
  
  });
  </code></pre>
  
  <p><strong>PHP Form Processor:</strong></p>
  
  <pre><code>&lt;?php
  
  // Only process POST reqeusts.
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
      // Get the form fields and remove whitespace.
      $name = strip_tags(trim($_POST["name"]));
              $name = str_replace(array("\r","\n"),array(" "," "),$name);
      $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
      $tel = filter_var(trim($_POST["tel"]));
      $message = trim($_POST["message"]);
      $make = trim($_POST["make"]);
      $model = trim($_POST["model"]);
      $reference = trim($_POST["reference"]);
      $condition = trim($_POST["condition"]);
  
      // Check that data was sent to the mailer.
      if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
          // Set a 400 (bad request) response code and exit.
          http_response_code(400);
          echo "Oops! There was a problem with your submission. Please complete the form and try again.";
          exit;
      }
  
      // Set the recipient email address.
      // FIXME: Update this to your desired email address.
      $recipient = "myemail@mycompany.com";
  
      // Set the email subject.
      $subject = "New Contact form Submitted";
  
      // Build the email content.
      $email_content = "Name: $name\n";
      $email_content .= "Tel: $tel\n";
      $email_content .= "Email: $email\n";
      $email_content .= "Message: $message\n";
      $email_content .= "Make/Brand: $make\n";
      $email_content .= "Model: $model\n";
      $email_content .= "Reference: $reference\n";
      $email_content .= "Condition: $condition\n";
  
      // Build the email headers.
      $email_headers = "From: $name &lt;$email&gt;";
  
      // Send the email.
      if (mail($recipient, $subject, $email_content, $email_headers)) {
          // Set a 200 (okay) response code.
          http_response_code(200);
          echo "Thank You! Your message has been sent.";
      } else {
          // Set a 500 (internal server error) response code.
          http_response_code(500);
          echo "Oops! Something went wrong and we couldn't send your message.";
      }
  
  } else {
      // Not a POST request, set a 403 (forbidden) response code.
      http_response_code(403);
      echo "There was a problem with your submission, please try again.";
  }
  
  ?&gt;
  </code></pre>