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.
<?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 ...