簡體   English   中英

在 HTML 上運行 PHP 后台程序而不會減慢頁面加載速度

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

當有人打開電子郵件正文中包含 IP 地址等內容的頁面時,我會發送觸發電子郵件。

我用它從另一個頁面運行 PHP 腳本。

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


    <!DOCTYPE html>
    <html>
    <head>

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

這個 PHP 腳本需要時間來處理,它會減慢客戶頁面的加載速度。

在 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";
}

有沒有辦法在 HTML 頁面上運行 PHP 腳本而不會使頁面變慢?

謝謝

羅布

您應該使用 Javascript 觸發此腳本。 您應該使用 Ajax (jQuery) 或 Fetch Api 來觸發 Http 請求。 我推薦 Fetch,但請查看http://caniuse.com/#search=fetch以獲取瀏覽器支持。

獲取 Api 示例:

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

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

該腳本在您的 DOM 加載后調用,意味着首先是內容,然后是 trigger.php 的請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM