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 = "info@webhost.com"; $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 = "Trigger@webhost.com"; $mail->FromName = "Website"; //To address and name $mail->addAddress($email, "Web Trigger"); //Address to which recipient will reply $mail->addReplyTo("info@webhost.com", "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
Advertisement
Answer
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.