I'm writing some simple PHP to back up a microsite. In my controller, I have a quick security/sanity check
if(!preg_match('/^[a-z]$/i', $req)) { gohome(); }
I'd like to continue my the main code after this, but for aesthetics, I'd like to avoid putting the rest of it inside the else
block. What's the best way around this? I can think of setting up a fairly simple wrapper to handle authentication and security logic, but I feel like I just missed a really simple solution in my training.
You can use the die/exit function to end the script with (or without) an error.
If this is in a function, you can usually just return early.
You could
return gohome();
or
throw new Exception('Request may only contain letters');
Either will stop the execution of that particular script at that point.
exit() is a pretty good way to terminate the current script...
if(!preg_match('/^[a-z]$/i', $req)) { gohome(); exit() }
I prefer to keep exit()/die() calls in the main flow. Or as Phil suggests, throw an Exception and exit() somewhere lower in the stack
Try the following.
preg_match('/^[a-z]$/i', $req) or die("exit message here, if you'd like");
It's no better functionally than Xavier's but I just like the syntax/idea of "do this or DIE" :) Also kind of makes me think of those old Nintendo games Skate Or Die and Ski Or Die.
You can quite simply just write;
return;
The command will return program control to the calling script, so;
null
if not.exit
or die
for that) unless there is no calling script.So in your case;
if(!preg_match('/^[a-z]$/i', $req))
{
gohome();
return;
}
and the else block is not required since it will only continue the script if the condition returns false.