Sajax – PHP and AJAX

Sajax is an open source tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh. The toolkit does 99% of the work for you so you have no excuse to not use it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
<?php	
if (!isset($SAJAX_INCLUDED)) {
 
	/*  
	 * GLOBALS AND DEFAULTS
	 *
	 */ 
	$GLOBALS['sajax_version'] = '0.12';	
	$GLOBALS['sajax_debug_mode'] = 0;
	$GLOBALS['sajax_export_list'] = array();
	$GLOBALS['sajax_request_type'] = 'GET';
	$GLOBALS['sajax_remote_uri'] = '';
	$GLOBALS['sajax_failure_redirect'] = '';
 
	/*
	 * CODE
	 *
	 */ 
 
	//
	// Initialize the Sajax library.
	//
	function sajax_init() {
	}
 
	//
	// Helper function to return the script's own URI. 
	// 
	function sajax_get_my_uri() {
		return $_SERVER["REQUEST_URI"];
	}
	$sajax_remote_uri = sajax_get_my_uri();
 
	//
	// Helper function to return an eval()-usable representation
	// of an object in JavaScript.
	// 
	function sajax_get_js_repr($value) {
		$type = gettype($value);
 
		if ($type == "boolean") {
			return ($value) ? "Boolean(true)" : "Boolean(false)";
		} 
		elseif ($type == "integer") {
			return "parseInt($value)";
		} 
		elseif ($type == "double") {
			return "parseFloat($value)";
		} 
		elseif ($type == "array" || $type == "object" ) {
			//
			// XXX Arrays with non-numeric indices are not
			// permitted according to ECMAScript, yet everyone
			// uses them.. We'll use an object.
			// 
			$s = "{ ";
			if ($type == "object") {
				$value = get_object_vars($value);
			} 
			foreach ($value as $k=>$v) {
				$esc_key = sajax_esc($k);
				if (is_numeric($k)) 
					$s .= "$k: " . sajax_get_js_repr($v) . ", ";
				else
					$s .= "\"$esc_key\": " . sajax_get_js_repr($v) . ", ";
			}
			if (count($value))
				$s = substr($s, 0, -2);
			return $s . " }";
		} 
		else {
			$esc_val = sajax_esc($value);
			$s = "'$esc_val'";
			return $s;
		}
	}
 
	function sajax_handle_client_request() {
		global $sajax_export_list;
 
		$mode = "";
 
		if (! empty($_GET["rs"])) 
			$mode = "get";
 
		if (!empty($_POST["rs"]))
			$mode = "post";
 
		if (empty($mode)) 
			return;
 
		$target = "";
 
		if ($mode == "get") {
			// Bust cache in the head
			header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // Date in the past
			header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			// always modified
			header ("Cache-Control: no-cache, must-revalidate");  // HTTP/1.1
			header ("Pragma: no-cache");                          // HTTP/1.0
			$func_name = $_GET["rs"];
			if (! empty($_GET["rsargs"])) 
				$args = $_GET["rsargs"];
			else
				$args = array();
		}
		else {
			$func_name = $_POST["rs"];
			if (! empty($_POST["rsargs"])) 
				$args = $_POST["rsargs"];
			else
				$args = array();
		}
 
		if (! in_array($func_name, $sajax_export_list))
			echo "-:$func_name not callable";
		else {
			echo "+:";
			$result = call_user_func_array($func_name, $args);
			echo "var res = " . trim(sajax_get_js_repr($result)) . "; res;";
		}
		exit;
	}
 
	function sajax_get_common_js() {
		global $sajax_debug_mode;
		global $sajax_request_type;
		global $sajax_remote_uri;
		global $sajax_failure_redirect;
 
		$t = strtoupper($sajax_request_type);
		if ($t != "" && $t != "GET" && $t != "POST") 
			return "// Invalid type: $t.. \n\n";
 
		ob_start();
		?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
		// remote scripting library
		// (c) copyright 2005 modernmethod, inc
		var sajax_debug_mode = "<?php echo $sajax_debug_mode ? "true" : "false"; ?>";
		var sajax_request_type = "<?php echo $t; ?>";
		var sajax_target_id = "";
		var sajax_failure_redirect = "<?php echo $sajax_failure_redirect; ?>";
 
		function sajax_debug(text) {
			if (sajax_debug_mode)
				alert(text);
		}
 
 		function sajax_init_object() {
 			sajax_debug("sajax_init_object() called..")
 
 			var A;
 
 			var msxmlhttp = new Array(
				'Msxml2.XMLHTTP.5.0',
				'Msxml2.XMLHTTP.4.0',
				'Msxml2.XMLHTTP.3.0',
				'Msxml2.XMLHTTP',
				'Microsoft.XMLHTTP');
			for (var i = 0; i < msxmlhttp.length; i++) {
				try {
					A = new ActiveXObject(msxmlhttp[i]);
				} catch (e) {
					A = null;
				}
			}
 
			if(!A && typeof XMLHttpRequest != "undefined")
				A = new XMLHttpRequest();
			if (!A)
				sajax_debug("Could not create connection object.");
			return A;
		}
 
		var sajax_requests = new Array();
 
		function sajax_cancel() {
			for (var i = 0; i < sajax_requests.length; i++) 
				sajax_requests[i].abort();
		}
 
		function sajax_do_call(func_name, args) {
			var i, x, n;
			var uri;
			var post_data;
			var target_id;
 
			sajax_debug("in sajax_do_call().." + sajax_request_type + "/" + sajax_target_id);
			target_id = sajax_target_id;
			if (typeof(sajax_request_type) == "undefined" || sajax_request_type == "") 
				sajax_request_type = "GET";
 
			uri = "<?php echo $sajax_remote_uri; ?>";
			if (sajax_request_type == "GET") {
 
				if (uri.indexOf("?") == -1) 
					uri += "?rs=" + escape(func_name);
				else
					uri += "&rs=" + escape(func_name);
				uri += "&rst=" + escape(sajax_target_id);
				uri += "&rsrnd=" + new Date().getTime();
 
				for (i = 0; i < args.length-1; i++) 
					uri += "&rsargs[]=" + escape(args[i]);
 
				post_data = null;
			} 
			else if (sajax_request_type == "POST") {
				post_data = "rs=" + escape(func_name);
				post_data += "&rst=" + escape(sajax_target_id);
				post_data += "&rsrnd=" + new Date().getTime();
 
				for (i = 0; i < args.length-1; i++) 
					post_data = post_data + "&rsargs[]=" + escape(args[i]);
			}
			else {
				alert("Illegal request type: " + sajax_request_type);
			}
 
			x = sajax_init_object();
			if (x == null) {
				if (sajax_failure_redirect != "") {
					location.href = sajax_failure_redirect;
					return false;
				} else {
					sajax_debug("NULL sajax object for user agent:\n" + navigator.userAgent);
					return false;
				}
			} else {
				x.open(sajax_request_type, uri, true);
				// window.open(uri);
 
				sajax_requests[sajax_requests.length] = x;
 
				if (sajax_request_type == "POST") {
					x.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
					x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				}
 
				x.onreadystatechange = function() {
					if (x.readyState != 4) 
						return;
 
					sajax_debug("received " + x.responseText);
 
					var status;
					var data;
					var txt = x.responseText.replace(/^\s*|\s*$/g,"");
					status = txt.charAt(0);
					data = txt.substring(2);
 
					if (status == "") {
						// let's just assume this is a pre-response bailout and let it slide for now
					} else if (status == "-") 
						alert("Error: " + data);
					else {
						if (target_id != "") 
							document.getElementById(target_id).innerHTML = eval(data);
						else {
							try {
								var callback;
								var extra_data = false;
								if (typeof args[args.length-1] == "object") {
									callback = args[args.length-1].callback;
									extra_data = args[args.length-1].extra_data;
								} else {
									callback = args[args.length-1];
								}
								callback(eval(data), extra_data);
							} catch (e) {
								sajax_debug("Caught error " + e + ": Could not eval " + data );
							}
						}
					}
				}
			}
 
			sajax_debug(func_name + " uri = " + uri + "/post = " + post_data);
			x.send(post_data);
			sajax_debug(func_name + " waiting..");
			delete x;
			return true;
		}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
		<?php
		$html = ob_get_contents();
		ob_end_clean();
		return $html;
	}
 
	function sajax_show_common_js() {
		echo sajax_get_common_js();
	}
 
	// javascript escape a value
	function sajax_esc($val)
	{
		$val = str_replace("\\", "\\\\", $val);
		$val = str_replace("\r", "\\r", $val);
		$val = str_replace("\n", "\\n", $val);
		$val = str_replace("'", "\\'", $val);
		return str_replace('"', '\\"', $val);
	}
 
	function sajax_get_one_stub($func_name) {
		ob_start();	
		?>
 
		// wrapper for <?php echo $func_name; ?>
 
		function x_<?php echo $func_name; ?>() {
			sajax_do_call("<?php echo $func_name; ?>",
				x_<?php echo $func_name; ?>.arguments);
		}
 
		<?php
		$html = ob_get_contents();
		ob_end_clean();
		return $html;
	}
 
	function sajax_show_one_stub($func_name) {
		echo sajax_get_one_stub($func_name);
	}
 
	function sajax_export() {
		global $sajax_export_list;
 
		$n = func_num_args();
		for ($i = 0; $i < $n; $i++) {
			$sajax_export_list[] = func_get_arg($i);
		}
	}
 
	$sajax_js_has_been_shown = 0;
	function sajax_get_javascript()
	{
		global $sajax_js_has_been_shown;
		global $sajax_export_list;
 
		$html = "";
		if (! $sajax_js_has_been_shown) {
			$html .= sajax_get_common_js();
			$sajax_js_has_been_shown = 1;
		}
		foreach ($sajax_export_list as $func) {
			$html .= sajax_get_one_stub($func);
		}
		return $html;
	}
 
	function sajax_show_javascript()
	{
		echo sajax_get_javascript();
	}
 
 
	$SAJAX_INCLUDED = 1;
}
?>

You can reference more info here at the home site

  • Share/Save/Bookmark

PHP Class – PHPMailer

PHPMailer is a PHP class for PHP that provides a package of functions to send email. The two primary features are sending HTML Email and e-mails with attachments. PHPMailer supports nearly all possiblities to send email: mail(), Sendmail, qmail & direct to SMTP server. You can use any feature of SMTP-based e-mail, multiple recepients via to, CC, BCC, etc. In short: PHPMailer is an efficient way to send e-mail within PHP.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php  
 
 require("class.phpmailer.php");  
 
 $mail = new PHPMailer();  
 
 $mail->IsSMTP();  // telling the class to use SMTP  
 $mail->Host     = "smtp.example.com"; // SMTP server  
 
 $mail->From     = "from@example.com";  
 $mail->AddAddress("myfriend@example.net");  
 
 $mail->Subject  = "First PHPMailer Message";  
 $mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer.";  
 $mail->WordWrap = 50;  
 
 if(!$mail->Send()) {  
   echo 'Message was not sent.';  
   echo 'Mailer error: ' . $mail->ErrorInfo;  
 } else {  
   echo 'Message has been sent.';  
 }  
 ?>

You can find more code samples and the base class to download here: Click Here

  • Share/Save/Bookmark

PHP Class – Geshi

GeSHi is a Generic Syntax Highlighter for PHP and many other languages. The user inputs the source to be highlighted and a language to highlight it in, and GeSHi returns the source code, highlighted and formatted for the web. It includes features for increasing the speed of highlighting, changing how the source is displayed and decreasing the amount of HTML source outputted for speed over slower connections.

GeSHi features also include:

  • The ability to check for keywords in source code in either a case sensitive or non-case sensitive manner (for example, Java will only accept classes with TheCorrectCapitalisation, while in PHP it doesn’t matter)
  • The ability to auto-caps/auto-noncaps keywords in the source (particularly for SQL and older BASIC dialects)
  • The ability to change the style of almost any aspect of the source on the fly, or even choose whether some parts of the source (for example, strings) are highlighted at all. The use of CSS means that the source can take on many aspects – rather than those provided by deprecated HTML elements such as font, b etc.
  • The ability to use CSS classes to massively reduce the amount of outputted code.
  • XHTML compliant output.
  • Simple adding and removing languages.
  • Function to URL conversion so functions can be linked to API documentation
  • Line numbering, context highlighting and much, much more!
48568

The PHPClass page can be found here: Click Here
The GeSHI HomePage can be found here

  • Share/Save/Bookmark

GraphicsMagick or ImageMagick

At some point in a web site or web application project you are going to need Photoshop like capabilites and you are going to need them dynamically on the web. This is where packages like GD fall short and packages like ImageMagick nicely fit this bill however recently I was doing some research on ImageMagick something that we use a lot in our shop, ( using php just making command calls to ImageMagick ) and I came across a new project GraphicsMagic or rather fork of the ImageMagick project that not only claims to be faster and be less resource intensive but also claims that its Open Soucre Licensening is valid and the Licensing of ImageMagick is in question or at worst in violation. So as usual I am interested to here from others on this topic.

  • Share/Save/Bookmark

PHP Class – getID3

Today I was working on a media managent CMS tool and needed the ability to know what size ( screen resolution ) a video is, similar but different to using getimagesize() for an image. I came across an article on php.net and a class project on soureforge that offers a wealth of info on media files of all types. I thought I would share what I found, getID3() is a PHP script that extracts useful information (such as ID3 tags, bitrate, playtime, etc.) from MP3s & other multimedia file formats (Ogg, WMA, WMV, ASF, WAV, AVI, AAC, VQF, FLAC, MusePack, Real, QuickTime, Monkey’s Audio, MIDI and more).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
// include getID3() library (can be in a different directory if full path is specified)
 include_once('getid3.php');
 
// Initialize getID3 engine
$getID3 = new getID3;
 
 // File to get info from
 $file_location = './your/path/to/file.mov';
 
// Get information from the file
 $fileinfo = $getID3->analyze($file_location);
 getid3_lib::CopyTagsToComments($fileinfo);
 
 // Output results
if (!empty($fileinfo['video']['resolution_x'])) { echo '<p> video width: '.$fileinfo['video']['resolution_x'].'</p>'; }
if (!empty($fileinfo['video']['resolution_y'])) { echo '<p> video height: '.$fileinfo['video']['resolution_y'].'</p>'; }
?>

The package referenced (http://www.getid3.org/)

  • Share/Save/Bookmark

HTTP POST from PHP, without cURL

I don’t think we do a very good job of evangelizing some of the nice things that the PHP streams layer does in the PHP manual, or even in general. At least, every time I search for the code snippet that allows you to do an HTTP POST request, I don’t find it in the manual and resort to reading the source. (You can find it if you search for “HTTP wrapper” in the online documentation, but that’s not really what you think you’re searching for when you’re looking).So, here’s an example of how to send a POST request with straight up PHP, no cURL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
  function do_post_request($url, $data, $optional_headers = null)
  {
     $params = array('http' => array(
                  'method' => 'POST',
                  'content' => $data
               ));
     if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
     }
     $ctx = stream_context_create($params);
     $fp = @fopen($url, 'rb', false, $ctx);
     if (!$fp) {
        throw new Exception("Problem with $url, $php_errormsg");
     }
     $response = @stream_get_contents($fp);
     if ($response === false) {
        throw new Exception("Problem reading data from $url, $php_errormsg");
     }
     return $response;
  }
?>

$optional_headers is a string containing additional HTTP headers that you would like to send in your request.

PHP’s HTTP wrapper will automatically fill out the Content-Length header based on the length of the $data that you pass in. It will also automatically set the Content-Type to application/x-www-form-urlencoded if you don’t specify one in the $optional_headers.

I find this very handy; I don’t need to code in redirection logic, HTTP auth handling, user agent setting and so on; they are handled for me by PHP.

You may also want to look into http_build_query() which is a convenience function that allows you to assemble query/post parameters from a PHP variable, applying appropriate escaping.

Kudos to Sara Golemon for both of these things. You can find more documentation on the HTTP wrapper options in the HTTP and HTTPS page in the PHP manual.

  • Share/Save/Bookmark

PHP – send variables using POST without using forms or hidden variables

There came a situation where I needed the ability to send information via the POST method to another URL ( or for that matter it could be another PHP script ) and I did not want to use another language or some sort of trickery, there has to be an elegant solution. Unless I am wrong I think this example below outlines just that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
// Generate the request header 
$ReqHeader = 
"POST $URI HTTP/1.1\n". 
"Host: $Host\n". 
"Content-Type: application/x-www-form-urlencoded\n". 
"Content-Length: $ContentLength\n\n". 
"$ReqBody\n"; 
 
// Open the connection to the host 
$socket = fsockopen($Host, 80, &$errno, &$errstr); 
if (!$socket) 
 
$Result["errno"] = $errno; 
$Result["errstr"] = $errstr; 
return $Result; 
} 
$idx = 0; 
fputs($socket, $ReqHeader); 
while (!feof($socket)) 
 
$Result[$idx++] = fgets($socket, 128); 
} 
?>

Or you can use the cURL extensions for PHP. Once you build it and compile their support into PHP, it is fairly easy to do posting stuff (even over https):

1
2
3
4
5
6
7
8
<?php 
$URL="www.mysite.com/test.php"; 
$ch = curl_init();    
curl_setopt($ch, CURLOPT_URL,"https://$URL");  
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "Data1=blah&Data2=blah");curl_exec ($ch);     
curl_close ($ch); 
?>

This will have the net effect of posting your data to the $URL site, without any header hacking.
You can also do other nifty things with cURL, like retrieve the HTML into variables and scrape through it for neat functionality.To use cURL you need to recompile PHP or check with your ISP to see if they support it

  • Share/Save/Bookmark

HTTP Class for PHP (supports both cURL and fsockopen)

This is a wrapper HTTP class that uses either cURL or fsockopen to harvest resources from the web. It supports a handy subset of functionalists of HTTP that are mostly needed in day to day coding. Scripts who need to communicate with other servers will find it useful. If you’re looking to invoke any RESTful API and don’t want to bother adding a bunch of libraries for that simple thing, just put this class and you’re set.

  • Can use both cURL and fsockopen.
  • Degrades to fsockopen if cURL not enabled.
  • Supports HTTP Basic authentication.
  • Supports defining custom request headers.
  • Supports defining connection timeout values.
  • Supports defining user agent and referral values.
  • Supports both user-defined and persistent cookies.
  • Supports secure connections (HTTPS) with and without cURL.
  • Supports adding requests parameters for both GET and POST.
  • Supports automatic redirection (maximum redirect can be defined).
  • Returns HTTP response headers and response body data separately.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
<?php
/**
 * HTTP Class
 *
 * This is a wrapper HTTP class that uses either cURL or fsockopen to 
 * harvest resources from web. This can be used with scripts that need 
 * a way to communicate with various APIs who support REST.
 *
 * @author      Md Emran Hasan <phpfour@gmail.com>
 * @package     HTTP Library
 * @copyright   2007-2008 Md Emran Hasan
 * @link        http://www.phpfour.com/lib/http
 * @since       Version 0.1
 */
 
class Http
{
    /**
     * Contains the target URL
     *
     * @var string
     */
    var $target;
 
    /**
     * Contains the target host
     *
     * @var string
     */
    var $host;
 
    /**
     * Contains the target port
     *
     * @var integer
     */
    var $port;
 
    /**
     * Contains the target path
     *
     * @var string
     */
    var $path;
 
    /**
     * Contains the target schema
     *
     * @var string
     */
    var $schema;
 
    /**
     * Contains the http method (GET or POST)
     *
     * @var string
     */
    var $method;
 
    /**
     * Contains the parameters for request
     *
     * @var array
     */
    var $params;
 
    /**
     * Contains the cookies for request
     *
     * @var array
     */
    var $cookies;
 
    /**
     * Contains the cookies retrieved from response
     *
     * @var array
     */
    var $_cookies;
 
    /**
     * Number of seconds to timeout
     *
     * @var integer
     */
    var $timeout;
 
    /**
     * Whether to use cURL or not
     *
     * @var boolean
     */
    var $useCurl;
 
    /**
     * Contains the referrer URL
     *
     * @var string
     */
    var $referrer;
 
    /**
     * Contains the User agent string
     *
     * @var string
     */
    var $userAgent;
 
    /**
     * Contains the cookie path (to be used with cURL)
     *
     * @var string
     */
    var $cookiePath;
 
    /**
     * Whether to use cookie at all
     *
     * @var boolean
     */
    var $useCookie;
 
    /**
     * Whether to store cookie for subsequent requests
     *
     * @var boolean
     */
    var $saveCookie;
 
    /**
     * Contains the Username (for authentication)
     *
     * @var string
     */
    var $username;
 
    /**
     * Contains the Password (for authentication)
     *
     * @var string
     */
    var $password;
 
    /**
     * Contains the fetched web source
     *
     * @var string
     */
    var $result;
 
    /**
     * Contains the last headers 
     *
     * @var string
     */
    var $headers;
 
    /**
     * Contains the last call's http status code
     *
     * @var string
     */
    var $status;
 
    /**
     * Whether to follow http redirect or not
     *
     * @var boolean
     */
    var $redirect;
 
    /**
     * The maximum number of redirect to follow
     *
     * @var integer
     */
    var $maxRedirect;
 
    /**
     * The current number of redirects
     *
     * @var integer
     */
    var $curRedirect;
 
    /**
     * Contains any error occurred
     *
     * @var string
     */
    var $error;
 
    /**
     * Store the next token
     *
     * @var string
     */
    var $nextToken;
 
    /**
     * Whether to keep debug messages
     *
     * @var boolean
     */
    var $debug;
 
    /**
     * Stores the debug messages
     *
     * @var array
     * @todo will keep debug messages
     */
    var $debugMsg;
 
    /**
     * Constructor for initializing the class with default values.
     * 
     * @return void  
     */
    function Http()
    {
        $this->clear();    
    }
 
    /**
     * Initialize preferences
     * 
     * This function will take an associative array of config values and 
     * will initialize the class variables using them. 
     * 
     * Example use:
     * 
     * $httpConfig['method']     = 'GET';
     * $httpConfig['target']     = 'http://www.somedomain.com/index.html';
     * $httpConfig['referrer']   = 'http://www.somedomain.com';
     * $httpConfig['user_agent'] = 'My Crawler';
     * $httpConfig['timeout']    = '30';
     * $httpConfig['params']     = array('var1' => 'testvalue', 'var2' => 'somevalue');
     * 
     * $http = new Http();
     * $http->initialize($httpConfig);
     *
     * @param array Config values as associative array
     * @return void
     */    
    function initialize($config = array())
    {
        $this->clear();
        foreach ($config as $key => $val)
        {
            if (isset($this->$key))
            {
                $method = 'set' . ucfirst(str_replace('_', '', $key));
 
                if (method_exists($this, $method))
                {
                    $this->$method($val);
                }
                else
                {
                    $this->$key = $val;
                }            
            }
        }
    }
 
    /**
     * Clear Everything
     * 
     * Clears all the properties of the class and sets the object to
     * the beginning state. Very handy if you are doing subsequent calls 
     * with different data.
     *
     * @return void
     */
    function clear()
    {
        // Set the request defaults
        $this->host         = '';
        $this->port         = 0;
        $this->path         = '';
        $this->target       = '';
        $this->method       = 'GET';
        $this->schema       = 'http';
        $this->params       = array();
        $this->headers      = array();
        $this->cookies      = array();
        $this->_cookies     = array();
 
        // Set the config details        
        $this->debug        = FALSE;
        $this->error        = '';
        $this->status       = 0;
        $this->timeout      = '25';
        $this->useCurl      = TRUE;
        $this->referrer     = '';
        $this->username     = '';
        $this->password     = '';
        $this->redirect     = TRUE;
 
        // Set the cookie and agent defaults
        $this->nextToken    = '';
        $this->useCookie    = TRUE;
        $this->saveCookie   = TRUE;
        $this->maxRedirect  = 3;
        $this->cookiePath   = 'cookie.txt';
        $this->userAgent    = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.9';
    }
 
    /**
     * Set target URL
     *
     * @param string URL of target resource
     * @return void
     */
    function setTarget($url)
    {
        if ($url)
        {
            $this->target = $url;
        }   
    }
 
    /**
     * Set http method
     *
     * @param string HTTP method to use (GET or POST)
     * @return void
     */
    function setMethod($method)
    {
        if ($method == 'GET' || $method == 'POST')
        {
            $this->method = $method;
        }   
    }
 
    /**
     * Set referrer URL
     *
     * @param string URL of referrer page
     * @return void
     */
    function setReferrer($referrer)
    {
        if ($referrer)
        {
            $this->referrer = $referrer;
        }   
    }
 
    /**
     * Set User agent string
     *
     * @param string Full user agent string
     * @return void
     */
    function setUseragent($agent)
    {
        if ($agent)
        {
            $this->userAgent = $agent;
        }   
    }
 
    /**
     * Set timeout of execution
     *
     * @param integer Timeout delay in seconds
     * @return void
     */
    function setTimeout($seconds)
    {
        if ($seconds > 0)
        {
            $this->timeout = $seconds;
        }   
    }
 
    /**
     * Set cookie path (cURL only)
     *
     * @param string File location of cookiejar
     * @return void
     */
    function setCookiepath($path)
    {
        if ($path)
        {
            $this->cookiePath = $path;
        }   
    }
 
    /**
     * Set request parameters
     *
     * @param array All the parameters for GET or POST
     * @return void
     */
    function setParams($dataArray)
    {
        if (is_array($dataArray))
        {
            $this->params = array_merge($this->params, $dataArray);
        }   
    }
 
    /**
     * Set basic http authentication realm
     *
     * @param string Username for authentication
     * @param string Password for authentication
     * @return void
     */
    function setAuth($username, $password)
    {
        if (!empty($username) && !empty($password))
        {
            $this->username = $username;
            $this->password = $password;
        }
    }
 
    /**
     * Set maximum number of redirection to follow
     *
     * @param integer Maximum number of redirects
     * @return void
     */
    function setMaxredirect($value)
    {
        if (!empty($value))
        {
            $this->maxRedirect = $value;
        }
    }
 
    /**
     * Add request parameters
     *
     * @param string Name of the parameter
     * @param string Value of the parameter
     * @return void
     */
    function addParam($name, $value)
    {
        if (!empty($name) && !empty($value))
        {
            $this->params[$name] = $value;
        }   
    }
 
    /**
     * Add a cookie to the request
     *
     * @param string Name of cookie
     * @param string Value of cookie
     * @return void
     */
    function addCookie($name, $value)
    {
        if (!empty($name) && !empty($value))
        {
            $this->cookies[$name] = $value;
        }   
    }
 
    /**
     * Whether to use cURL or not
     *
     * @param boolean Whether to use cURL or not
     * @return void
     */
    function useCurl($value = TRUE)
    {
        if (is_bool($value))
        {
            $this->useCurl = $value;
        }   
    }
 
    /**
     * Whether to use cookies or not
     *
     * @param boolean Whether to use cookies or not
     * @return void
     */
    function useCookie($value = TRUE)
    {
        if (is_bool($value))
        {
            $this->useCookie = $value;
        }   
    }
 
    /**
     * Whether to save persistent cookies in subsequent calls
     *
     * @param boolean Whether to save persistent cookies or not
     * @return void
     */
    function saveCookie($value = TRUE)
    {
        if (is_bool($value))
        {
            $this->saveCookie = $value;
        }   
    }
 
    /**
     * Whether to follow HTTP redirects
     *
     * @param boolean Whether to follow HTTP redirects or not
     * @return void
     */
    function followRedirects($value = TRUE)
    {
        if (is_bool($value))
        {
            $this->redirect = $value;
        }   
    }
 
    /**
     * Get execution result body
     *
     * @return string output of execution
     */
    function getResult()
    {
        return $this->result;
    }
 
    /**
     * Get execution result headers
     *
     * @return array last headers of execution
     */
    function getHeaders()
    {
        return $this->headers;
    }
 
    /**
     * Get execution status code
     *
     * @return integer last http status code
     */
    function getStatus()
    {
        return $this->status;
    }
 
    /**
     * Get last execution error
     *
     * @return string last error message (if any)
     */
    function getError()
    {
        return $this->error;
    }
 
    /**
     * Execute a HTTP request
     * 
     * Executes the http fetch using all the set properties. Intellegently
     * switch to fsockopen if cURL is not present. And be smart to follow
     * redirects (if asked so).
     * 
     * @param string URL of the target page (optional)
     * @param string URL of the referrer page (optional)
     * @param string The http method (GET or POST) (optional)
     * @param array Parameter array for GET or POST (optional)
     * @return string Response body of the target page
     */    
    function execute($target = '', $referrer = '', $method = '', $data = array())
    {
        // Populate the properties
        $this->target = ($target) ? $target : $this->target;
        $this->method = ($method) ? $method : $this->method;
 
        $this->referrer = ($referrer) ? $referrer : $this->referrer;
 
        // Add the new params
        if (is_array($data) && count($data) > 0) 
        {
            $this->params = array_merge($this->params, $data);
        }
 
        // Process data, if presented
        if(is_array($this->params) && count($this->params) > 0)
        {
            // Get a blank slate
            $tempString = array();
 
            // Convert data array into a query string (ie animal=dog&sport=baseball)
            foreach ($this->params as $key => $value) 
            {
                if(strlen(trim($value))>0)
                {
                    $tempString[] = $key . "=" . urlencode($value);
                }
            }
 
            $queryString = join('&', $tempString);
        }
 
        // If cURL is not installed, we'll force fscokopen
        $this->useCurl = $this->useCurl && in_array('curl', get_loaded_extensions());
 
        // GET method configuration
        if($this->method == 'GET')
        {
            if(isset($queryString))
            {
                $this->target = $this->target . "?" . $queryString;
            }
        }
 
        // Parse target URL
        $urlParsed = parse_url($this->target);
 
        // Handle SSL connection request
        if ($urlParsed['scheme'] == 'https')
        {
            $this->host = 'ssl://' . $urlParsed['host'];
            $this->port = ($this->port != 0) ? $this->port : 443;
        }
        else
        {
            $this->host = $urlParsed['host'];
            $this->port = ($this->port != 0) ? $this->port : 80;
        }
 
        // Finalize the target path
        $this->path   = (isset($urlParsed['path']) ? $urlParsed['path'] : '/') . (isset($urlParsed['query']) ? '?' . $urlParsed['query'] : '');
        $this->schema = $urlParsed['scheme'];
 
        // Pass the requred cookies
        $this->_passCookies();
 
        // Process cookies, if requested
        if(is_array($this->cookies) && count($this->cookies) > 0)
        {
            // Get a blank slate
            $tempString   = array();
 
            // Convert cookiesa array into a query string (ie animal=dog&sport=baseball)
            foreach ($this->cookies as $key => $value) 
            {
                if(strlen(trim($value)) > 0)
                {
                    $tempString[] = $key . "=" . urlencode($value);
                }
            }
 
            $cookieString = join('&', $tempString);
        }
 
        // Do we need to use cURL
        if ($this->useCurl)
        {
            // Initialize PHP cURL handle
            $ch = curl_init();
 
            // GET method configuration
            if($this->method == 'GET')
            {
                curl_setopt ($ch, CURLOPT_HTTPGET, TRUE); 
                curl_setopt ($ch, CURLOPT_POST, FALSE); 
            }
            // POST method configuration
            else
            {
                if(isset($queryString))
                {
                    curl_setopt ($ch, CURLOPT_POSTFIELDS, $queryString);
                }
 
                curl_setopt ($ch, CURLOPT_POST, TRUE); 
                curl_setopt ($ch, CURLOPT_HTTPGET, FALSE); 
            }
 
            // Basic Authentication configuration
            if ($this->username && $this->password)
            {
                curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);
            }
 
            // Custom cookie configuration
            if($this->useCookie && isset($cookieString))
            {
                curl_setopt ($ch, CURLOPT_COOKIE, $cookieString);
            }
 
            curl_setopt($ch, CURLOPT_HEADER,         TRUE);                 // No need of headers
            curl_setopt($ch, CURLOPT_NOBODY,         FALSE);                // Return body
 
            curl_setopt($ch, CURLOPT_COOKIEJAR,      $this->cookiePath);    // Cookie management.
            curl_setopt($ch, CURLOPT_TIMEOUT,        $this->timeout);       // Timeout
            curl_setopt($ch, CURLOPT_USERAGENT,      $this->userAgent);     // Webbot name
            curl_setopt($ch, CURLOPT_URL,            $this->target);        // Target site
            curl_setopt($ch, CURLOPT_REFERER,        $this->referrer);      // Referer value
 
            curl_setopt($ch, CURLOPT_VERBOSE,        FALSE);                // Minimize logs
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);                // No certificate
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $this->redirect);      // Follow redirects
            curl_setopt($ch, CURLOPT_MAXREDIRS,      $this->maxRedirect);   // Limit redirections to four
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);                 // Return in string
 
            // Get the target contents
            $content = curl_exec($ch);
            $contentArray = explode("\r\n\r\n", $content);
 
            // Get the request info 
            $status  = curl_getinfo($ch);
 
			// Get the headers
			$resHeader = array_shift($contentArray);
 
			// Store the contents
			$this->result = implode($contentArray, "\r\n\r\n");
 
			// Parse the headers
			$this->_parseHeaders($resHeader);
 
            // Store the error (is any)
            $this->_setError(curl_error($ch));
 
            // Close PHP cURL handle
            curl_close($ch);
        }
        else
        {
            // Get a file pointer
            $filePointer = fsockopen($this->host, $this->port, $errorNumber, $errorString, $this->timeout);
 
            // We have an error if pointer is not there
            if (!$filePointer)
            {
                $this->_setError('Failed opening http socket connection: ' . $errorString . ' (' . $errorNumber . ')');
                return FALSE;
            }
 
            // Set http headers with host, user-agent and content type
            $requestHeader  = $this->method . " " . $this->path . "  HTTP/1.1\r\n";
            $requestHeader .= "Host: " . $urlParsed['host'] . "\r\n";
            $requestHeader .= "User-Agent: " . $this->userAgent . "\r\n";
            $requestHeader .= "Content-Type: application/x-www-form-urlencoded\r\n";
 
            // Specify the custom cookies
            if ($this->useCookie && $cookieString != '')
            {
                $requestHeader.= "Cookie: " . $cookieString . "\r\n";
            }
 
            // POST method configuration
            if ($this->method == "POST")
            {
                $requestHeader.= "Content-Length: " . strlen($queryString) . "\r\n";
            }
 
            // Specify the referrer
            if ($this->referrer != '')
            {
                $requestHeader.= "Referer: " . $this->referrer . "\r\n";
            }
 
            // Specify http authentication (basic)
            if ($this->username && $this->password)
            {
                $requestHeader.= "Authorization: Basic " . base64_encode($this->username . ':' . $this->password) . "\r\n";
            }
 
            $requestHeader.= "Connection: close\r\n\r\n";
 
            // POST method configuration
            if ($this->method == "POST")
            {
                $requestHeader .= $queryString;
            }           
 
            // We're ready to launch
            fwrite($filePointer, $requestHeader);
 
            // Clean the slate
            $responseHeader = '';
            $responseContent = '';
 
            // 3...2...1...Launch !
            do
            {
                $responseHeader .= fread($filePointer, 1);
            }
            while (!preg_match('/\\r\\n\\r\\n$/', $responseHeader));
 
            // Parse the headers
            $this->_parseHeaders($responseHeader);
 
            // Do we have a 302 redirect ?
            if ($this->status == '302' && $this->redirect == TRUE)
            {
                if ($this->curRedirect < $this->maxRedirect)
                {
                    // Let's find out the new redirect URL
                    $newUrlParsed = parse_url($this->headers['location']);
 
                    if ($newUrlParsed['host'])
                    {
                        $newTarget = $this->headers['location'];    
                    }
                    else
                    {
                        $newTarget = $this->schema . '://' . $this->host . '/' . $this->headers['location'];
                    }
 
                    // Reset some of the properties
                    $this->port   = 0;
                    $this->status = 0;
                    $this->params = array();
                    $this->method = 'GET';
                    $this->referrer = $this->target;
 
                    // Increase the redirect counter
                    $this->curRedirect++;
 
                    // Let's go, go, go !
                    $this->result = $this->execute($newTarget);
                }
                else
                {
                    $this->_setError('Too many redirects.');
                    return FALSE;
                }
            }
            else
            {
                // Nope...so lets get the rest of the contents (non-chunked)
                if ($this->headers['transfer-encoding'] != 'chunked')
                {
                    while (!feof($filePointer))
                    {
                        $responseContent .= fgets($filePointer, 128);
                    }
                }
                else
                {
                    // Get the contents (chunked)
                    while ($chunkLength = hexdec(fgets($filePointer)))
                    {
                        $responseContentChunk = '';
                        $readLength = 0;
 
                        while ($readLength < $chunkLength)
                        {
                            $responseContentChunk .= fread($filePointer, $chunkLength - $readLength);
                            $readLength = strlen($responseContentChunk);
                        }
 
                        $responseContent .= $responseContentChunk;
                        fgets($filePointer);  
                    }
                }
 
                // Store the target contents
                $this->result = chop($responseContent);
            }
        }
 
        // There it is! We have it!! Return to base !!!
        return $this->result;
    }
 
    /**
     * Parse Headers (internal)
     * 
     * Parse the response headers and store them for finding the resposne 
     * status, redirection location, cookies, etc. 
     *
     * @param string Raw header response
     * @return void
     * @access private
     */
    function _parseHeaders($responseHeader)
    {
        // Break up the headers
        $headers = explode("\r\n", $responseHeader);
 
        // Clear the header array
        $this->_clearHeaders();
 
        // Get resposne status
        if($this->status == 0)
        {
            // Oooops !
            if(!eregi($match = "^http/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\$", $headers[0], $matches))
            {
                $this->_setError('Unexpected HTTP response status');
                return FALSE;
            }
 
            // Gotcha!
            $this->status = $matches[1];
            array_shift($headers);
        }
 
        // Prepare all the other headers
        foreach ($headers as $header)
        {
            // Get name and value
            $headerName  = strtolower($this->_tokenize($header, ':'));
            $headerValue = trim(chop($this->_tokenize("\r\n")));
 
            // If its already there, then add as an array. Otherwise, just keep there
            if(isset($this->headers[$headerName]))
            {
                if(gettype($this->headers[$headerName]) == "string")
                {
                    $this->headers[$headerName] = array($this->headers[$headerName]);
                }
 
                $this->headers[$headerName][] = $headerValue;
            }
            else
            {
                $this->headers[$headerName] = $headerValue;
            }
        }
 
        // Save cookies if asked 
        if ($this->saveCookie && isset($this->headers['set-cookie']))
        {
            $this->_parseCookie();
        }
    }
 
    /**
     * Clear the headers array (internal)
     *
     * @return void
     * @access private
     */
    function _clearHeaders()
    {
        $this->headers = array();
    }
 
    /**
     * Parse Cookies (internal)
     * 
     * Parse the set-cookie headers from response and add them for inclusion.
     *
     * @return void
     * @access private
     */
    function _parseCookie()
    {
        // Get the cookie header as array
        if(gettype($this->headers['set-cookie']) == "array")
        {
            $cookieHeaders = $this->headers['set-cookie'];
        }
        else
        {
            $cookieHeaders = array($this->headers['set-cookie']);
        }
 
        // Loop through the cookies
        for ($cookie = 0; $cookie < count($cookieHeaders); $cookie++)
        {
            $cookieName  = trim($this->_tokenize($cookieHeaders[$cookie], "="));
            $cookieValue = $this->_tokenize(";");
 
            $urlParsed   = parse_url($this->target);
 
            $domain      = $urlParsed['host'];
            $secure      = '0';
 
            $path        = "/";
            $expires     = "";
 
            while(($name = trim(urldecode($this->_tokenize("=")))) != "")
            {
                $value = urldecode($this->_tokenize(";"));
 
                switch($name)
                {
                    case "path"     : $path     = $value; break;
                    case "domain"   : $domain   = $value; break;
                    case "secure"   : $secure   = ($value != '') ? '1' : '0'; break;
                }
            }
 
            $this->_setCookie($cookieName, $cookieValue, $expires, $path , $domain, $secure);
        }
    }
 
    /**
     * Set cookie (internal)
     * 
     * Populate the internal _cookies array for future inclusion in 
     * subsequent requests. This actually validates and then populates 
     * the object properties with a dimensional entry for cookie.
     *
     * @param string Cookie name
     * @param string Cookie value
     * @param string Cookie expire date
     * @param string Cookie path
     * @param string Cookie domain
     * @param string Cookie security (0 = non-secure, 1 = secure)
     * @return void
     * @access private
     */
    function _setCookie($name, $value, $expires = "" , $path = "/" , $domain = "" , $secure = 0)
    {
        if(strlen($name) == 0)
        {
            return($this->_setError("No valid cookie name was specified."));
        }
 
        if(strlen($path) == 0 || strcmp($path[0], "/"))
        {
            return($this->_setError("$path is not a valid path for setting cookie $name."));
        }
 
        if($domain == "" || !strpos($domain, ".", $domain[0] == "." ? 1 : 0))
        {
            return($this->_setError("$domain is not a valid domain for setting cookie $name."));
        }
 
        $domain = strtolower($domain);
 
        if(!strcmp($domain[0], "."))
        {
            $domain = substr($domain, 1);
        }
 
        $name  = $this->_encodeCookie($name, true);
        $value = $this->_encodeCookie($value, false);
 
        $secure = intval($secure);
 
        $this->_cookies[] = array( "name"      =>  $name,
                                   "value"     =>  $value,
                                   "domain"    =>  $domain,
                                   "path"      =>  $path,
                                   "expires"   =>  $expires,
                                   "secure"    =>  $secure
                                 );
    }
 
    /**
     * Encode cookie name/value (internal)
     *
     * @param string Value of cookie to encode
     * @param string Name of cookie to encode
     * @return string encoded string
     * @access private
     */
    function _encodeCookie($value, $name)
    {
        return($name ? str_replace("=", "%25", $value) : str_replace(";", "%3B", $value));
    }
 
    /**
     * Pass Cookies (internal)
     * 
     * Get the cookies which are valid for the current request. Checks 
     * domain and path to decide the return.
     *
     * @return void
     * @access private
     */
    function _passCookies()
    {
        if (is_array($this->_cookies) && count($this->_cookies) > 0)
        {
            $urlParsed = parse_url($this->target);
            $tempCookies = array();
 
            foreach($this->_cookies as $cookie)
            {
                if ($this->_domainMatch($urlParsed['host'], $cookie['domain']) && (0 === strpos($urlParsed['path'], $cookie['path']))
                    && (empty($cookie['secure']) || $urlParsed['protocol'] == 'https')) 
                {
                    $tempCookies[$cookie['name']][strlen($cookie['path'])] = $cookie['value'];
                }
            }
 
            // cookies with longer paths go first
            foreach ($tempCookies as $name => $values) 
            {
                krsort($values);
                foreach ($values as $value) 
                {
                    $this->addCookie($name, $value);
                }
            }
        }
    }
 
    /**
    * Checks if cookie domain matches a request host (internal)
    * 
    * Cookie domain can begin with a dot, it also must contain at least
    * two dots.
    * 
    * @param string Request host
    * @param string Cookie domain
    * @return bool Match success
     * @access private
    */
    function _domainMatch($requestHost, $cookieDomain)
    {
        if ('.' != $cookieDomain{0}) 
        {
            return $requestHost == $cookieDomain;
        } 
        elseif (substr_count($cookieDomain, '.') < 2) 
        {
            return false;
        } 
        else 
        {
            return substr('.'. $requestHost, - strlen($cookieDomain)) == $cookieDomain;
        }
    }
 
    /**
     * Tokenize String (internal)
     * 
     * Tokenize string for various internal usage. Omit the second parameter 
     * to tokenize the previous string that was provided in the prior call to 
     * the function.
     *
     * @param string The string to tokenize
     * @param string The seperator to use
     * @return string Tokenized string
     * @access private
     */
    function _tokenize($string, $separator = '')
    {
        if(!strcmp($separator, ''))
        {
            $separator = $string;
            $string = $this->nextToken;
        }
 
        for($character = 0; $character < strlen($separator); $character++)
        {
            if(gettype($position = strpos($string, $separator[$character])) == "integer")
            {
                $found = (isset($found) ? min($found, $position) : $position);
            }
        }
 
        if(isset($found))
        {
            $this->nextToken = substr($string, $found + 1);
            return(substr($string, 0, $found));
        }
        else
        {
            $this->nextToken = '';
            return($string);
        }
    }
 
    /**
     * Set error message (internal)
     *
     * @param string Error message
     * @return string Error message
     * @access private
     */
    function _setError($error)
    {
        if ($error != '')
        {
            $this->error = $error;
            return $error;
        }
    }
}
 
?>

1. Simple Get (Facebook Application List)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
 
// Include the Http Class
include_once('class.http.php');
 
// Instantiate it
$http = new Http();
 
// Get Facebook Application page
$http->execute('http://www.facebook.com/apps/index.php');
 
// Show result page or error if occurred
echo ($http->error) ? $http->error : $http->result;
 
?>

2. Invoking Yahoo Term Extraction API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
 
// Include the Http Class
include_once('class.http.php');
 
// Instantiate it
$http = new Http();
 
// Set API parameters
$http->addParam('appid'   , 'a_really_random_yahoo_app_id');
$http->addParam('context' , 'I am happy because I bought a new car');
$http->addParam('output'  , 'xml');
 
// Get the extracted term
$http->execute('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction');
 
// Show result xml or error if occurred
echo ($http->error) ? $http->error : $http->result;
 
?>

3. Logging into Basecamp (without using cURL!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
 
//Include the Http Class
include_once('class.http.php');
 
//Instantiate it
$http = new Http();
 
//Let's not use cURL
$http->useCurl(false);
 
//POST method
$http->setMethod('POST');
 
//POST parameters
$http->addParam('user_name' , 'yourusername');
$http->addParam('password'  , 'yourpassword');
 
//Referrer
$http->setReferrer('https://yourproject.projectpath.com/login');
 
//Get basecamp dashboard (HTTPS)
$http->execute('https://yourproject.projectpath.com/login/authenticate');
 
//Show result page or error if occurred
echo ($http->error) ? $http->error : $http->result;
 
?>

4. Getting a protected feed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
 
// Include the Http Class
include_once('class.http.php');
 
// Instantiate it
$http = new Http();
 
// Set HTTP basic authentication realms
$http->setAuth('yourusername', 'yourpassword');
 
// Get the protected feed
$http->execute('http://www.someblog.com/protected/feed.xml');
 
// Show result feed or error if occurred
echo ($http->error) ? $http->error : $http->result;
 
?>

Reference for this article: Click Here

  • Share/Save/Bookmark

Pasting from MS Word how to format

If you have troubles (like me) getting data from ISO-8859-1 encoded forms where user’s copy and paste directly from word, this routine could be useful. It adds to the standard get_html_translation_table the codes of the characters usually M$ Word replacs into typed text. Otherwise those characters would never be displayed correctly in html output. For all those that use WYSIWYG editors on the web that allow pasting this is a god send as this will catch all the characters that are usually not thought of.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
function get_html_translation_table_CP1252() {
    $trans = get_html_translation_table(HTML_ENTITIES);
    $trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
    $trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
    $trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
    $trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
    $trans[chr(134)] = '&dagger;';    // Dagger
    $trans[chr(135)] = '&Dagger;';    // Double Dagger
    $trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
    $trans[chr(137)] = '&permil;';    // Per Mille Sign
    $trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
    $trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
    $trans[chr(140)] = '&OElig;    ';    // Latin Capital Ligature OE
    $trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
    $trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
    $trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
    $trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
    $trans[chr(149)] = '&bull;';    // Bullet
    $trans[chr(150)] = '&ndash;';    // En Dash
    $trans[chr(151)] = '&mdash;';    // Em Dash
    $trans[chr(152)] = '&tilde;';    // Small Tilde
    $trans[chr(153)] = '&trade;';    // Trade Mark Sign
    $trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
    $trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
    $trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
    $trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
    ksort($trans);
    return $trans;
}
?>

Reference for this article: Click Here

Searching for a fast replacement of the MS WORD special characters which are not covered by get_html_translation_table() , I think the following function might help someone.It replaces all types of quotes (single and double), horizontal ellipsis (…), bullet, en dash and em dash.

1
2
3
4
5
6
7
8
9
10
<?php
function clean_up($str){
$str = stripslashes($str);
$str = strtr($str, get_html_translation_table(HTML_ENTITIES));
$str = str_replace( 
array("\x82", "\x84", "\x85", "\x91", "\x92", "\x93", "\x94", "\x95", "\x96",  "\x97"), 
array("&#8218;", "&#8222;", "&#8230;", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8226;", "&#8211;", "&#8212;"),$str);
return $str;
}
?>

Reference for this article: Click Here

  • Share/Save/Bookmark

PHP reading in XML using UTF-8 with no mbstring

I had a project recently where I need to read in UTF-8 based characters from an XML file.
This would have worked just fine however the production server this was to run on did not have
mbstring as apart of the PHP install and there was no chance of getting that to change, so here
is the workaround that worked for me…This was then used on an HTML(Email) page therefore rendering with the correct UTF-8 character.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
    function XMLEntities($string)
    {
        $string = preg_replace('/[^\x09\x0A\x0D\x20-\x7F]/e', '_privateXMLEntities("$0")', $string);
        return $string;
    }
 
    function _privateXMLEntities($num)
    {
    $chars = array(
        128 => '&#8364;',
        130 => '&#8218;',
        131 => '&#402;',
        132 => '&#8222;',
        133 => '&#8230;',
        134 => '&#8224;',
        135 => '&#8225;',
        136 => '&#710;',
        137 => '&#8240;',
        138 => '&#352;',
        139 => '&#8249;',
        140 => '&#338;',
        142 => '&#381;',
        145 => '&#8216;',
        146 => '&#8217;',
        147 => '&#8220;',
        148 => '&#8221;',
        149 => '&#8226;',
        150 => '&#8211;',
        151 => '&#8212;',
        152 => '&#732;',
        153 => '&#8482;',
        154 => '&#353;',
        155 => '&#8250;',
        156 => '&#339;',
        158 => '&#382;',
        159 => '&#376;');
        $num = ord($num);
        return (($num > 127 && $num < 160) ? $chars[$num] : "&#".$num.";" );
    }
?>

Reference for this article can be found here: Click Here

  • Share/Save/Bookmark

Devin’s Knowledge Blog is Digg proof thanks to caching by WP Super Cache!