想知道是否可以修改此示例PHP页面,以避免页面加载延迟10秒而不影响功能。
<html>
<head><title>Test Page</title></head>
<body>
<h1>Test Page </h1>
<?php
echo '<br/>';
$post_url_prefix="https://httpbin.org/delay/10?ua=";
// creating URL to post (sending user agent received at the server to sample remote API, currently remote API responds after 10 seconds configured in url)
$post_url = $post_url_prefix . urlencode($_SERVER[HTTP_USER_AGENT]);
print_r($post_url);
?>
</body>
</html>
<?php
// using php curl to post data
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,$post_url);
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result=curl_exec($cSession);
curl_close($cSession);
?>
目前,API服务器在响应之前添加了10秒的人工延迟。想知道是否有一个解决方案,这个延迟不应该反映在页面加载时间内。
请注意,问题是来自PHP&#34;服务器端&#34;是否可行。这排除了使用JS,iframe,ajax等的解决方案,这需要从客户端浏览器发出请求。
答案 0 :(得分:0)
这不是很干净,但您可以关闭当前连接并将数据发送到用户浏览器,然后执行CURL调用。这样用户就不必等待它了。
这样的事情会起作用:
<html>
<head><title>Test Page</title></head>
<body>
<h1>Test Page </h1>
<?php
echo '<br/>';
$post_url_prefix="https://httpbin.org/delay/10?ua=";
// creating URL to post (sending user agent received at the server to sample remote API, currently remote API responds after 10 seconds configured in url)
$post_url = $post_url_prefix . urlencode($_SERVER[HTTP_USER_AGENT]);
print_r($post_url);
?>
</body>
</html>
<?php
ob_end_clean();
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
header("Content-Length: 1");
ignore_user_abort(true);
ob_end_flush();
ob_flush();
flush();
// At this point, the page has been sent in full to the user.
// Now, do the CURL request:
// using php curl to post data
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,$post_url);
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result=curl_exec($cSession);
curl_close($cSession);
?>