简体   繁体   中英

PHP microtime returning different results

I seem to be having a strange issue when using the microtime function in PHP. On my index.php I have the following

$.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
}
});

On loadtime.php

$host =  $_GET['host'];

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

When going to my index.php it shows a time of anything under 2.00 seconds (which is wrong). I then created another PHP file called loadtime2.php and changed the code to

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

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

And then test the script by going to mywebsite.com/loadtime2.php and this gives me times over 5.00 seconds. I can't work out what is causing this discrepancy, it's like microtime is giving me the time to retrieve loadtime.php from index.php instead of the time to get the website contents.

Assuming your code snippets aren't contrived examples, the issue is probably this:

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

Since you're using GET, URLs should be encoded before they are passed in a query string. The PHP is probably receiving a garbled version of the URL which 404s in the 2 seconds, whereas the loadtime2.php file is giving you (roughly) the actual loading time. (You could confirm this by dumping the URL or the response)

Try encodeURIComponent .

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

PS In PHP, single ticks ' are best for URLs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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