Zend certified PHP/Magento developer

Magento 1.9.4.3 – Run php scripts only once

I describe my situation:

I created a PHP script in the header.phtml file that allows customers to change the group based on their order total. I put this script inside an if and it works perfectly.

In addition to this function, I added the sending of a personalized email that informs the customer of the group change.

The problem is that this PHP code that saves the client group and sends the email executes it every time the page of the site is loaded. I can’t put this code online because otherwise the user will receive an email with a group change every time he loads a page.

This is a piece of the code I put in:

$localeCode = Mage::getStoreConfig('general/locale/code', Mage::app()->getStore()->getStoreId());
if($subTotal >= 1000){
    //CHANGE CUSTOMER GROUP
    $customer->setData('group_id',9);
    //SET DATE OF THE CUSTOMER GROUP CHANGE
    $customer->setdatagruppo(date('Y'));
    $customer->save();

    //SEND EMAIL FOR CUSTOMER GROUP
    $localeCode = Mage::getStoreConfig('general/locale/code', Mage::app()->getStore()->getStoreId());
    $emailTemplate = Mage::getModel('core/email_template')->loadDefault('customer_status_template',$localeCode);
    $emailTemplateVariables = array('customer_status' => ''.$titleStatus.'','title_status' => ''.$titleStatus.'','customer_status_year' => ''.$customerStatusYear.'');
    $processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
    $emailTemplate->setSenderName(Mage::getStoreConfig('trans_email/ident_general/name'));
    $emailTemplate->setSenderEmail(Mage::getStoreConfig('trans_email/ident_general/email'));
    $emailTemplate->send($email, $name, $emailTemplateVariables);
} 

I would like the change of the group and the sending of the email to be carried out ONLY ONCE, only when the client group is changed for the first time and not every time I load a page of the site.

How would I go about running my php code just once?