1

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.

tshepang
  • 10,772
  • 21
  • 84
  • 127

1 Answers1

0

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),

P.S. In PHP, single ticks ' are best for URLs.

Community
  • 1
  • 1
JoshuaOne
  • 1
  • 1