How to filter variable in PHP?
Today, I am here with an interesting filter variable function in PHP.
This function can help us to validate and sanitize our form inputs or simple variables.
filter_var($variable, FILTER_TYPE, FILTER_OPTIONS)
This PHP function will return filtered data on the success or false on failure.
To filter the variable in PHP, we can use filter function with following filter types,
FILTER_SANITIZE_STRING FILTER_FLAG_STRIP_HIGH FILTER_FLAG_STRIP_LOW FILTER_VALIDATE_INT FILTER_SANITIZE_EMAIL FILTER_VALIDATE_EMAIL FILTER_SANITIZE_URL FILTER_VALIDATE_URL FILTER_VALIDATE_IP
Let’s understand this function with the help of a demo project.
How’s it sound?
You will get the source code of this project from my Github repository, link given at the end of the post.
Best age calculator with PHP OOPs
Let’s get started,
We will create two files in layout.
The header file is just to add CSS and required js. This is good practice to create separate layout files, it will help while working on a big project or multiple pages with the same header and footer.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Add page icon --> <link rel="icon" href="assets/icon/sb.png" type="image/png" sizes="16x16" /> <title>Filter variable with php</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <!-- Latest compiled and minified JavaScript --> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Add external css --> <link rel="stylesheet" href="assets/css/theme.css" /> </head> <body>
Usually, we can trigger any js plugin here but for now, we don’t have any.
</body> </html>
<?php include_once('layout/header.php'); include_once('validator.php'); $validator = new Validator(); if($_POST) { $validator->SetForm($_POST); $validator->Validate(); } $status_icon['success'] = '<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>'; $status_icon['error'] = '<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>'; $status_icon[''] = ''; ?> <ol class="breadcrumb"> <li><a href="https://sbsharma.com">Home</a></li> <li><a href="https://sbsharma.com/php">PHP</a></li> <li class="active">Filter var with php</li> </ol> <div class="container"> <div class="page-header"> <h1>Filter variable with php</h1> </div> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="panel panel-default theme-color mt-1"> <!-- Default panel contents --> <div class="panel-heading theme-color text-center"> filter_var($variable, $filter_type, $options?) </div> <div class="panel-body"> <div class="alert alert-info alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>Info!</strong> Sanitize string only remove html tags e.g. <p> example </p> = example </div> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <div class="form-group has-<?= $validator->var['string']['status'] ?> has-feedback"> <label class="control-label" for="str_input">String</label> <input <?= $validator->var['string']['focus'] ?> name="string" value="<?= $validator->var['string']['value'] ?>" type="text" class="form-control" id="str_input" placeholder="abcd"> <?= $status_icon[$validator->var['string']['status']] ?> </div> <div class="form-group has-<?= $validator->var['integer']['status'] ?> has-feedback"> <label class="control-label" for="int_input">Integer</label> <input <?= $validator->var['integer']['focus'] ?> name="integer" value="<?= $validator->var['integer']['value'] ?>" type="text" class="form-control" id="int_input" placeholder="123456789"> <?= $status_icon[$validator->var['integer']['status']] ?> </div> <div class="form-group has-<?= $validator->var['email']['status'] ?> has-feedback"> <label class="control-label" for="email_input">Email address</label> <input <?= $validator->var['email']['focus'] ?> name="email" value="<?= $validator->var['email']['value'] ?>" type="email" class="form-control" id="email_input" placeholder="example@xyz.com"> <?= $status_icon[$validator->var['email']['status']] ?> </div> <div class="form-group has-<?= $validator->var['url']['status'] ?> has-feedback"> <label class="control-label" for="url_input">URL</label> <input <?= $validator->var['url']['focus'] ?> name="url" value="<?= $validator->var['url']['value'] ?>" type="text" class="form-control" id="url_input" placeholder="https://example.com"> <?= $status_icon[$validator->var['url']['status']] ?> </div> <div class="form-group has-<?= $validator->var['ip']['status'] ?> has-feedback"> <label class="control-label" for="ip_input">IP Address</label> <input <?= $validator->var['ip']['focus'] ?> name="ip" value="<?= $validator->var['ip']['value'] ?>" type="text" class="form-control" id="ip_input" placeholder="127.0.0.1"> <?= $status_icon[$validator->var['ip']['status']] ?> </div> <button type="submit" class="btn btn-dark">Submit</button> </form> </div> <div class="panel-footer theme-color text-center">Powered by <a class="link-color" href="https://sbsharma.com" target="_blank">www.sbsharma.com</a> </div> </div> </div> </div> </div>
Validator class give us a nice validated or sanitized result.
<?php class Validator { public $form_data; public $var; public $form_controls; public function __construct() { $this->form_controls = ['string', 'integer', 'email', 'url', 'ip']; } public function Validate() { foreach($this->form_controls as $control) { $res = $this->rules($control); $this->var[$control] = [ 'status' => $res ? 'success' : 'error', 'value' => $res ? $res : null, 'focus' => $res ? '' : 'autofocus' ]; } } public function rules($input) { $result = false; if($this->form_data) { $result = filter_var($this->form_data[$input], $this->filter_type($input)); } return $result; } public function SetForm($data) { $this->form_data = $data; } protected function filter_type($input) { switch($input) { case 'string': return FILTER_SANITIZE_STRING; break; case 'integer': return FILTER_VALIDATE_INT; break; case 'email': return FILTER_VALIDATE_EMAIL; break; case 'url': return FILTER_VALIDATE_URL; break; case 'ip': return FILTER_VALIDATE_IP; break; default: return false; break; } } }
FILTER_SANITIZE_STRING
This filter used to remove all HTML tags from a string. To remove ASCII values greater than 127, we can use the following option.
FILTER_FLAG_STRIP_HIGH
To remove ASCII values lower than 32 use the below option.
FILTER_FLAG_STRIP_LOW
More details here https://www.php.net/manual/en/function.filter-var.php
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…