Terminating a script in a function

I’ve been dabbling in php for a couple of years now, but I only just latched onto the idea of using functions (what took me so long?). So I’m just learning how they behave.
What I want to know is, how do I stop the rest of the script running from within a function?
I did think that just putting exit(); at the end of the function would do that. But does that just exit the function and continue to run the rest of the script?
An example being, in a form processing/validation script, I distinguish between two types of errors, normal human errors, like not filling a required field, and security errors, like a bot/hacker/spammer is trying something suspicious, the script detects this and calls a function which displays an error message stops any further processing.

Hey Sam. Others may correct me if I’m wrong, but I think you should always exit from a function. In this case with a different return value, and test the return value in the main part of the script.

1 Like

It just occurred to me, don’t I just add the exit() line, just after the function in the script to end it? That’s simple enough.

In this case I don’t think I need any return, as I don’t want to do anything more after the function has run.
All it does is display a generic error message to the user. Gather a little info about what security issue has been detected and the user that triggered it, then Email that to me so I know what’s happening and by whom.
It then unsets some sessions to remove privileges, and modifies another to flag the user as suspicious.
After it’s done all that, I don’t want anything else to happen, the major purpose of the function is to stop the script from continuing any further because of the security alert.

There doesn’t seem to be any issue in using exit() from within a function - I’ve seen several examples where a script calls a function to handle errors as you describe, then terminates by redirecting to another page and then exiting. You have to do it somewhere, and it doesn’t make sense to force your function to return a specific value that you can check simply to move the exit() back into the calling code.

I think that exiting prematurely from a function is similar to the poor practise of using GOTO. Far better to test and return an appropriate value.

Doing some more testing, it seems like the exit in the function is terminating the script.
But I got the idea in my head that it only exits the function, last night while testing/de-bugging. There was some anomaly where because of an error (fixed now), I got flagged as a robot, but the form Email still arrived in my inbox, which should not happen if I’m flagged as a robot. But then I suppose I was de-bugging at the time and the script did have errors in it, which may explain this.
Anyway, as belt and braces, I left in the exits after the call to function, no harm in that I don’t think.

This is not my actual code, just a simplified example to illustrate.

function baderror($error) {
   echo "You're a dirty spam merchant. Get out!" ; // It don't really say that
   // Other bits that inform me about what happened
   exit(); // this should terminate the script... I think...

and the call to function

if($spam == true) { 
    baderror('spam') ;
    exit(); // just in case that exit in the function did not work
}

Can you explain? I don’t think I need any return, the function does everything I need it to do. The only thing I need to happen next is nothing.

I was taught to treat functions similar to Black Box Logic where the function accepts parameters, tests, performs actions and always returns with a value.

I would be tempted to use the function to display various messages depending on the parameters sent, for example, friend, business, spam and ultimately return either true or false if the messages have been sent.

Your main program should test the function’s result and exits or continues with the main program flow.

I do take your point about how a function should generally run. But I would maybe make specific exceptions, in a case such as this.
The purpose of this function is not to detect a security risk, the pieces of script that call the function do that job, and calling the function is the result of that process.
The purpose of the function is to handle the security risk that has been identified. The main action to do that is to cease the script from running any further, thus preventing any harm from a malicious user, and exit() performs that primary action. The other actions are secondary, gathering info about the nature of the error, gathering info about the user, then sending me that info. It also displays a generic (giving little away) error message to the user, which is most likely a bot anyway. You could look upon these secondary actions as being the returns of the function.
There is not any scenario where the function gets called and I want the script to keep running, it’s basically a big fat finger to the spam-bot to stop it in its tracks and say I’m not playing with you any more.
So exit is the primary action of the function, I could in fact just replace all the calls with exit and not have the function. But I’m nosey and want to know who is trying to spam my form and how often it happens.

Anyway, things seem to be working smoothly now.
Thanks everyone.

I guess if the intent is to stop the script from continuing any further, it could work.

It may be more an emotional thing with me, but an alias for “exit” is “die”
So its use seems more like a drastic nuclear option than something that should be used casually.

I have often seen it used at the beginning of script. eg.

<?php 
if (!$admin) {
  header("Location: login.php");
  exit;
}

I have also often seen it used in resource failure code eg.

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

Personally, it “feels” better to me to have functions return; rather than to die; and I prefer to use try{} catch{} when appropriate, but to each his own

1 Like

That would be the “correct” way of exiting from anywhere in the code when an exception occurs.

2 Likes

Sure that’s better for general error handling, and exit may not be appropriate for ordinary everyday functions. But when it comes to dealing with spam-bots, I’m quite comfortable with dishing out “drastic nuclear” death :smiling_imp:

The very thing that attracted me to functions was to DRY my code a bit. The form processor runs multiple checks to sniff out bots, if any are detected, the function is called. If I have a return, then start processing that after the function has run, I need to add that to every pair of brackets with the call, meaning repetitive script. Instad, I put everything I want to do when I find a bot in that one function, then drop the bomb on the script, before they do any harm.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.