How to Create a File Type Validation using PHP

Getting Started

I've used Bootstrap to beautify the presentation and is included in the downloadables of this tutorial but if you want, you can download it yourself using the this link.

Creating our Form

Next, we create our form which contains our file upload input field. Create a new file, name it as index.php and paste the codes below.
  1. <?php session_start(); ?>
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <title>How to Create a File Type Validation using PHP</title>
  7. <link rel="stylesheet" type="text/css" href="bootstrap4/css/bootstrap.min.css">
  8. </head>
  9. <body>
  10. <div class="container">
  11. <h1 class="text-center" style="margin-top:30px;">File Type Validation using PHP</h1>
  12. <hr>
  13. <div class="row justify-content-center">
  14. <div class="col-sm-4">
  15. <?php
  16. if(isset($_SESSION['error'])){
  17. echo "
  18. <div class='alert alert-danger text-center'>
  19. ".$_SESSION['error']."
  20. </div>
  21. ";
  22.  
  23. unset($_SESSION['error']);
  24. }
  25.  
  26. if(isset($_SESSION['success'])){
  27. echo "
  28. <div class='alert alert-success text-center'>
  29. ".$_SESSION['success']."
  30. </div>
  31. ";
  32.  
  33. unset($_SESSION['success']);
  34. }
  35.  
  36. ?>
  37. <div class="card">
  38. <div class="card-body">
  39. <form method="POST" action="validate.php" enctype="multipart/form-data">
  40. <input type="file" class="form-control-file" name="file" required><br>
  41. <button type="submit" class="btn btn-primary" name="validate">Validate</button>
  42. </form>
  43. </div>
  44. </div>
  45. </div>
  46. </div>
  47. </div>
  48. </body>
  49. </html>

Creating our Validation

Lastly, we create our validation if our form is submitted to check for the file/mime type of the uploaded file. Create a new file, name it as validate.php and paste the codes below.
  1. <?php
  2.  
  3. if(isset($_POST['validate'])){
  4. //set allowed types as array
  5. $allowed = array('jpg', 'png', 'jpeg');
  6.  
  7. //get uploaded file extension
  8. $file = $_FILES['file']['name'];
  9. $ext = pathinfo($file, PATHINFO_EXTENSION);
  10.  
  11. //check if extension is allowed
  12. if(in_array($ext, $allowed)){
  13. //action if type is allowed
  14. $_SESSION['success'] = 'File type allowed';
  15. }
  16. else{
  17. //action if type is not allowed
  18. $_SESSION['error'] = 'File type not allowed';
  19. }
  20. }
  21. else{
  22. $_SESSION['error'] = 'Upload a file to validate first';
  23. }
  24.  
  25. header('location: index.php');
  26.  
  27. ?>
That ends this tutorial. Happy Coding :)

Add new comment