PHP Data Validation

PHP Code Snippets Data Validation
Share:

About

In this code snippet, we’ll learn how to perform data validation in PHP.

Data validation is used to make sure the input data is present and in the correct format for further processing. This can be performed either on the front or backend.

Let’s see the example code below.

Code:

<?php

//Make sure the correct HTTP request method is used.
if($_SERVER['REQUEST_METHOD'] != "GET")
    die("Wrong HTTp method used!");

//Make sure parameter is present.
if(empty($_GET["userID"]))
    die("userID paremeter is missing!");

//Make sure the parameter isn't too long.
if(strlen($_GET["userID"]) > 10)
    die("Paremeter value too long!");
    
//Sanatize string. Depending on your needs you can use differnt filters: https://eecs.blog/php-string-sanitization/
$userID = filter_var($_GET["userID"], FILTER_SANITIZE_STRING);

//Display value.
echo $userID;

//Now the $userID can be used to get user info from the data base.
//Do DB stuff ...
Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger