3
I’m trying to take the time that the internet remained on the page, however is returned nothing.
Main php file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Introdução</title>
<!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>-->
<script src="jquery-3.1.1.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
var inicio;
$(document).ready(function(){
inicio = new Date();
inicio = inicio.getTime();
$(window).unload(function(){
fim = new Date;
fim = fim.getTime();
$.ajax({
url: 'http://127.0.0.1/time.php',
data: {'time': fim - inicio},
success: function(i){$('#demo').html(i);}
});
});
});
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>
time php.
<?php
# converter o tempo para um formato legivel
function converter($tempo)
{
$hora = 0;
$tempo = $tempo / 1000;
$ms = str_replace('0.', '', $tempo - floor($tempo));
if($tempo > 3600)
{
$hora = floor($tempo / 3600);
}
$tempo = $tempo % 3600;
$out = str_pad($hora, 2, '0', STR_PAD_LEFT) . gmdate(':i:s', $tempo) . ($ms ? ".$ms" : '');
return $out;
}
if(isset($_GET['time'])){
$file = fopen('time.txt', 'w');
if($file){
fwrite($file, converter($_GET['time']));
fclose($file);
}
}
?>
and finally:
time.txt
blank.
Anybody know what’s wrong? I really need to solve this problem.
Or it only works on one system?
– valpmg
The PHP code that creates the convert function and takes the data from the http request must be in the time.php file and not in the main one. And you also don’t need to set the div on it. Just the code is enough.
– igor.araujo
I tried it anyway. Igor did what you mentioned and visited the.php team but nothing yet. I put js inside a site and visited the page time.php and nothing yet. I think this code has some error.
– valpmg
sendBeacon is the ideal solution for this, but does not work in IE or Safari. One idea is to make a long-Polling/websocket, would be very reliable and has wider support. Consider leaving this type of task to Google Analytics or Piwik.
– rodorgas