RPeraltaJr
10/10/2019 - 2:55 PM

File Uploads with validations

This snippet was used in a WordPress theme.

<?php 

if (file_exists($_FILES["resume"]["tmp_name"]) || is_uploaded_file($_FILES["resume"]["tmp_name"])):

  // * Check filesize < 2MB
  // documentation: http://www.cheatsheeting.com/show.html?sheet=mb-to-b-conversions
  if ($_FILES["resume"]["size"] > 2097152):
      $response->error = true;
      $response->messages[] = "Resume needs to be less than 2MB.";
  endif;
  
  // * Check file extension(s)
  $allowedExts = array("doc", "docx", "pdf");
  $temp = explode(".", $_FILES["resume"]["name"]);
  $extension = end($temp);
  if (!in_array($extension, $allowedExts)):
      $response->error = true;
      $response->messages[] = "Resume - extension - " . filter_var($_FILES["resume"]["name"], FILTER_SANITIZE_STRING);
  endif;

  // * Check filetype
  if ($_FILES["resume"]["type"] != "application/pdf" &&
  $_FILES["resume"]["type"] != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" &&
  $_FILES["resume"]["type"] != "application/msword"):
      $response->error = true;
      // $response->messages[] = "Resume - filetype - " . filter_var($_FILES["resume"]["type"], FILTER_SANITIZE_STRING);
  endif;

  // * File Renaming
  $timestamp = date('Y-m-d');
  $random = mt_rand();
  $filename = "{$timestamp}-{$random}_{$first_name}-{$last_name}_Resume.{$extension}";

  // * Rename Files with allowed File extension(s)
  // Prevents users from uploading double filetypes
  if (strpos($filename, ".docx") !== false):
      $filename = "{$timestamp}-{$random}_{$first_name}-{$last_name}_Resume.docx"; // rebuild file
  elseif (strpos($filename, ".doc") !== false):
      $filename = "{$timestamp}-{$random}_{$first_name}-{$last_name}_Resume.doc"; // rebuild file
  elseif (strpos($filename, ".pdf") !== false):
      $filename = "{$timestamp}-{$random}_{$first_name}-{$last_name}_Resume.pdf"; // rebuild file
  else:
      $response->error = true;
      $response->messages[] = "Invalid file type.";
  endif; 

  // * Create new directory if it doesn't exist
  $new_dir_path = __DIR__ . '/../../../../_resumes';
  if(!file_exists($new_dir_path)):
      mkdir($new_dir_path, 0777, true);
  endif;

  if($response->error != true):
      // * Upload file to directory
      $tmp_name = $_FILES["resume"]["tmp_name"];
      move_uploaded_file($tmp_name, "$new_dir_path/$filename");
      $table_data["resume"] = home_url() . '/_resumes/' . basename($filename);
  else: 
      $response->error = true;
      $response->messages[] = "Oops! There was an error uploading your file.";
  endif;

endif;
<div class="form-group">
  <label class="resume-label" for="resume">Resume <small>(docx/pdf and &lt;2MB)</span>
  <input type="file" name="resume" id="resume" accept="application/pdf, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document">
</div>