Location: PHPKode > scripts > HTTP Request class > http-request-class/classhttpreq.php
<?php
/*
Author : Martin Fasani [ www.movil.be ]
lastMod: 20050701 [YYYYMMDD]

Please feel free to leave comments about this class at: http://www.movil.be/blog/index.php?entry=entry050823-112430

This class will make the JavaScript code to create the request.
Is experimental and tested for this examples. Has minumum error checking, be aware if you are going to use it anywhere.
Feel free to extend it and add new methods.

To do:
+ needs tweaking, validation, extend it to another uses
+ handling setTimeOut to repeat a request function each n seconds
+ Extend implementation of $onreadydo, right now it outputs to a DIV tag writing with InnerHTML or launchs a user defined function, it should have other options as well.
+ error handling
*/

class httpreq {
  var $obj;     // Name of the object handler
  var $method;  // GET (POST method coded as a demo for the google soap request)
  var $url;     // url of the request
  var $async;   // Sync mode. Booleean
  var $getheader="ALL";      // Only for HEAD method. [default ALL] or header name, e.g. Last-modified
  var $send;
  var $debug=true;             // On true will alert some errors
  var $nocache=false;          // Adds "?timestamp" or "&timestamp" depending on the url. Not production.
  var $onreadydo="writetodiv"; // DIV output by default or used defined fucntion. e.g. dothis();
  var $output;                 // internal Script output 

//constructor that runs in the initialization of the class
function httpreq($obj) {
  $this->obj   =$obj;
  $msie = preg_match("/MSIE/i",getenv("HTTP_USER_AGENT") );
  // Check browser type. Expanded this constructor if you need additional support for specific browsers
  switch ($msie) {
    case true:
	    $output="var ieversion = ['Msxml2.XMLHTTP.5.0','Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0','Msxml2.XMLHTTP', 'Microsoft.XMLHTTP']; var $obj=false;
        for(var i=0; !$this->obj && i<ieversion.length; i++) { 
          try{ $this->obj = new ActiveXObject(ieversion[i]); } catch(e) { $this->obj = false; }
        };\n";
		break;

	default:
		$output=$this->obj." = new XMLHttpRequest();\n";
	    break;
  }

  $this->output=$output;

 }

function httpdorequest($method,$url,$async=true) {
/* $method,$url,$async any validation would be here */
  $this->method=$method;
  $this->url   =$url;
  $this->async =($async) ? 'true' : 'false';
  $strnocache="";
  if ($this->nocache) {
    $this->url =(! strstr($this->url, '?') ) ? $this->url."?" :$this->url."&";
    $strnocache= "+(new Date).getTime()";
  }
  
  switch ($this->method) {
    case "GET":
	$output ="function httpdo$this->obj() {
	$this->obj.open('$this->method','$this->url' $strnocache,$this->async); 
	$this->obj.onreadystatechange=httpresponse$this->obj;
	$this->obj.send('$this->send');
    } \n";
	$responsetype="responseText";
	break;

/*
We will set here a default content type text/xml for the google request demo.
*/
	case "POST":
	$output ="function httpdo$this->obj() {
	$this->obj.open('$this->method','$this->url' $strnocache,$this->async); 
	$this->obj.onreadystatechange=httpresponse$this->obj;
	$this->obj.setRequestHeader('MessageType','CALL');
    $this->obj.setRequestHeader('Content-Type','text/xml');
	$this->obj.send('$this->send');
    } \n";
	$responsetype="responseText";
	break;

	case "HEAD":
	$output ="function httpdo$this->obj() {
	$this->obj.open('$this->method','$this->url' $strnocache,$this->async); 
	$this->obj.onreadystatechange=httpresponse$this->obj;
	$this->obj.send('$this->send');
    } \n";
	
	$responsetype=($this->getheader=="ALL") ? "getAllResponseHeaders()" 
                  : "getResponseHeader('$this->getheader')";
	break;
	}

//Event handler function called by onreadystatechange
  switch ($this->onreadydo) {
  case "writetodiv":
    $debugline=($this->debug) ? "  if (!document.getElementById('$this->obj')) { 
	    alert('Place tag <DIV id=$this->obj > in your HTML before doing the output');
        }" : "";
	$output .="function httpresponse$this->obj() {
	if ($this->obj.readyState==4) {
	$debugline
        document.getElementById('$this->obj').innerHTML=$this->obj.$responsetype;
	} else {
        document.getElementById('$this->obj').innerHTML='Loading ...';} 
	} \n";
   break;

   default:  //This will be a user defined function
    preg_match("/^([A-Z]+)/i",$this->onreadydo,$funcmatch); //Get only function name ( $funcmatch[0] )
   
    $debugline=($this->debug) ? "if (window.$funcmatch[0]) { $this->onreadydo; } else { alert('function $funcmatch[0] NOT FOUND. Please create the javascript function in order to set value onreadydo to launch function $funcmatch[0]'); }" : "$this->onreadydo;";
	$output .="function httpresponse$this->obj() {
	if ($this->obj.readyState==4) {
	$debugline
	}
  }\n";
   break;
   }

	$this->output.=$output;
}

/*
Keep in mind that if you use several httpfireonload() only the last one will be fired, otherwise build a custom function to launch them serialized.
*/
function httpfireonload() {
    $this->output.="window.onload=httpdo$this->obj; \n"; 
}

function send($data=null,$type='string',$cleanwhitespace=true) {
  switch ($type) {
  case "file":
  $handle = fopen ($data, "r"); 
  $send   = fread ($handle, filesize($data) );
  fclose($handle);
  break;

  case "url":
  $handle = fopen ($data, "r");
  if ($handle) {
  while (!feof($handle))   {
	  $send .= fread($handle, 500);
      }
  fclose($handle);
  }
  break;

  case "string":
  $send=$data;
  }
  if ($cleanwhitespace) {
    // Strip out white space to avoid JS errors
  $search  = array ("'([\r\n])[\s]+'");
  $replace = array ("");
  $send = preg_replace($search, $replace, $send);
  }
  $this->send  =$send;
}

function httpcreate() {
  $pretag="<SCRIPT language='JavaScript'>\n";$endtag="</SCRIPT>";
  echo $pretag.$this->output.$endtag;
}

}

  /*
  Optional redirect when browser does not support HttpRequest (add after switch case in costructor)
  $output.="if (!$this->obj) window.location='theotherpage.php'";

  */
?>
Return current item: HTTP Request class