Renegade Rob
Renegade Rob

Reputation: 403

Run PHP background program on HTML without slowing down a page load

I send a trigger email when someone opens a page with things like an IP address in the email body.

I use this to run the PHP scrip from another page.

    <script src="trigger.php">
    </script>


    <!DOCTYPE html>
    <html>
    <head>

Here is the rest of the HTML page.......

This PHP script takes time to process and it slows down the loading of a page for a customer.

in the trigger.php is (I have taken out some lines for privacy)

$site = "Main Page";
$email = "[email protected]";
$ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$ip"));
$country = $geo["geoplugin_countryName"];
$city = $geo["geoplugin_city"];
$identify = $_SERVER['HTTP_USER_AGENT'];

if (isset($_GET['source'])){$source=$_GET['source'];}

date_default_timezone_set('Australia/Melbourne');

$date = date('l jS \of F Y h:i:s A');

$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));

if($query && $query['status'] == 'success') {
  $country = $query['country'];
  $city = $query['city'];
  $lat = $query['lat'];
  $lon = $query['lon'];
} 

require_once "PHPMailer-master/PHPMailerAutoload.php";

$mail = new PHPMailer;

$mail->From = "[email protected]";
$mail->FromName = "Website";

//To address and name
$mail->addAddress($email, "Web Trigger");

//Address to which recipient will reply
$mail->addReplyTo("[email protected]", "Reply");

//Send HTML or Plain Text email
$mail->isHTML(true);

$mail->Subject = $site." Trigger";
$mail->Body = $message;

if(!$mail->send())
{
    echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
    echo "Message has been sent successfully";
}

Is there a way to run the PHP script on the HTML page without the page slowing down?

Thanks

Rob

Upvotes: 0

Views: 1960

Answers (1)

danopz
danopz

Reputation: 3408

You should trigger this script using Javascript. You either should use Ajax (jQuery), or the Fetch Api to trigger Http requests. I recommend Fetch, but have a look at http://caniuse.com/#search=fetch for browser support.

Fetch Api example:

<html>
    <head>
    </head>
    <body>
        <span>Content</span>

        <script>
            (function() {
                fetch('/trigger.php');
            })();
        </script>
    </body>
</html>

The script is called after your DOM is loaded, means content first, then the request for trigger.php.

Upvotes: 2

Related Questions