Dragan Peric Dragan Peric - 6 months ago 42
PHP Question

Fake client browser request

Is it possible to make an HTTP request for some HTML pages from a PHP script where the PHP script resides on the same server as the HTML pages? This script has to be running all the time while server is up.


The PHP script must make the request exactly every one second.


I tried a cron job and the accuracy was not sufficient.


I have used nodejs in a javascript routine and that works for me but I would rather have a server side script do the requests.


I want to use an asynchronous method of making the request so as the HTTP request does not interfere with the timing.


I don't want to have a computer which is always on just to be on that page all the time. So I need some other solution using the server where site is hosted.

Answer

Below is an asynchronous PHP request.
It can be run from the same server or any server.
Accuracy should be within a millisecond.
Reducing usleep(1000) will increase accuracy but decrease CPU availability.
Before down voting my answer please make sure you understand what I have done.

This PHP script is http://ispeedlink.com/so/asyncTimer/index.php
It makes an HTTP request to http://ispeedlink.com/so/asyncTimer/log.php "exactly" every second

<?php
$host = 'ispeedlink.com';
$path = '/so/asyncTimer/log.php';
$http = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";
$cntr = 0;
while(true){
  if(((microtime(true) * 1000)  % 10) < 1){ // make http request as soon as system clock passes one second + 100mS
    $stream = stream_socket_client("$host:80", $errno,$errstr, 100,STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT); 
    if ($stream) {
      fwrite($stream, $http);
    }
    else { 
      file_put_contents('error.txt',"Failed: $errno,$errstr\n",FILE_APPEND);
    }
    usleep(990000);  // wait 99 milliseconds so microtime() % 1000   will be greater than 100 until next second
    $cntr++;
    if($cntr > 9){break;}
  }
  usleep(1000);  // release CPU for at least a millisecond.

}

header('Content-Type: text/plain; charset=utf-8');
readfile('log.txt');
file_put_contents('log.txt',"\n",FILE_APPEND);

?>

This is log.php

<?php
$time = microtime(true) . "\n";
file_put_contents('log.txt',$time,FILE_APPEND);
?>

In my Browser I made a request to http://ispeedlink.com/so/asyncTimer/
twice times with a pause in between.

Here is the log.txt

1462802817.32
1462802818.32
1462802819.32
1462802820.32
1462802821.32
1462802822.32
1462802823.32
1462802824.32
1462802825.32
1462802826.33

1462802836.72
1462802837.71
1462802838.72
1462802839.72
1462802840.72
1462802841.72
1462802842.72
1462802843.72
1462802844.72
1462802845.71
Comments