PHP Classes

Package extensions

Recommend this page to a friend!

      HTTP Request class  >  All threads  >  Package extensions  >  (Un) Subscribe thread alerts  
Subject:Package extensions
Summary:A couple of ideas to extend this package.
Messages:2
Author:Marc Bonaventura
Date:2005-09-05 10:22:53
Update:2005-09-06 12:17:48
 

  1. Package extensions   Reply   Report abuse  
Picture of Marc Bonaventura Marc Bonaventura - 2005-09-05 10:22:53
First of all, I liked this package a lot because it's so simple it has almost nothing but the most basic functionality. That said, here come a couple of ideas I've implemented over the basic package:

<?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
*/

/* If you decide to include the script as an external javascript file, you should set the following two tags to null like this:
define (HTTPREQ_PRETAG,"");
define (HTTPREQ_ENDTAG,"");
If you are using a different document model, be careful to adapt the <script...> tag to your particular model.
*/
define (HTTPREQ_PRETAG,"<script type='text/javascript'>\n");
define (HTTPREQ_ENDTAG,"</script>\n");
define (HTTPREQ_COMMENT,"'Loading ...'"); // Defines the message to appear while contacting the server. Leave blank for no message, feel free to localize.
/* if you initialize it with $req->httpdorequest('GET','reqfile.php',true,**false**);, then the following comment will not be printed while the class checks the server for a reply. If it's true or not present, it will be shown. */
define (HTTPREQ_DEFAULTMETHOD,"GET"); // The default method in case of non-identifyable input

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();
/* Possible values for $onreadydo:
writetodiv: just writes to the div, and then executes $runafter.
default: calls a user defined function.
*/
var $output; // internal Script output
/* Here starts to get interesting: $runafter includes the code you want executed after the server has replied. I choose to hide/show the containing div depending on it being empty or not */
var $runafter=" if (div_obj.innerHTML=='') div_obj.style.display='none'; else div_obj.style.display='block';\n "; // This javascript will be executed after the contents have been updated.
/* here goes the code that will be executed if the navigator doesn't suppor this object (that is, usually MSIE with activex disabled). I just pop up an alert, it could as well be redirected somewhere else... */
var $noobject="alert('You cannot run the code associated to this page. Please go to Tools -> Internet Options -> and enable execution of Activex controls.\\nBE WARNED: this composes somewhat of a security risk, so it is not advised.');\n";

//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;
}
$output.="if (!$this->obj) ".$this->noobject;
$this->output=$output;
}

function httpdorequest($method,$url,$async=true,$comment=true) {
/* $method,$url,$async any validation would be here */

$this->method = (preg_match("(GET|POST|HEAD)",$method)) ? $method : HTTPREQ_DEFAULTMETHOD;
$this->url =$url;
$this->async = ($async) ? 'true' : 'false';
$commentline = ($comment) ? 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() {\n $this->obj.open('$this->method','$this->url' $strnocache,$this->async);\n $this->obj.onreadystatechange=httpresponse$this->obj;\n $this->obj.send('$this->send');\n} \n";
$responsetype="responseText";
break;
case "POST":
/* We will set here a default content type text/xml for the google request demo. */
$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() {\n $this->obj.open('$this->method','$this->url' $strnocache,$this->async);\n $this->obj.onreadystatechange=httpresponse$this->obj;\n $this->obj.send('$this->send');\n}\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() {\n div_obj=document.getElementById('$this->obj');\n if ($this->obj.readyState==4) {\n $debugline\n div_obj.innerHTML=$this->obj.$responsetype;\n $this->runafter}\n";
if ($commentline) $output .= " else document.getElementById('$this->obj').innerHTML=".HTTPREQ_COMMENT.";";
$output .= "\n} \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]'); }\n" : " $this->onreadydo;\n";
$output .="function httpresponse$this->obj() {\n if ($this->obj.readyState==4) {\n$debugline }\n}\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;
break;
}
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() {
echo(HTTPREQ_PRETAG.$this->output.HTTPREQ_ENDTAG);
}
}
?>

  2. Re: Package extensions   Reply   Report abuse  
Picture of Martin Fasani Martin Fasani - 2005-09-06 12:17:48 - In reply to message 1 from Marc Bonaventura
Thanks for the comments and suggestions. It's true that the class has almost nothing except the basic things to fire and receive the request. That was the initial mission, making a javascript generator with the basics, to make it simple to understand to developers starting to use this type of requests.
Actually, I've printed out your suggestions, and I'm checking the updates and writing in paper. When I find out some free time I will publish here in the forum and later update the class.
As I wrote before in my blog, AJAX is still not supported in the 100% of the browsers, and if you 've ActiveX disabled in Internet Explorer, it will fail work. Hence, you need always to provide an alternative, if possible non-javascript at all, to make sure your page works for everybody.

If anyone has more suggestions or comments post them, so I add them to the list. Best regards,
MARTIN