I'm looking at a way of structuring if
clauses using the DRY principles of Don't 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?
You can use the ternary operator. The first expression will be used if it evaluates to true, otherwise the latter one. The
$_REQUEST
superglobal takes precedence in this case, like the code in the question:However as Havenard stated in a comment above, blindly trusting request data could be a security issue.
Also note that the condition will be true if any user IDs are
0
, in that case anull
check would be better:Of course this is assuming that you do not store falsy values in the
$_SESSION
as a non-null value.