mardi 9 juin 2015

PHP: most efficient way of structuring IF clauses

I'm looking at a way of structuring If clauses using the DRY principles of Dont Repeat Yourself.

This is work involving scripts that are ~15 years old and poorly coded with globals etc., and I'm asked to drag this script/site into the 21st Century - but due to time and cost constraints, I can not facilitate a complete site rewrite from scratch, although I know that would be far better.

I have a value that is formerly a global value and I do not know where it comes from and it may come from different places from different pages.

I have some activity that is checking an input value in $_POST or $_GET data, if the input value is empty (or invalid), then check if the value is in fact sat in a $_SESSION. If the input value is still empty (or invalid) then boot to another page.

My code as it stands:

$userId = $_REQUEST['userid'];
if (empty($userId)) {
    $userId = $_SESSION['userid'];
    }
if(empty($userId) || !is_numeric($userId))
    {
    header("Location:contactdetails.php");
    die();
    }

I repeat the empty() function twice, I could wrap both IF's into one line but then would need an IF to pass the value from the REQUEST or the SESSION into the $userId variable.

Is there a (better) way that I can check the two possible inputs to see where this [formerly global] '['userid']' variable is coming from and applying that value to the page-local userId variable?

Aucun commentaire:

Enregistrer un commentaire