Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Say I have made an ajax request to a php file. when the result is success or something other. I do not need my server to go through the rest of the code. So I was thinking to use exit function but having too many exits a good practise ? I am not sure.
if(some condition) exit("success");
else if(some condition) exit("fail");
// after some 3 lines or so
if(fail) exit("error");
Using too many exit functions in PHP is a good or bad practice. Could anyone tell me are there any restrictions on using exit function? I have been told that you cannot use too many return statements in a function and I was thinking may be even exit must not be used more frequently. Using too many exit functions a wrong way of doing things?
Update
When it has satisfied the given requirement, there is no need for further execution of code. I don't want my server to go down and meet the end I could simply exit. It makes faster I guess?
I prefer to have multiple exit messages, drawing a correlation between having multiple return statements in a method.
If you did not have multiple exit messages, I think your code would be kind of ugly:
$retCondition = "success";
if(!some condition) {
if(some condition 2) $retCondition = "fail";
else {
..Your code
}
}
exit($retCondition);
This is kind of a php solution, but you get the idea.
To me it is wrong practice. If possible one entry point and one exit point - it's irrelevant what language it is. I care my time and such approach simply help reading, maintaining and debugging code.
EDIT
To summary my point here (or follow the comments): this is not black/white case, so you never should be really 100% strict, but I tend to avoid early returns if I find this causing readability loss and this is a sufficient reason for me but also I sometimes agree to do the opposite if the code whould simply look like xmas tree with all nested if()/else blocks.
I prefer to use Exception and only use exit if redirecting using headers
try {
if (! $conditionA) {
throw new Exception(" Fail ConditionA");
}
if (! $conditionB) {
throw new Exception(" Fail ConditionB");
}
header("Location: xxx");
exit();
} catch (Exception $e) {
echo $e->getMessage();
}
Using exit is a bad practice. It should only be used if crucial code fails for example:
<?php defined('FOO') or exit('Foo not set');?>
<?php mysql_connect('usr','pwd','host') or exit('could not connect');?>
For normal circumstances for example the 'if' statement:
if (condition) {
echo 'Hello';
} else {
callSomeFunction();
}
Let's say you have a fooBar function:
function fooBar () {
if (condition) {
return 'Hello';
} else {
return FALSE; // If you use return the function 'fooBar' stops at that point
echo 'Hello?'; // This is not executed because we already returned.
}
}
Good luck
It doesn't cause any problem, but it's nice to have just one exit point. It may make debugging easier. You can do it this way:
if(some condition) $error_msg = "success";
else if(some condition) $error_msg = "fail";
// after some 3 lines or so
if(fail) $error_msg = "error";
if($error_msg != '') exit($error_msg);
If you are using a true object oriented style it should be structured similar to the following
function foo($x){
if (!is_int($x)) throw new Exception('foo needs an int argument');
return $x *2
}
Now there is only one return and when you call the method you use
$variable = 0;
try{
$variable = $this->foo(2.5);
}catch(Exception e){
print_r($e)
}
which allows you to see the problem and handle it in a controlled way.
it follows the flow chart way of having 1 "start" and 1 "end" but allows very verbose messages to be displayed etc
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a PHP switch statement that either grants access to a form or displays an error message based on the type of user and whether he/she has rights to it. The case I need help with looks like this:
case 2:
CheckStatus();
CheckRevokeFlag();
CheckNotifyFlag();
RecordLock();
include 'gotopage1.php';
break;
The function calls display messages based on the level of the user's access. My problem is that ONLY ONE message should ever display at a time, but sometimes more than one condition can be true. For example, if the user does not have rights to the form (CheckStatus) AND the form is also in use by someone else (RecordLock), then he gets both "access denied" and "record is locked." Is there a way to fix this so that the user only gets either the "access denied" message or the "record is locked" message, or should I use something other than a switch statement?
I'm going to take a shot in the dark here.
Let's say your functions are defined on this pattern:
function funcName() {
// do some stuff here
if( $error) echo $error;
}
Change it to this:
function funcName() {
// do some stuff here
if( $error) {
echo $error;
return false;
}
return true;
}
Now the function returns something, so we can do stuff with it. Change your switch case structure to:
case 2:
CheckStatus() or break;
CheckRevokeFlag() or break;
CheckNotifyFlag() or break;
RecordLock() or break;
include "gotopage1.php";
break;
So now, if each function returns true (ie has no error condition to report) then it will continue as normal. Otherwise, it will hit the or break and stop processing the remaining checks.
I was wondering if PHP has a function that allows me to end a process before it reaches the "?>" tag, example:
<?php
echo 'first';
endphptag();
echo 'second';
?>
third
<?php
echo 'fourth';
?>
Then the output should be:
first
third
fourth
I know that some people consider this as something useless, but I want to do it for a validation script on an iframe instead of use the die or exit function because it kills the whole script, I just want to end a part of it.
Normally I use if - else instead, but I want to avoid them because the processes are large and I want something more readable, by the way I use if - die in my ajax scripts and I want to use something like this in my iframes too, Thank's!
Well, I just wanted to know if PHP already had a proper function for it (it seems not), so I think I will just leave it with if - elses, because is not really worth to use more process for make it "more readable" (ex: try - catches uses too much resources, I'm not going to go-tos neither). My doubt was only for that, I will only use this procesdure in my ajax files using the die function (I don't know if it is recommended, but I think there's no problem because PHP should have it for some reason)
Exceptions is what you are looking for:
try {
// code
} catch (Exception $e) {
// handling
}
You put your code inside the try block and you end it throwing an exception with throw new Exception();, and it exits only the rest of the code inside the try block.
Your code would then be:
<?php
try {
echo 'first';
throw new Exception();
echo 'second';
} catch (Exception $e) {}
?>
third
<?php
echo 'fourth';
?>
I'm going to throw this out there and duck, but if you really need to do this, then goto is actually not a bad option:
<?php
echo 'first';
goto endofblock;
echo 'second';
endofblock:
?>
Or you could avoid the "evil" of goto with a faux-loop. To the compiler they basically look the same, but other programmers won't club you to death for using goto
<?php
do {
echo 'first';
break;
echo 'second';
} while (false)
?>
Why do you not use switches and cases?
http://php.net/manual/en/control-structures.switch.php
If I were you, I would omit the end-php tag. Most coding standards advise against it, for reasons that are too lengthy to explain here.
But that aside, go ahead and use the if/else or the switch/case control structures. Take the large parts of the validation process out of the inline code and package them in functions or class methods if you're using OOP.
See also this note about GOTO ;-) http://xkcd.com/292/
The PHP interpreter works with the file as a single unit, the <?php tag just specifies portions of text (outside the tag) to ignore, just like comments. The tag does not border any portion of code.
So in your case, I think the goto statement might be the right option. Or, if you could put the code into a function, you could use return.
Is it ok to include a break or exit command to prevent further code from executing or is this bad programming?
function index()
{
$error = NULL;
if ($_POST){
// validate form
if ($form_validated) {
echo 'this content only';
exit; // or return IS THIS BAD???
} else {
$error = 'form failed';
}
}
echo 'normal page on initial load';
if ($error) { echo '<br />'.$error; }
}
It is OK to prevent further code from executing using exit.
Having said that, whether this is the best way to do it in this particular example is debatable. It is typical to use exit when issuing redirects:
header('Location: /foo');
exit;
In your case, there doesn't seem to be an immediate need to stop the program execution in mid run. You should rather structure your program flow so it always completes, but with different results. It is hard to follow program logic which may terminate somewhere in the middle, so a more logical flow that returns from functions or branches using if..else is usually preferable.
For the example you give:
function index()
{
...
if ($form_validated) {
echo 'this content only';
exit; // or return IS THIS BAD???
} else {
...
}
This is normally called early exit or early return (return is more common). This can be very okay, some people say that early returns make code hard to understand but I'd say it depends on a lot more if a function can be easily read and understood or not.
So the person who decides here whether it is bad or not is you. You need to find some criteria on your own where you draw the line. For example if a function is long (more than 12 lines of code) and contains many of these early returns or even exits, this will make the code more complicated.
Generally early returns can make a functions code less complex which can heavily reduce the number of bugs.
So probably the complexity is a good criteria here.
Additionally I suggest you use exit very carefully. It does much at once and you should normally not need it within your program flow. Especially if you're writing business logic.
Is it a good or bad practice to authenticate and then just exit() the function or to wrap the whole result of the authentication in an if statement? Example
function foo($uid)
{
$allowed = $auth->checkIfAllowed($uid);
if ($allowed == false) exit();
//continue with senstive code here
}
}
OR
function foo($uid)
{
$allowed = $auth->checkIfAllowed($uid);
if ($allowed == true)
{
// do sensitive stuff
}
}
I would like to take this opportunity to talk about exit; (as others have stated both work, the second is more explicit then the first, and give you the opportunity to send a nice error message to the user). My main beef (I have several with exit;) is that people should stop using it in libraries, i.e. code that can/will be used in other projects... You know how irritating it is to debug those? Throw exceptions, trigger fatal errors, but give me something with a description.
/rant
Your examples are equivalent.
However, it's not usually useful to the end user to just exit the script abruptly. Instead, send your user a useful error message printed in HTML rather than the plain text you would get from a die() call, for example.
function foo($uid)
{
$allowed = $auth->checkIfAllowed($uid);
if ($allowed == false)
{
$errormsg = "You are not allowed to view this page";
}
else
{
//continue with senstive code here
}
}
Later, print the error in HTML, rather than just aborting the script:
<div class='error'><?php echo $errormsg; ?></error>
Either or. I don't think it'll make a difference. It relatively the exact same thing. In programming there are many ways to program things, never on right way in most instances.
They are absolutely the same. The indentation and coding style is the only difference. In both cases the sensitive code won't execute unless the authentication is done successfully.
It's usually better to be expressive in your code though, so I'd recommend the second method.
I need to do a PHP while loop, but only if a variable is true. And I can't really put the while loop in an "if" statement, which seems like the obvious thing to do, since the code block is huge and it would be ugly and confusing. Do I need to break out the code in the loop into a function, or is there an easier way to deal with this?
Here's the basic idea:
if(condition){
while(another_condition){
//huge block of code loops many times
}
} else {
// huge block of code runs once
}
I want the huge block of code to execute regardless of the state of the condition variable-- but only to execute once if condition is false, and execute for as long as another_condition is true if condition is true.
The following code doesn't work, but gives an idea of what I want to accomplish:
if(condition){ while(another_condition){ }
// huge block of code
if (condition){ } } // closes the while loop-- obviously throws an error though!
thanks in advance.
If I understood your problem correctly, you could use the do ... while() structure:
do
{
// your code
} while(condition);
This will execute // your code once regardless of any factor, and then only for the second iteration and those after will it check for the condition.
For readability if your huge block of code can be separated in several specialized functions, do it. It will surely pay out if you need to debug later.
I would put the huge block of code in a function so it can be used again without having duplicate code.
function hugeBlockOfCode() {
// Huge block of code.
}
while (condition && another_condition) {
hugeBlockOfCode();
}
if (!condition) {
// Run code once.
hugeBlockOfCode();
}
or
do {
hugeBlockOfCode();
} while (another_condition);
Is this kind of what you are looking for?
while (condition && another_condition) {
// large block of code
}
if (!condition) {
// do something else
}