2

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
}
Your Common Sense
  • 154,967
  • 38
  • 205
  • 325
user622378
  • 2,288
  • 6
  • 39
  • 61

4 Answers4

3

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

Charles
  • 50,010
  • 13
  • 100
  • 141
1

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.

Stoosh
  • 2,398
  • 2
  • 17
  • 24
0

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.

Your Common Sense
  • 154,967
  • 38
  • 205
  • 325
0

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.

Geoffrey
  • 10,196
  • 3
  • 30
  • 44