How to only call function once

In the code below. I have a function named notification(). While the condition is true I only what to call it once. I have set_time_limit(1) set to 1, but I continue to get multiple emails. The echo statement needs to keep working indefinitely, but the function should only be called once. How can I accomplish this?

<html>
<head>
<title>Switch</title>
</head>
<body>

<div style="text-align: center">
<?php

require '/usr/share/php/Mail.php';

function notification (){
$mail = new Mail();

$headers = array(
      'From' => 'noreply@localhost',
      'Subject' => 'Garage Door'
      
);

$auth = array(
      'auth'             =>  true,
      'host'             =>  'smtp.gmail.com',
      'username'         =>  'redacted+gmail.com',
      'password'         =>  'redacted'
      
);

$smtp = $mail->factory('smtp', $auth);
$smtp->send('redacted@txt.att.net', $headers, 'The garage door has been activated.');

}
?>

<?php

$switch = exec('/usr/local/bin/gpio read 1');

if ($switch == "1"){
            echo "<img src='garage-door-open.jpeg' width='497px' height='448px'/>";
            notification();
            set_time_limit(1);      
}
if ($switch == "0"){
            echo "<img src='garage-door-close.jpeg' width='497px' height='448px'/>";
      }

?>
</div>
</body>
</html> 

Open in new window


(Edited to use the code snippet for the code ~Ray)
(Edited to redact the code snippet ~Ray)
dynamicOneAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
Are you saying that you want to run this script over and over, but only fire the notification() function once?  If so, you can probably store the signal in the PHP session.
0
Ray PaseurCommented:
This is untested code.  See if it makes sense for your needs.  You will find that as long as the browser remains open and active, you should get only one notification.

<?php
error_reporting(E_ALL);

// START THE SESSION HERE, BEFORE ANY BROWSER OUTPUT
session_start();

?>
<html>
<head>
<title>Switch</title>
</head>
<body>

<div style="text-align: center">
<?php

require '/usr/share/php/Mail.php';

function notification()
{
    // ENSURE THAT THIS FUNCTION ONLY RUNS ONCE
    if (isset($_SESSION['switch'])) return FALSE;
    $_SESSION['switch'] = TRUE;
    
    $mail = new Mail();

    $headers = array(
      'From' => 'noreply@localhost',
      'Subject' => 'Garage Door'
      
    );

    $auth = array(
      'auth'             =>  true,
      'host'             =>  'smtp.gmail.com',
      'username'         =>  'REDACTED+gmail.com',
      'password'         =>  'pwd!'
      
    );

    $smtp = $mail->factory('smtp', $auth);
    $smtp->send('REDACTED@txt.att.net', $headers, 'The garage door has been activated.');
    return TRUE;
}

$switch = exec('/usr/local/bin/gpio read 1');

if ($switch == "1"){
    echo "<img src='garage-door-open.jpeg' width='497px' height='448px'/>";
    notification();
    set_time_limit(1);      
}
if ($switch == "0"){
    echo "<img src='garage-door-close.jpeg' width='497px' height='448px'/>";
}

?>
</div>
</body>
</html>

Open in new window

HTH, ~Ray
0
gr8gonzoConsultantCommented:
First, when you post questions, always remove sensitive info like phone numbers and passwords and username.

Now, I'm not sure I understand the concept you're going for.

1. set_time_limit() will only control how long the script has to finish executing. If the script doesn't finish all instructions in that requested time period (unless you specify 0, which means unlimited time), then the script aborts. Usually you would set this at the top of your script. It's used as a way to keep a script under control.

2. A PHP script is going to run top-down once. This means that EVERY time you run this script, you're going to get the results that the script produces, including the gpio read call, the email, and the echo. You said, "The echo statement needs to keep working indefinitely" but do you mean you want the echo to keep running each time you run the page, or do you want it to run multiple times within the page?

3. You said "the function should only be called once" (to send the email), but it should be only sent once unless you have other code that you haven't provided that re-runs this bit. If you're having trouble with multiple notifications being sent from one script call, then you can always set a global variable as a flag and then check it when you start the notification function:

function notification (){
global $alreadyNotified;
if(isset($alreadyNotified) && $alreadyNotified) return;
... rest of notification function code ...
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Slick812Commented:
greetings dynamicOne, , since you are using the Raspberry Pi linux gpio you may want to look into using the gpio PIN SETTINGS to set and retrieve some value (On-Off) for this, I would think that your best bet in PHP is to just write a file when the Email is sent, and test if the file exists, and if it does exist DO NOT send email, possibly something like this
<?php

$switch = exec('/usr/local/bin/gpio read 1');

if ($switch == "1"){
            echo "<img src='garage-door-open.jpeg' width='497px' height='448px'/>";
            $file = 'mailSent.txt';
            if (!file_exists($file)) {	
                file_put_contents($file, 'sent');
                notification();
                }
}
if ($switch == "0"){
            echo "<img src='garage-door-close.jpeg' width='497px' height='448px'/>";
      }

?>

Open in new window

as has already been said here, your  set_time_limit(1);     has no use whatsoever in this PHP working
you can just go in the PHP page directory and delete the  'mailSent.txt'  file to restart the Email sending

ask questions if you need more info
0
dynamicOneAuthor Commented:
Thank you everyone for your input. I have put in a request to the moderator to mark the question private or remove the sensitive information.

I am having trouble with multiple notifications being sent from one script call so I will try what was suggested.
0
Ray PaseurCommented:
...  multiple notifications being sent from one script call ...
That is puzzling to me because the script as written will only send one notification.  But it would potentially send one notification each time it was called.  Any chance there is something in the process that is calling it repeatedly?
0
Slick812Commented:
@dynamicOne  - if you can give information about the Lasting time-line for this end of notifications, if you use SESSION, then it will last just until you close the browser, (or some session time limit), if you write a file like I have suggested, this file will be there untill it is deleted, so it will always Stop notifications, even if you close browser or restart Linux-apatche -php.
0
dynamicOneAuthor Commented:
Ray, yes there is. I am using some jquery to reload the div that is echoing whether the door is open or closed. After I click the button, there is javascript that is appended to the url. If I  refresh the page to check the state of the door with the appended javascript in the url, it will trigger the door.
0
Ray PaseurCommented:
Hmm... You might try the session-related idea.  I'm not sure of what would happen in a repeated-call design, but it's an interesting question!
0
dynamicOneAuthor Commented:
That is what I need to figure out because it will only check the status of the pins when a page is loaded and constantly refreshing. I keep a page up in a browser on the Raspberry Pi so that is no big deal.

Right now I can have an email send to me whenever the app is used to open or close the door. I want to write the code in such a way that an email is generated each time the door is opened or closed.
0
dynamicOneAuthor Commented:
The more I think about this I think I am going to have run this directly on the Pi.
0
dynamicOneAuthor Commented:
Ray, quick question. The code you suggested, if I keep a page open in a browser on the Pi to keep the script running, will it send notification each time the conditional statement notices a change from 1 to 0 and vice-versa?
0
Ray PaseurCommented:
Here is that script, isolated so that it tests with "mock objects."  You can install it and run it to see the effect of repeated calls to the notification(), or just test it here on my server.
http://www.laprbass.com/RAY_temp_dynamicone.php

To understand what the PHP session is doing here, have a look at this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html
0
Slick812Commented:
@dynamicOne, you have taken what seems to me to be a round-about approach to doing what you so-far have told us, I say so-far, because you have now added important factors as -
"send notification each time the conditional statement notices a change from 1 to 0"
and that this page is refreshed on a timer basis as you say -"constantly refreshing"

you then say -"Right now I can have an email send to me whenever the app is used to open or close the door. I want to write the code in such a way that an email is generated each time the door is opened or closed.", , I can not get any meaning from this, but it sort of says that during all of the "constantly refreshing" page loads, you only want the email when the gpio generated $switch changes from it's binary value. I will tell you the programming Logic I would use for this, First to recognize a Change you will need to record the Value as 1 or 0,  alternately as true or false, some where, in session, or in file, or in a pin value of the gpio, as the Previous value, NOT the current value in the $switch, then you will need to retrieve or read the Previous value, and if NOT EQUAL to the current $switch value, then call the notification email. when the notification is sent CHANGE the recorded Previous value in session-file-gpio. .
But if there are More Factors that you have failed to mention, we can not read your mind.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.