How to Sanitize Request Data Values in PHP?

This tutorial focuses on Data Sanitization in PHP. It is designed to serve as a comprehensive guide with practical examples for students and beginners looking to learn essential techniques for safeguarding data in PHP projects or web applications. Here, you will gain valuable insights and access a sample website that includes a feature for sanitizing request data values when submitting form data.

Why Sanitize Request Data Values?

In PHP and other programming languages, the purpose of sanitizing request data values, including `POST` and `GET` data, is to boost the security and reliability of web applications. Sanitization involves the process of validating and cleansing user inputs and other incoming data, such as form submissions, query parameters, or cookies, before utilizing them within the application or storing them in a database.

Here are several important reasons for sanitizing request data values:

  1. Enhanced Security: The process of sanitizing request data values in web applications is crucial in preventing security threats, including SQL Injection, Cross-Site Scripting (XSS), and Cross-Site Request Forgery (CSRF) attacks.
  2. Data Validation: Sanitizing request data values ensures that inputs conform to expected formats, such as URLs, email addresses, and more.
  3. Improved User Experience: Proper data sanitization contributes to a positive user experience by preventing errors and ensuring secure and accurate display of user-generated content.

These reasons highlight the advantages and benefits of implementing the sanitization process in web applications.

How to Sanitize Request Data Values in PHP?

Now, let's develop a basic web application that includes a Post Request Data Value Sanitization feature. This web application illustrates a straightforward implementation of sanitizing POST request data from a simple form submission. Before we begin, please make sure to download and install the following components if they are not already installed:

  • Web server package or software like XAMPP or WAMP
  • Code Editor such as Sublime Text, Microsoft Visual Studio Code, or Notepad++

Once you've installed the web server, ensure that you run or start the `Apache` or a similar service.

Creating the Request Data Sanitization Class

In your chosen Code Editor, start by creating a new `PHP` file and save it as `SanitizeRequestData.class.php`. This file houses a PHP class specifically crafted for sanitizing request data values using data filters. Please review the PHP script provided below:

  1. <?php
  2. class SanitizeRequestData{
  3.     private $filters;
  4.    
  5.     function __construct(){
  6.         $this->filters = [
  7.             "email" => FILTER_SANITIZE_EMAIL,
  8.             "addslashes" => FILTER_SANITIZE_ADD_SLASHES,
  9.             "float" => FILTER_SANITIZE_NUMBER_FLOAT,
  10.             "int" => FILTER_SANITIZE_NUMBER_INT,
  11.             "special_characters" => FILTER_SANITIZE_SPECIAL_CHARS,
  12.             "url" => FILTER_SANITIZE_URL
  13.         ];
  14.     }
  15.  
  16.     public function sanitize($value="", $filter= "special_characters"){
  17.         if($filter == 'float')
  18.             return filter_var($value, $this->filters[$filter], FILTER_FLAG_ALLOW_FRACTION);
  19.         else
  20.             return filter_var($value, $this->filters[$filter]);
  21.     }
  22.    
  23. }
  24. ?>

If you wish to utilize additional filters, you can explore various Sanitization and Validation filters at https://www.php.net/manual/en/filter.filters.php.

Creating the Simple Form Interface

Next, let's construct the user interface for the basic website, which includes a sample form. Begin by creating a new `PHP` file named `index.php`. This file also contains the script responsible for loading the class we created earlier and sanitizing the submitted data values.

  1. <?php
  2. if($_SERVER['REQUEST_METHOD'] == "POST"){
  3.     require_once("SanitizeRequestData.class.php");
  4.     $sanitizeRequestData = new SanitizeRequestData();
  5.  
  6.     /**
  7.         * Filter to use in Sanitizing the request data
  8.         * key => request data key
  9.         * value => sanitazation filter
  10.         */
  11.     $filter = [
  12.         "site_url" => "url",
  13.         "site_email" => "email",
  14.         "site_name" => "addslashes",
  15.         "sample_float" => "float",
  16.         "sample_int" => "int",
  17.         "sample_html" => "special_characters"
  18.     ];
  19.  
  20.     /**
  21.         * Sanitize POST Data
  22.         */
  23.     foreach($_POST as $key => $value){
  24.         $_POST[$key] = $sanitizeRequestData->sanitize($value, $filter[$key]);
  25.     }
  26.     $dataJSONpath = __DIR__."/request-data.json";
  27.     $save = file_put_contents($dataJSONpath, json_encode($_POST, JSON_PRETTY_PRINT));
  28. }
  29. ?>
  30. <!DOCTYPE html>
  31. <html lang="en">
  32. <head>
  33.     <meta charset="UTF-8">
  34.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  35.     <title>Sample Website Form</title>
  36.     <!-- Bootstrap 5.3 CSS-->
  37.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  38.     <!-- jQuery -->
  39.     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  40.     <!-- Bootstrap 5.3 JS-->
  41.     <script src="       https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  42. </head>
  43. <body>
  44.     <nav class="navbar navbar-expand-lg bg-body-tertiary">
  45.         <div class="container-fluid">
  46.             <a class="navbar-brand" href="#">Sample Form</a>
  47.             <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
  48.             <span class="navbar-toggler-icon"></span>
  49.             </button>
  50.             <div class="collapse navbar-collapse" id="navbarNav">
  51.             <ul class="navbar-nav">
  52.                 <li class="nav-item">
  53.                 <a class="nav-link <?= $page == 'home' ? "active" : '' ?>" href="./">Home</a>
  54.                 </li>
  55.             </ul>
  56.             </div>
  57.         </div>
  58.     </nav>
  59.     <div class="container-md py-4">
  60.         <div class="card rounded-0 mx-auto col-lg-5 col-md-7 col-sm-12 col-12">
  61.             <div class="card-header rounded-0">
  62.                 <h5 class="card-title">Sample Form</h5>
  63.             </div>
  64.             <div class="card-body rounded-0">
  65.                 <?php if(isset($_POST) && !empty($_POST)): ?>
  66.                     <div class="bg-dark text-light px-2 py-3">
  67.                         <?php
  68.                             foreach($_POST as $k => $v){
  69.                                 echo "{$k} = <code>".addslashes($v)."</code><br>";
  70.                             }
  71.                         ?>
  72.                     </div>
  73.                 <?php endif; ?>
  74.                 <form action="" id="sample-form" method="POST">
  75.                     <div class="container-fluid">
  76.                         <div class="mb-3">
  77.                             <label for="site_url" class="form-label">Site URL</label>
  78.                             <input type="text" id="site_url" name="site_url" class="form-control form-control-sm rounded-0" required="required">
  79.                         </div>
  80.                         <div class="mb-3">
  81.                             <label for="site_email" class="form-label">Site Email</label>
  82.                             <input type="text" id="site_email" name="site_email" class="form-control form-control-sm rounded-0" required="required">
  83.                         </div>
  84.                         <div class="mb-3">
  85.                             <label for="site_name" class="form-label">Site Name</label>
  86.                             <input type="text" id="site_name" name="site_name" class="form-control form-control-sm rounded-0" required="required">
  87.                         </div>
  88.                         <div class="mb-3">
  89.                             <label for="sample_float" class="form-label">Sample Float Field</label>
  90.                             <input type="text" id="sample_float" name="sample_float" class="form-control form-control-sm rounded-0" required="required">
  91.                         </div>
  92.                         <div class="mb-3">
  93.                             <label for="sample_int" class="form-label">Sample Integer Field</label>
  94.                             <input type="text" id="sample_int" name="sample_int" class="form-control form-control-sm rounded-0" required="required">
  95.                         </div>
  96.                         <div class="mb-3">
  97.                             <label for="sample_html" class="form-label">Sample HTML Field</label>
  98.                             <textarea rows="5" id="sample_html" name="sample_html" class="form-control form-control-sm rounded-0" required="required"></textarea>
  99.                         </div>
  100.                         <div class="d-flex justify-content-center align-items-center w-100">
  101.                             <div class="col-lg-4 col-md-6 col-sm-8 col-12">
  102.                                 <button class="btn btn-primary rounded-pills">Submit Data</button>
  103.                             </div>
  104.                         </div>
  105.                     </div>
  106.                 </form>
  107.             </div>
  108.         </div>
  109.     </div>
  110.    
  111. </body>
  112. </html>

After submitting the form, a container located above the form fields will become visible, showing the sanitized data submitted. Additionally, the script generates a new JSON file, which contains the raw sanitized data in JSON format. This file is named `request-data.json`.

Here are some images that depict the outcomes produced by the provided script:

Website UI

Sanitizing Request Data Values in PHP

Sample Filled Form

Sanitizing Request Data Values in PHP

Sanitized Data Result in Browser

Sanitizing Request Data Values in PHP

Unparsed Sanitized Data Result in JSON File

Sanitizing Request Data Values in PHP

And that's it! I hope that this `Sanitizing Request Data Values in PHP Tutorial` will be of great assistance to you in your current and future PHP projects. Feel free to explore our website for additional resources, including Free Source Code, Tutorials, and Articles covering a wide range of programming languages.

Happy Coding =)

Add new comment