简体   繁体   English

在 HTML 上运行 PHP 后台程序而不会减慢页面加载速度

[英]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.当有人打开电子邮件正文中包含 IP 地址等内容的页面时,我会发送触发电子邮件。

I use this to run the PHP scrip from another page.我用它从另一个页面运行 PHP 脚本。

    <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.这个 PHP 脚本需要时间来处理,它会减慢客户页面的加载速度。

in the trigger.php is (I have taken out some lines for privacy)在 trigger.php 是(为了隐私,我已经去掉了一些行)

$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?有没有办法在 HTML 页面上运行 PHP 脚本而不会使页面变慢?

Thanks谢谢

Rob罗布

You should trigger this script using Javascript.您应该使用 Javascript 触发此脚本。 You either should use Ajax (jQuery), or the Fetch Api to trigger Http requests.您应该使用 Ajax (jQuery) 或 Fetch Api 来触发 Http 请求。 I recommend Fetch, but have a look at http://caniuse.com/#search=fetch for browser support.我推荐 Fetch,但请查看http://caniuse.com/#search=fetch以获取浏览器支持。

Fetch Api example:获取 Api 示例:

<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.该脚本在您的 DOM 加载后调用,意味着首先是内容,然后是 trigger.php 的请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM