forward.phps

#!/usr/bin/php5
<?php                            
// forward.php
// Forwards all http-clients to a specified url, has been tested with over 100 requests/second.
// hellfairy - http://packy.se/
error_reporting(E_ALL & ~E_NOTICE);
define('NEWLINE', "\r\n");

// listen port
$port = 6969;
// destination url
$forward = "http://aftonbladet.se/";
 
$laststat = time();
$hits = 0;

$data = 'HTTP/1.1 301 Moved Permanently'.NEWLINE.'Connection: close'.NEWLINE.'Location: '.$forward.NEWLINE.'Content-Length: 0'.NEWLINE.NEWLINE;
$datasize = strlen($data);

$socket = stream_socket_server('tcp://0.0.0.0:'.$port, $errno, $errstr);
if (!$socket) {
  echo "$errstr ($errno)\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    $clientaddr = stream_socket_get_name($conn, true);
    list($ip, $port) = explode(':', $clientaddr);
    if($ip)
    {
      //echo 'Forwarding: '.$ip.' to: '.$forward.NEWLINE;
      if(fwrite($conn, $data))
      {
        stats();
      }
    }
    fclose($conn);
  }
  fclose($socket);
}

function stats()
{
  global $laststat, $hits, $datasize;
  $hits++;
  $time = time() - $laststat;
  if($time > 15)
  {
    $laststat = $laststat + 15;
    echo date('[H:i:s]')." Forwarder: ".str_pad(round($hits/15,0),4)." relocated/s (".str_pad(round(($hits*$datasize)/15,0),8)." bytes/s)\n";
    $hits = 0;
  }
}

?>