I always do POST's check validation, sometime its get too messy and long. What is the best way to keep it shorter and tidy?
Example:
if (isset($_POST['albumName']) && trim($_POST['albumName']) != "" && isset($_POST['slugName']) && $_POST['slugName'] != "" && is_numeric($_POST['PhotoCatID'])) {
//All good
}
The standard Filter extension may have what you're looking for, filter_input
in particular:
$albumName = filter_input(INPUT_POST, 'albumName', FILTER_SANITIZE_STRIPPED);
$slugNamed = filter_input(INPUT_POST, 'slugName', FILTER_SANITIZE_STRIPPED);
$PhotoCatId = filter_input(INPUT_POST, 'PhotoCatId', FILTER_SANITIZE_NUMBER_INT);
(I personally ended up writing wrappers named filter_get
, filter_post
and filter_request
just to make the lines a bit shorter...)
If you are looking to cut down your duplicate code and improve your logic, look into creating a validation class, will allow you to centralise all the validation logic.
Lots of resources on validation classes:
Also you have PHP built-in FILTER extension, which allows you to both sanitize and validate data.
First. Write vertically, not horizontally.
If you have several statements, write it one under another, not in one enormous line
Next, some validations can be be applied in a loop:
foreach ($_POST as $key => $value) $_POST[$key] = trim($value);
Next, some statements can be shortened.
$err=array();
if (empty($_POST['albumName'])) $err[]= "Album name is empty";
if (empty($_POST['slugName'])) $err[]= "Slug name is empty";
if (!is_numeric($_POST['PhotoCatID'])) $err[]= "Wrong parameters";
if(!$err) {
//All good
}
The rest is depends on your needs.
For IDs you can save yourself alot of trouble and just typecast them to int
$id = (int)$_POST['id'];
If the value is not valid, $id will be set to 0.