Home > Blockchain >  Function only when key is pressed?
Function only when key is pressed?

Time:09-26

<form method="post">
    <input type="submit" name="test" id="test" value="RUN" /><br/>
</form>
if(array_key_exists('test',$_POST)){
    execute();
    $test = NULL;
 }
 else {
    $test = NULL;
 }

I have a normal PHP script that executes a function every time the button is pressed. As I understood it, it just checks if the variable is not NULL and if the request already happened.

But that's why every time you reload the page the function is executed again. I already tried to set the variable back to NULL after the button click but it doesn't work.

CodePudding user response:

Oh that's actually very simple :). You see, once you click on the button, test in the $_POST array is set to the value of the button (RUN). When you reload the page, the input in $_POST remains the same. What you have to do is remove the test value once you execute it for the first time. Let me show you:

if(array_key_exists('test',$_POST)){
    execute();
    unset($_POST['test']);
}

The else statement and setting $test to NULL is not even needed here for what you're trying to achieve, however if you needed them for anything else, the whole point to keep it working is just to keep the first 2 lines in the if.

  • Related