How to Create a File Type Validation using PHP
Submitted by nurhodelta_17 on Thursday, April 26, 2018 - 23:09.
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.- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>How to Create a File Type Validation using PHP</title>
- <link rel="stylesheet" type="text/css" href="bootstrap4/css/bootstrap.min.css">
- </head>
- <body>
- <div class="container">
- <h1 class="text-center" style="margin-top:30px;">File Type Validation using PHP</h1>
- <hr>
- <div class="row justify-content-center">
- <div class="col-sm-4">
- <?php
- echo "
- <div class='alert alert-danger text-center'>
- ".$_SESSION['error']."
- </div>
- ";
- }
- echo "
- <div class='alert alert-success text-center'>
- ".$_SESSION['success']."
- </div>
- ";
- }
- ?>
- <div class="card">
- <div class="card-body">
- <form method="POST" action="validate.php" enctype="multipart/form-data">
- <input type="file" class="form-control-file" name="file" required><br>
- <button type="submit" class="btn btn-primary" name="validate">Validate</button>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </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.- <?php
- //set allowed types as array
- //get uploaded file extension
- $file = $_FILES['file']['name'];
- //check if extension is allowed
- //action if type is allowed
- $_SESSION['success'] = 'File type allowed';
- }
- else{
- //action if type is not allowed
- $_SESSION['error'] = 'File type not allowed';
- }
- }
- else{
- $_SESSION['error'] = 'Upload a file to validate first';
- }
- ?>
Add new comment
- 387 views