1

在 PHP 中使用 microtime 函数时,我似乎遇到了一个奇怪的问题。在我的 index.php 上,我有以下内容

$.ajax({
url:'loadtime.php',
datatype:"application/json",
type:'get',
data: "host=http://www.mywebsite.com",
success:function(data){
  document.getElementById('loadtime_com').innerHTML = data;
},
    error:function(){
  // code for error
}
});

在加载时间.php

$host =  $_GET['host'];

$time = microtime( TRUE );
file_get_contents( $host );
$time = microtime( TRUE ) - $time;
echo $time;

当转到我的 index.php 时,它显示的时间小于 2.00 秒(这是错误的)。然后我创建了另一个名为 loadtime2.php 的 PHP 文件并将代码更改为

$host =  "http://www.mywebsite.com";

$time = microtime( TRUE );
file_get_contents( $host );
$time = microtime( TRUE ) - $time;
echo $time;

然后通过访问 mywebsite.com/loadtime2.php 测试脚本,这给了我超过 5.00 秒的时间。我不知道是什么导致了这种差异,就像 microtime 让我有时间从 index.php 检索 loadtime.php 而不是获取网站内容的时间。

4

1 回答 1

0

假设您的代码片段不是人为的示例,问题可能是这样的:

data: "host=http://www.mywebsite.com",

由于您使用的是 GET,因此在将 URL 传递到查询字符串之前应该对其进行编码。PHP 可能会收到一个乱码版本的 URL,它在 2 秒内 404 秒,而该loadtime2.php文件(大致)为您提供了实际加载时间。(您可以通过转储 URL 或响应来确认这一点)

尝试encodeURIComponent

data: "host=" + encodeURIComponent(url),

PS 在 PHP 中,单引号'适合 URL

于 2014-04-29T16:34:52.437 回答