First, we will create a folder /app/Common. In this directory, we will place a Utility.php file which is our custom class containing the required methods to clean user input. This utility sanitizes all input provided by the user.

/app/Common/Utility.php

<?php
namespace App\Common;

use Illuminate\Support\Facades\Input;

class Utility {

public static function stripXSS()
{
$sanitized = static::cleanArray(Input::get());
Input::merge($sanitized);
}

public static function cleanArray($array)
{
$result = array();
foreach ($array as $key => $value) {
$key = strip_tags($key);
if (is_array($value)) {
$result[$key] = static::cleanArray($value);
} else {
$result[$key] = trim(strip_tags($value)); // Remove trim() if you want to.
}
}
return $result;
}
}

Now we can use it in any of our controller actions where we are submitting a form and saving some data to our database. For example,

<?php

use App\Common\Utility;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SomeController extends Controller {
// some code...
protected function saveForm(Request $request) {

Utility::stripXSS(); //This will clean input
//rest of your validation code goes below...
}
}

Credits: This utility is based on work of usman.it. I just made it compatible with 5.2.



blog comments powered by Disqus

Share

Published

Tags