Category Archives: PHP and jQuery

PHP jQuery Class

This is a very interesting code snippets to construct a class that gives you access to all the power of jQuery
{code type=php}<?php

class Jquery {

function animate($trigger, $element, $event, $time) {

echo<script>

$(function() {

$($trigger).$event(function() {

$(#$element’).slideDown($time);

});

});

</script>;

;
}
}

?>

<html>

<head>
<meta http-equiv=”Content-type” content=”text/html; charset=utf-8″>
<title>jquery class</title>

<script type=”text/javascript” charset=”utf-8″ src=”http://code.jquery.com/jquery-1.5.1.js”>

</script>

<style>

#paragraph {display:none;}

</style>

</head>

<body id=”jquery” onload=”">

<?
$trigger=#trigger”;
$element = “paragraph”;
$event = “click”;
$time =500;

$slide = new Jquery();
echo $slide->animate($trigger, $element, $event, $time);
?>

<a id=”trigger” href=”#”>click me</a>
<div id = “paragraph”>my paragraph</div>

</body>

</html>{/code}

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP Scripts for Utilize jQuery and AJAX in WordPress

In the following snippets of code, we will show you how to implement the use of jQuery and AJAX in your WordPress installation (typically in your own custom plugin). The first bit of code you will need is to make sure that you load the jQuery library.Since WordPress comes with jQuery and AJAX already bundled, you can make sure it is loaded by first setting up an action for WordPress to include the jQuery library. The below example utilizes the admin_print_scripts action, which will obviously only run in the admin section of WordPress. You may change this based on your needs.

 

1    jQuery(document).ready(function($) {
2
3       $('#someElementId').live('click', function() {
4            var dataRequest = ({action: "yourWordPressAjaxFunction",
5                        someparam: somevalue,
6                        seed: Math.random()});
7
8            $.ajaxSetup ({
9                cache: false,
10                async: false
11            });
12
13            $("#preloader").html('<p><img src="loader.gif" alt="" /></p>');
14
15            $.get(ajaxurl, dataRequest, function(data){
16
17                if (data.returnError != "success") {
18                    divContent = '<p> + data.returnError + '</p>';
19                    $("#someDivId").empty().append( divContent );
20                } else {
21                            divContent  = '
<p><strong>FINISHED</strong></p>';
22                            divContent  += '
<p><strong>VAR1: ' + data.someValue1 + '</strong></p>';
23                            divContent  += '
<p><strong>VAR2: ' + data.someValue2 + '</strong></p>';
24                            $("#preloader").empty().append( divContent );
25                }
26            }, "json");
27        });
28    });

&amp;nbsp;

PHP Scripts for Sending Hebrew Mail to Outlook

A few weeks ago I had a client that needed a PHP contact form, no problem right. Wrong, the thing is he wanted to receive mails in Hebrew. I set it all up and worked fine in Thunderbird, Gmail, etc… , but would not display the Hebrew in MS Outlook. After hours of testing and searching I finally found a solution. The issue was the message headers, setting just the charset and mime type did not work, the content-language also needed to be set. Below is the snippet.

 

1    <?php
2
3    // Your Email Address
4    $ax_mailTo          = 'you@tld.com';
5
6    // Contact Form Title
7    $ax_mailSubject     = '[Contact Form]' . $_POST['subject'];
8
9    // IMPORTANT The base encoded subject, this prevents the title printing gibberish.
10    $subject            = "=?UTF-8?B?".base64_encode($ax_mailSubject)."?=";
11
12    // Name from Contact Form
13    $name               = $_POST['contactName'];
14
15    // Message from Contact Form
16    $message            = $_POST['message'];
17
18    // The email contents.
19    $body = '
20
21        Name: '
. $name . '
22        Email: '
. $email . '
23        Comments: '
. $message . '
24
25    '
;
26
27    // The message headers
28    $headers = "From: $ax_mailTo" . "\r\n";
29    $headers .= "Reply-To: $ax_mailTo" . "\r\n";
30    $headers .= "MIME-Version: 1.0" . "\r\n";
31    $headers .= "Content-language: he" . "\r\n";
32    $headers .= "Content-type: text/plain; charset=UTF-8";
33
34    // Send the mail
35    mail($ax_mailTo, $subject, $body, $headers);
36
37    ?>

&amp;nbsp;

PHP Scripts Ajax-jquery-shoutbox.zip

This script is based on jQuery library and Form plugin. It’s very easy to setup it, also an archive is available for download so you can play with the files on your localhost. This jquery shoutbox is file based, but it’s very easy to write a few more lines to keep your messages in a database. It tries to simulate the behaviour of YShout (a donation ware script) you can find online. Data is exchanged in JSON format, pear Json library is being used.

 

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 <title>jQuery</title>
 <style type="text/css">
 #daddy-shoutbox {
padding: 5px;
 background: #3E5468;
color: white;
 width: 600px;
 font-family: Arial,Helvetica,sans-serif;
 font-size: 11px;
 }
 .shoutbox-list {
 border-bottom: 1px solid #627C98;

 padding: 5px;
 display: none;
 }
 #daddy-shoutbox-list {
text-align: left;
 margin: 0px auto;
 }
 #daddy-shoutbox-form {
text-align: left;

 }
 .shoutbox-list-time {
 color: #8DA2B4;
}
 .shoutbox-list-nick {
 margin-left: 5px;
 font-weight: bold;
 }
 .shoutbox-list-message {
 margin-left: 5px;
 }

 </style>
 <script type="text/javascript" src="js/jquery.js"></script>
 <script type="text/javascript" src="js/jquery.form.js"></script>
</head>
 <body>

 <center>
 <div id="daddy-shoutbox">
 <div id="daddy-shoutbox-list"></div>
 <br />
 <form id="daddy-shoutbox-form" action="demos/jquery-shoutbox/daddy-shoutbox.php?action=add" method="post">
 Nick: <input type="text" name="nickname" /> Say: <input type="text" name="message" />
 <input type="submit" value="Submit" />
 <span id="daddy-shoutbox-response"></span>
 </form>
 </div>
 </center>

 <script type="text/javascript">
 var count = 0;
 var files = 'demos/jquery-shoutbox/';
 var lastTime = 0;

 function prepare(response) {
 var d = new Date();
 count++;
 d.setTime(response.time*1000);
 var mytime = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
 var string = '<div id="list-'+count+'">'
 + '<span>'+mytime+'</span>'
 + '<span>'+response.nickname+':</span>'
 + '<span>'+response.message+'</span>'
 +'</div>';

 return string;
 }

 function success(response, status)  {
 if(status == 'success') {
 lastTime = response.time;
 $('#daddy-shoutbox-response').html('<img src="'+files+'images/accept.png" />');
 $('#daddy-shoutbox-list').append(prepare(response));
 $('input[@name=message]').attr('value', '').focus();
 $('#list-'+count).fadeIn('slow');
 timeoutID = setTimeout(refresh, 3000);
 }
 }

 function validate(formData, jqForm, options) {
 for (var i=0; i < formData.length; i++) {
 if (!formData[i].value) {
 alert('Please fill in all the fields');
 $('input[@name='+formData[i].name+']').css('background', 'red');
 return false;
 }
 }
 $('#daddy-shoutbox-response').html('<img src="'+files+'images/loader.gif" />');
 clearTimeout(timeoutID);
 }

 function refresh() {
 $.getJSON(files+"daddy-shoutbox.php?action=view&amp;time="+lastTime, function(json) {
 if(json.length) {
 for(i=0; i < json.length; i++) {
 $('#daddy-shoutbox-list').append(prepare(json[i]));
 $('#list-' + count).fadeIn('slow');
 }
 var j = i-1;
 lastTime = json[j].time;
 }
 //alert(lastTime);
 });
 timeoutID = setTimeout(refresh, 3000);
 }

 // wait for the DOM to be loaded
 $(document).ready(function() {
 var options = {
 dataType:       'json',
 beforeSubmit:   validate,
 success:        success
 };
 $('#daddy-shoutbox-form').ajaxForm(options);
 timeoutID = setTimeout(refresh, 100);
 });
 </script>
</body>
</html>

&amp;nbsp;

&amp;nbsp;

PHP scripts for PluXml-latest

# ------------------ BEGIN LICENSE BLOCK ------------------
#
# This file is part of PluXml : http://pluxml.org
#
# Copyright (c) 2010 Stephane Ferrari and contributors
# Copyright (c) 2008-2009 Florent MONTHEL and contributors
# Copyright (c) 2006-2008 Anthony GUERIN
# Licensed under the GPL license.
# See http://www.gnu.org/licenses/gpl.html
#
# ------------------- END LICENSE BLOCK -------------------

# Configuration avançée #
define('PLX_ROOT', './');
define('PLX_CORE', PLX_ROOT.'core/');
define('PLX_CONF', PLX_ROOT.'data/configuration/parametres.xml');

# On verifie que PluXml est installé
if(!file_exists(PLX_CONF)) {
 header('Location: '.PLX_ROOT.'install.php');
 exit;
}

# On inclut les librairies nécessaires
include(PLX_ROOT.'config.php');
include(PLX_CORE.'lib/class.plx.date.php');
include(PLX_CORE.'lib/class.plx.utils.php');
include(PLX_CORE.'lib/class.plx.capcha.php');
include(PLX_CORE.'lib/class.plx.erreur.php');
include(PLX_CORE.'lib/class.plx.glob.php');
include(PLX_CORE.'lib/class.plx.record.php');
include(PLX_CORE.'lib/class.plx.motor.php');
include(PLX_CORE.'lib/class.plx.feed.php');
include(PLX_CORE.'lib/class.plx.show.php');
include(PLX_CORE.'lib/class.plx.encrypt.php');

# Creation de l'objet principal et lancement du traitement
$plxMotor = new plxMotor(PLX_CONF);
$plxMotor->prechauffage();
$plxMotor->demarrage();

# Creation de l'objet d'affichage
$plxShow = new plxShow($plxMotor);

# On démarre la bufferisation
ob_start();
ob_implicit_flush(0);

# On charge les fichiers du thème
if($plxMotor->style == '' or !is_dir(PLX_ROOT.'themes/'.$plxMotor->style)) {
 header('Content-Type: text/plain');
 echo 'Le theme principal PluXml est introuvable ('.PLX_ROOT.'themes/'.$plxMotor->style.') !';
} elseif(file_exists(PLX_ROOT.'themes/'.$plxMotor->style.'/'.$plxMotor->template)) {
 # On impose le charset
header('Content-Type: text/html; charset='.PLX_CHARSET);
 # Insertion du template
include(PLX_ROOT.'themes/'.$plxMotor->style.'/'.$plxMotor->template);
} else {
 header('Content-Type: text/plain');
 echo 'Le fichier cible PluXml est introuvable ('.PLX_ROOT.'themes/'.$plxMotor->style.'/'.$plxMotor->template.') !';
}

# Affichage
if($plxMotor->aConf['urlrewriting']) {
 if($plxMotor->aConf['gzip'])
 plxUtils::ob_gzipped_page($plxMotor->aConf['racine']);
 else
 echo plxUtils::rel2abs($plxMotor->aConf['racine'], ob_get_clean());
} else {
 if($plxMotor->aConf['gzip'])
 plxUtils::ob_gzipped_page(false);
 else
 echo ob_get_clean();
}

?>

&amp;nbsp;

&amp;nbsp;

Unzip file using PHP

if (!function_exists(file_put_contents)) {
 // If not PHP5, creates a compatible function
 function file_put_contents($file, $data) {
 if ($tmp = fopen($file, “w”)) {
 fwrite($tmp, $data);
 fclose($tmp);
 return true;
 }
 echo<b>file_put_contents:</b> Cannot create file $file<br>;
 return false;
 }
 }

class dUnzip2 {
 function getVersion() {
 return2.6;
 }
 // Public
 var $fileName;
 var $compressedList; // You will problably use only this one!
 var $centralDirList; // Central dir list… It’s a kind of ‘extra attributes’ for a set of files
 var $endOfCentral; // End of central dir, contains ZIP Comments
 var $debug;

// Private
 var $fh;
 var $zipSignature = “\x50\x4b\x03\x04″; // local file header signature
 var $dirSignature = “\x50\x4b\x01\x02″; // central dir header signature
 var $dirSignatureE = “\x50\x4b\x05\x06″; // end of central dir signature

// Public
 function dUnzip2($fileName) {
 $this->fileName = $fileName;
 $this->compressedList = $this->centralDirList = $this->endOfCentral = Array ();
 }

function getList($stopOnFile = false) {
 if (sizeof($this->compressedList)) {
 $this->debugMsg(1, “Returning already loaded file list.);
 return $this->compressedList;
 }

// Open file, and set file handler
 $fh = fopen($this->fileName, “r”);
 $this->fh = &amp; $fh;
 if (!$fh) {
 $this->debugMsg(2, “Failed to load file.);
 return false;
 }

$this->debugMsg(1, “Loading list from ‘End of Central Dir’ index list…”);
 if (!$this->_loadFileListByEOF($fh, $stopOnFile)) {
 $this->debugMsg(1, “Failed! Trying to load list looking for signatures…”);
 if (!$this->_loadFileListBySignatures($fh, $stopOnFile)) {
 $this->debugMsg(1, “Failed! Could not find any valid header.);
 $this->debugMsg(2, “ZIP File is corrupted or empty);
 return false;
 }
 }

if ($this->debug) {
 #——- Debug compressedList
$kkk = 0;
 echo<table border=0′ style=’font: 11px Verdana; border: 1px solid #000′>”;
foreach ($this->compressedList as $fileName => $item) {
 if (!$kkk &amp;&amp; $kkk = 1) {
 echo<tr style=’background: #ADA’>”;
foreach ($item as $fieldName => $value)
 echo<td>$fieldName</td>;
 echo</tr>;
 }
 echo<tr style=’background: #CFC’>”;
foreach ($item as $fieldName => $value) {
 if ($fieldName == ‘lastmod_datetime’)
 echo<td title=$fieldName’ nowrap=’nowrap’>. date(“d/m/Y H:i:s”, $value) .</td>;
 else
 echo<td title=$fieldName’ nowrap=’nowrap’>$value</td>;
 }
 echo</tr>;
 }
 echo</table>;

#——- Debug centralDirList
$kkk = 0;
 if (sizeof($this->centralDirList)) {
 echo<table border=0′ style=’font: 11px Verdana; border: 1px solid #000′>”;
foreach ($this->centralDirList as $fileName => $item) {
 if (!$kkk &amp;&amp; $kkk = 1) {
 echo<tr style=’background: #AAD’>”;
foreach ($item as $fieldName => $value)
 echo<td>$fieldName</td>;
 echo</tr>;
 }
 echo<tr style=’background: #CCF’>”;
foreach ($item as $fieldName => $value) {
 if ($fieldName == ‘lastmod_datetime’)
 echo<td title=$fieldName’ nowrap=’nowrap’>. date(“d/m/Y H:i:s”, $value) .</td>;
 else
 echo<td title=$fieldName’ nowrap=’nowrap’>$value</td>;
 }
 echo</tr>;
 }
 echo</table>;
 }

#——- Debug endOfCentral
$kkk = 0;
 if (sizeof($this->endOfCentral)) {
 echo<table border=0′ style=’font: 11px Verdana’ style=’border: 1px solid #000′>”;
echo<tr style=’background: #DAA’><td colspan=’2′>dUnzip – End of file</td></tr>”;
foreach ($this->endOfCentral as $field => $value) {
 echo<tr>;
 echo<td style=’background: #FCC’>$field</td>”;
echo<td style=’background: #FDD’>$value</td>”;
echo</tr>;
 }
 echo</table>;
 }
 }

return $this->compressedList;
 }
 function getExtraInfo($compressedFileName) {
 return isset ($this->centralDirList[$compressedFileName]) ? $this->centralDirList[$compressedFileName] : false;
 }
 function getZipInfo($detail = false) {
 return $detail ? $this->endOfCentral[$detail] : $this->endOfCentral;
 }

function unzip($compressedFileName, $targetFileName = false, $applyChmod = false) {
 if (!sizeof($this->compressedList)) {
 $this->debugMsg(1, “Trying to unzip before loading file list… Loading it!);
 $this->getList(false, $compressedFileName);
 }

$fdetails = &amp; $this->compressedList[$compressedFileName];
 if (!isset ($this->compressedList[$compressedFileName])) {
 $this->debugMsg(2,File<b>$compressedFileName</b>’ is not compressed in the zip.);
 return false;
 }
 if (substr($compressedFileName, -1) ==/) {
 $this->debugMsg(2, “Trying to unzip a folder name ‘<b>$compressedFileName</b>.);
 return false;
 }
 if (!$fdetails['uncompressed_size']) {
 $this->debugMsg(1,File<b>$compressedFileName</b>’ is empty.);
 return $targetFileName ? file_put_contents($targetFileName, “”) : “”;
 }

fseek($this->fh, $fdetails['contents-startOffset']);
 $ret = $this->uncompress(fread($this->fh,  $fdetails['compressed_size']), $fdetails['compression_method'],  $fdetails['uncompressed_size'], $targetFileName);
 if ($applyChmod &amp;&amp; $targetFileName)
 chmod($targetFileName, 0777);

return $ret;
 }
 function unzipAll($targetDir = false, $baseDir = “”, $maintainStructure = true, $applyChmod = false) {
 if ($targetDir === false)
 $targetDir = dirname(__FILE__) ./;

$lista = $this->getList();
 if (sizeof($lista))
 foreach ($lista as $fileName => $trash) {
 $dirname = dirname($fileName);
 $outDN =$targetDir/$dirname;

if (substr($dirname, 0, strlen($baseDir)) != $baseDir)
 continue;

if (!is_dir($outDN) &amp;&amp; $maintainStructure) {
 $str = “”;
 $folders = explode(/, $dirname);
 foreach ($folders as $folder) {
 $str = $str ? “$str/$folder: $folder;
 if (!is_dir($targetDir/$str)) {
 $this->debugMsg(1, “Creating folder: $targetDir/$str);
 mkdir($targetDir/$str);
 if ($applyChmod)
 chmod($targetDir/$str, $applyChmod);
 }
 }
 }
 if (substr($fileName, -1, 1) ==/)
 continue;

$maintainStructure ? $this->unzip($fileName,  “$targetDir/$fileName, $applyChmod) : $this->unzip($fileName,  “$targetDir/. basename($fileName), $applyChmod);
 }
 }

function close() { // Free the file resource
 if ($this->fh)
 fclose($this->fh);
 }
 function __destroy() {
 $this->close();
 }

// Private (you should NOT call these methods):
 function uncompress($content, $mode, $uncompressedSize, $targetFileName = false) {
 switch ($mode) {
 case 0 :
 // Not compressed
 return $targetFileName ? file_put_contents($targetFileName, $content) : $content;
 case 1 :
 $this->debugMsg(2, “Shrunk mode is not supported… yet?”);
 return false;
 case 2 :
 case 3 :
 case 4 :
 case 5 :
 $this->debugMsg(2, “Compression factor ” . ($mode -1) . ” is not supported… yet?”);
 return false;
 case 6 :
 $this->debugMsg(2,Implode is not supported… yet?”);
 return false;
 case 7 :
 $this->debugMsg(2, “Tokenizing compression algorithm is not supported… yet?”);
 return false;
 case 8 :
 // Deflate
 return $targetFileName ? file_put_contents($targetFileName,  gzinflate($content, $uncompressedSize)) : gzinflate($content,  $uncompressedSize);
 case 9 :
 $this->debugMsg(2, “Enhanced Deflating is not supported… yet?”);
 return false;
 case 10 :
 $this->debugMsg(2, “PKWARE Date Compression Library Impoloding is not supported… yet?”);
 return false;
 case 12 :
 // Bzip2
 return $targetFileName ? file_put_contents($targetFileName, bzdecompress($content)) : bzdecompress($content);
 case 18 :
 $this->debugMsg(2, “IBM TERSE is not supported… yet?”);
 return false;
 default :
 $this->debugMsg(2, “Unknown uncompress method: $mode);
 return false;
 }
 }
 function debugMsg($level, $string) {
 if ($this->debug)
 if ($level == 1)
 echo<b style=’color: #777′>dUnzip2:</b> $string<br>”;
if ($level == 2)
 echo<b style=’color: #F00′>dUnzip2:</b> $string<br>”;
}

function _loadFileListByEOF(&amp; $fh, $stopOnFile = false) {
 // Check if there’s a valid Central Dir signature.
 // Let’s consider a file comment smaller than 1024 characters…
 // Actually, it length can be 65536.. But we’re not going to support it.

for ($x = 0; $x < 1024; $x++) {
 fseek($fh, -22$x, SEEK_END);

$signature = fread($fh, 4);
 if ($signature == $this->dirSignatureE) {
 // If found EOF Central Dir
 $eodir['disk_number_this'] = unpack(“v”, fread($fh, 2)); // number of this disk
 $eodir['disk_number'] = unpack(“v”, fread($fh, 2)); // number of the disk with the start of the central directory
 $eodir['total_entries_this'] = unpack(“v”, fread($fh, 2)); // total number of entries in the central dir on this disk
 $eodir['total_entries'] = unpack(“v”, fread($fh, 2)); // total number of entries in
 $eodir['size_of_cd'] = unpack(“V”, fread($fh, 4)); // size of the central directory
 $eodir['offset_start_cd'] = unpack(“V”, fread($fh, 4)); // offset of  start of central directory with respect to the starting disk number
 $zipFileCommentLenght = unpack(“v”, fread($fh, 2)); // zipfile comment length
 $eodir['zipfile_comment'] = $zipFileCommentLenght[1] ? fread($fh, $zipFileCommentLenght[1]) :; // zipfile comment
 $this->endOfCentral = Array (
 ‘disk_number_this’ => $eodir['disk_number_this'][1],
 ‘disk_number’ => $eodir['disk_number'][1],
 ‘total_entries_this’ => $eodir['total_entries_this'][1],
 ‘total_entries’ => $eodir['total_entries'][1],
 ‘size_of_cd’ => $eodir['size_of_cd'][1],
 ‘offset_start_cd’ => $eodir['offset_start_cd'][1],
 ‘zipfile_comment’ => $eodir['zipfile_comment'],

);

// Then, load file list
 fseek($fh, $this->endOfCentral['offset_start_cd']);
 $signature = fread($fh, 4);

while ($signature == $this->dirSignature) {
 $dir['version_madeby'] = unpack(“v”, fread($fh, 2)); // version made by
 $dir['version_needed'] = unpack(“v”, fread($fh, 2)); // version needed to extract
 $dir['general_bit_flag'] = unpack(“v”, fread($fh, 2)); // general purpose bit flag
 $dir['compression_method'] = unpack(“v”, fread($fh, 2)); // compression method
 $dir['lastmod_time'] = unpack(“v”, fread($fh, 2)); // last mod file time
 $dir['lastmod_date'] = unpack(“v”, fread($fh, 2)); // last mod file date
 $dir['crc-32'] = fread($fh, 4); // crc-32
 $dir['compressed_size'] = unpack(“V”, fread($fh, 4)); // compressed size
 $dir['uncompressed_size'] = unpack(“V”, fread($fh, 4)); // uncompressed size
 $fileNameLength = unpack(“v”, fread($fh, 2)); // filename length
 $extraFieldLength = unpack(“v”, fread($fh, 2)); // extra field length
 $fileCommentLength = unpack(“v”, fread($fh, 2)); // file comment length
 $dir['disk_number_start'] = unpack(“v”, fread($fh, 2)); // disk number start
 $dir['internal_attributes'] = unpack(“v”, fread($fh, 2)); // internal file attributes-byte1
 $dir['external_attributes1'] = unpack(“v”, fread($fh, 2)); // external file attributes-byte2
 $dir['external_attributes2'] = unpack(“v”, fread($fh, 2)); // external file attributes
 $dir['relative_offset'] = unpack(“V”, fread($fh, 4)); // relative offset of local header
 $dir['file_name'] = fread($fh, $fileNameLength[1]); // filename
 $dir['extra_field'] = $extraFieldLength[1] ? fread($fh, $extraFieldLength[1]) :; // extra field
 $dir['file_comment'] = $fileCommentLength[1] ? fread($fh, $fileCommentLength[1]) :; // file comment

// Convert the date and time, from MS-DOS format to UNIX Timestamp
 $BINlastmod_date = str_pad(decbin($dir['lastmod_date'][1]), 16,0, STR_PAD_LEFT);
 $BINlastmod_time = str_pad(decbin($dir['lastmod_time'][1]), 16,0, STR_PAD_LEFT);
 $lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7)) + 1980;
 $lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4));
 $lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5));
 $lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5));
 $lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6));
 $lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5));

$this->centralDirList[$dir['file_name']] = Array (
 ‘version_madeby’ => $dir['version_madeby'][1],
 ‘version_needed’ => $dir['version_needed'][1],
 ‘general_bit_flag’ => str_pad(decbin($dir['general_bit_flag'][1]
 ), 8,0, STR_PAD_LEFT), ‘compression_method’ =>  $dir['compression_method'][1], ‘lastmod_datetime’ =>  mktime($lastmod_timeH, $lastmod_timeM, $lastmod_timeS, $lastmod_dateM,  $lastmod_dateD, $lastmod_dateY), ‘crc-32=>  str_pad(dechex(ord($dir['crc-32'][3])), 2,0, STR_PAD_LEFT) .
 str_pad(dechex(ord($dir['crc-32'][2])), 2,0, STR_PAD_LEFT) .
 str_pad(dechex(ord($dir['crc-32'][1])), 2,0, STR_PAD_LEFT) .
 str_pad(dechex(ord($dir['crc-32'][0])), 2,0, STR_PAD_LEFT),  ‘compressed_size’ => $dir['compressed_size'][1], ‘uncompressed_size’  => $dir['uncompressed_size'][1], ‘disk_number_start’ =>  $dir['disk_number_start'][1], ‘internal_attributes’ =>  $dir['internal_attributes'][1], ‘external_attributes1′ =>  $dir['external_attributes1'][1], ‘external_attributes2′ =>  $dir['external_attributes2'][1], ‘relative_offset’ =>  $dir['relative_offset'][1], ‘file_name’ => $dir['file_name'],  ‘extra_field’ => $dir['extra_field'], ‘file_comment’ =>  $dir['file_comment'],);
 $signature = fread($fh, 4);
 }

// If loaded centralDirs, then try to identify the offsetPosition of the compressed data.
 if ($this->centralDirList)
 foreach ($this->centralDirList as $filename => $details) {
 $i = $this->_getFileHeaderInformation($fh, $details['relative_offset']);
 $this->compressedList[$filename]['file_name'] = $filename;
 $this->compressedList[$filename]['compression_method'] = $details['compression_method'];
 $this->compressedList[$filename]['version_needed'] = $details['version_needed'];
 $this->compressedList[$filename]['lastmod_datetime'] = $details['lastmod_datetime'];
 $this->compressedList[$filename]['crc-32'] = $details['crc-32'];
 $this->compressedList[$filename]['compressed_size'] = $details['compressed_size'];
 $this->compressedList[$filename]['uncompressed_size'] = $details['uncompressed_size'];
 $this->compressedList[$filename]['lastmod_datetime'] = $details['lastmod_datetime'];
 $this->compressedList[$filename]['extra_field'] = $i['extra_field'];
 $this->compressedList[$filename]['contents-startOffset'] = $i['contents-startOffset'];
 if (strtolower($stopOnFile) == strtolower($filename))
 break;
 }
 return true;
 }
 }
 return false;
 }
 function _loadFileListBySignatures(&amp; $fh, $stopOnFile = false) {
 fseek($fh, 0);

$return = false;
 for (;;) {
 $details = $this->_getFileHeaderInformation($fh);
 if (!$details) {
 $this->debugMsg(1, “Invalid signature. Trying to verify if is old style Data Descriptor…”);
 fseek($fh, 124, SEEK_CUR); // 12: Data descriptor – 4: Signature (that will be read again)
 $details = $this->_getFileHeaderInformation($fh);
 }
 if (!$details) {
 $this->debugMsg(1, “Still invalid signature. Probably reached the end of the file.);
 break;
 }
 $filename = $details['file_name'];
 $this->compressedList[$filename] = $details;
 $return = true;
 if (strtolower($stopOnFile) == strtolower($filename))
 break;
 }

return $return;
 }
 function _getFileHeaderInformation(&amp; $fh, $startOffset = false) {
 if ($startOffset !== false)
 fseek($fh, $startOffset);

$signature = fread($fh, 4);
 if ($signature == $this->zipSignature) {
 # $this->debugMsg(1, “Zip Signature!”);

// Get information about the zipped file
 $file['version_needed'] = unpack(“v”, fread($fh, 2)); // version needed to extract
 $file['general_bit_flag'] = unpack(“v”, fread($fh, 2)); // general purpose bit flag
 $file['compression_method'] = unpack(“v”, fread($fh, 2)); // compression method
 $file['lastmod_time'] = unpack(“v”, fread($fh, 2)); // last mod file time
 $file['lastmod_date'] = unpack(“v”, fread($fh, 2)); // last mod file date
 $file['crc-32'] = fread($fh, 4); // crc-32
 $file['compressed_size'] = unpack(“V”, fread($fh, 4)); // compressed size
 $file['uncompressed_size'] = unpack(“V”, fread($fh, 4)); // uncompressed size
 $fileNameLength = unpack(“v”, fread($fh, 2)); // filename length
 $extraFieldLength = unpack(“v”, fread($fh, 2)); // extra field length
 $file['file_name'] = fread($fh, $fileNameLength[1]); // filename
 $file['extra_field'] = $extraFieldLength[1] ? fread($fh, $extraFieldLength[1]) :; // extra field
 $file['contents-startOffset'] = ftell($fh);

// Bypass the whole compressed contents, and look for the next file
 fseek($fh, $file['compressed_size'][1], SEEK_CUR);

// Convert the date and time, from MS-DOS format to UNIX Timestamp
 $BINlastmod_date = str_pad(decbin($file['lastmod_date'][1]), 16,0, STR_PAD_LEFT);
 $BINlastmod_time = str_pad(decbin($file['lastmod_time'][1]), 16,0, STR_PAD_LEFT);
 $lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7)) + 1980;
 $lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4));
 $lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5));
 $lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5));
 $lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6));
 $lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5));

// Mount file table
 $i = Array (
 ‘file_name’ => $file['file_name'],
 ‘compression_method’ => $file['compression_method'][1],
 ‘version_needed’ => $file['version_needed'][1],
 ‘lastmod_datetime’ => mktime($lastmod_timeH,
 $lastmod_timeM,
 $lastmod_timeS,
 $lastmod_dateM,
 $lastmod_dateD,
 $lastmod_dateY
 ), ‘crc-32=> str_pad(dechex(ord($file['crc-32'][3])), 2,0, STR_PAD_LEFT) .
 str_pad(dechex(ord($file['crc-32'][2])), 2,0, STR_PAD_LEFT) .
 str_pad(dechex(ord($file['crc-32'][1])), 2,0, STR_PAD_LEFT) .
 str_pad(dechex(ord($file['crc-32'][0])), 2,0, STR_PAD_LEFT),  ‘compressed_size’ => $file['compressed_size'][1], ‘uncompressed_size’  => $file['uncompressed_size'][1], ‘extra_field’ =>  $file['extra_field'], ‘general_bit_flag’ =>  str_pad(decbin($file['general_bit_flag'][1]), 8,0, STR_PAD_LEFT),  ‘contents-startOffset’ => $file['contents-startOffset']);
 return $i;
 }
 return false;
 }
 }

$zip = new dUnzip2(‘zipfile.zip’);
 $zip->debug = false; // you can enable if you want to show whats happning
 $zip->getList();
 $zip->unzipAll();

?>

&amp;nbsp;

&amp;nbsp;

PHP scripts for Documentor

/**
 * Original Web Interface to phpDocumentor
 *
 * PHP versions 4 and 5
 *
 * @category   ToolsAndUtilities
 * @package    phpDocumentor
 * @author     Juan Pablo Morales <ju-moral@uniandes.edu.co>
 * @author     Joshua Eichorn <jeichorn@phpdoc.org>
 * @author     Gregory Beaver <cellog@php.net>
 * @author     Chuck Burgess <ashnazg@php.net>
 * @license    http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link       http://pear.php.net/package/PhpDocumentor
 * @filesource
 * @todo       CS cleanup - change package to PhpDocumentor
 * @deprecated redirects automatically to docbuilder
 *             (see {@link docbuilder/index.html})
 */

?>

<html>
<head>
<title>PhpDocumentor (deprecated web interface)</title>
<META HTTP-EQUIV="Refresh" CONTENT="5; URL=docbuilder/"/>
</head>
<body>
This PhpDocumentor web interface is deprecated...
you will be redirected to the DocBuilder interface.
</body>
</html>

&amp;nbsp;

&amp;nbsp;

Redux: Compressing PHP source code

<pre>/**
 * Compact PHP code.
 *
 * Strip comments, combine entire library into one file.
 */
 
if ($argc < 3) {
  <a href="http://www.php.net/print">print</a> "Strip unecessary data from PHP source files.\n\n\tUsage: php compactor.php DESTINATION.php SOURCE.php";
  <a href="http://www.php.net/exit">exit</a>;
}
 
 
$source = $argv[2];
$target = $argv[1];
<a href="http://www.php.net/print">print</a> "Compacting $source into $target.\n";
 
include $source;
 
$files = <a href="http://www.php.net/get_included_files">get_included_files</a>();
 
$out = <a href="http://www.php.net/fopen">fopen</a>($target, 'w');
<a href="http://www.php.net/fwrite">fwrite</a>($out, '<?php' . PHP_EOL);
<a href="http://www.php.net/fwrite">fwrite</a>($out, '
// QueryPath. Copyright (c) 2009, Matt Butcher.' . PHP_EOL);
<a href="http://www.php.net/fwrite">fwrite</a>($out, '// This software is released under the LGPL, v. 2.1 or an MIT-style license.' . PHP_EOL);
<a href="http://www.php.net/fwrite">fwrite</a>($out ,'// <a href="http://opensource.org/licenses/lgpl-2.1.php'" title="http://opensource.org/licenses/lgpl-2.1.php'">http://opensource.org/licenses/lgpl-2.1.php'</a>);
<a href="http://www.php.net/fwrite">fwrite</a>($out, '// <a href="http://querypath.org.'" title="http://querypath.org.'">http://querypath.org.'</a> . PHP_EOL);
foreach ($files as $f) {
  if ($f !== __FILE__) {
    $contents = <a href="http://www.php.net/file_get_contents">file_get_contents</a>($f);
    foreach (<a href="http://www.php.net/token_get_all">token_get_all</a>($contents) as $token) {
      if (<a href="http://www.php.net/is_string">is_string</a>($token)) {
        <a href="http://www.php.net/fwrite">fwrite</a>($out, $token);
      }
      else {
        switch ($token[0]) {
          case T_REQUIRE:
          case T_REQUIRE_ONCE:
          case T_INCLUDE_ONCE:
          // We leave T_INCLUDE since it is rarely used to include
          // libraries and often used to include HTML/template files.
          case T_COMMENT:
          case T_DOC_COMMENT:
          case T_OPEN_TAG:
          case T_CLOSE_TAG:
            break;
          case T_WHITESPACE:
            <a href="http://www.php.net/fwrite">fwrite</a>($out, ' ');
            break;
          default:
            <a href="http://www.php.net/fwrite">fwrite</a>($out, $token[1]);
        }
 
      }
    }
  }
}
<a href="http://www.php.net/fclose">fclose</a>($out);
?></pre>
&amp;nbsp;

&amp;nbsp;

PHP scripts for FormMailer

// ------- three variables you MUST change below  -------------------------------------------------------
$replyemail="you@your--domain"; //change to your email address
$valid_ref1="http://thedemosite.co.uk/contact.html"; //chamge to your domain name
$valid_ref2="http://www.thedemosite.co.uk/contact.html"; //chamge to your domain name

// -------- No changes required below here -------------------------------------------------------------
//
// email variable not set - load $valid_ref1 page
if (!isset($_POST['email']))
{
 echo "<script language=\"JavaScript\"><!--\n ";
 echo "top.location.href = \"$valid_ref1\"; \n// --></script>";
 exit;
}
$ref_page=$_SERVER["HTTP_REFERER"];
$valid_referrer=0;
if($ref_page==$valid_ref1) $valid_referrer=1;
elseif($ref_page==$valid_ref2) $valid_referrer=1;
if((!$valid_referrer) OR ($_POST["block_spam_bots"]!=12))//you can change this but remember to change it in the contact form too
{
 echo '<h2>ERROR - not sent.';
 if (file_exists("debug.flag")) echo '<hr>"$valid_ref1" and "$valid_ref2" are incorrect within the file:<br>
 contact_process.php <br><br>On your system these should be set to: <blockquote>
 $valid_ref1="'
.str_replace("www.","",$ref_page).'"; <br>
 $valid_ref2="'
.$ref_page.'";
 </blockquote></h2>Copy and paste the two lines above
 into the file: contact_process.php <br> (replacing the existing variables and settings)'
;
 exit;
}

//check user input for possible header injection attempts!
function is_forbidden($str,$check_all_patterns = true)
{
 $patterns[0] = '/content-type:/';
 $patterns[1] = '/mime-version/';
 $patterns[2] = '/multipart/';
 $patterns[3] = '/Content-Transfer-Encoding/';
 $patterns[4] = '/to:/';
 $patterns[5] = '/cc:/';
 $patterns[6] = '/bcc:/';
 $forbidden = 0;
 for ($i=0; $i<count($patterns); $i++)
 {
 $forbidden = preg_match($patterns[$i], strtolower($str));
 if ($forbidden) break;
 }
 //check for line breaks if checking all patterns
 if ($check_all_patterns AND !$forbidden) $forbidden = preg_match("/(%0a|%0d|\\n+|\\r+)/i", $str);
 if ($forbidden)
 {
 echo "<font color=red><center><h3>STOP! Message not sent.</font></h3><br><b>
 The text you entered is forbidden, it includes one or more of the following:
 <br><textarea rows=9 cols=25>"
;
 foreach ($patterns as $key => $value) echo trim($value,"/")."\n";
 echo "\\n\n\\r</textarea><br>Click back on your browser, remove the above characters and try again.
 </b><br><br><br><br>Thankfully protected by phpFormMailer freely available from:
 <a href=\"http://thedemosite.co.uk/phpformmailer/\">http://thedemosite.co.uk/phpformmailer/</a>"
;
 exit();
 }
}

foreach ($_REQUEST as $key => $value) //check all input
{
 if ($key == "themessage") is_forbidden($value, false); //check input except for line breaks
 else is_forbidden($value);//check all
}

$name = $_POST["name"];
$email = $_POST["email"];
$thesubject = $_POST["thesubject"];
$themessage = $_POST["themessage"];

$success_sent_msg='<p align="center"><strong>&amp;nbsp;</strong></p>
 <p align="center"><strong>Your message has been successfully sent to us<br>
 </strong> and we will reply as soon as possible.</p>
 <p align="center">A copy of your query has been sent to you.</p>
 <p align="center">Thank you for contacting us.</p>'
;

$replymessage = "Hi $name

Thank you for your email.

We will endeavour to reply to you shortly.

Please DO NOT reply to this email.

Below is a copy of the message you submitted:
--------------------------------------------------
Subject: $thesubject
Query:
$themessage
--------------------------------------------------

Thank you"
;

$themessage = "name: $name \nQuery: $themessage";
mail("$replyemail",
 "$thesubject",
 "$themessage",
 "From: $email\nReply-To: $email");
mail("$email",
 "Receipt: $thesubject",
 "$replymessage",
 "From: $replyemail\nReply-To: $replyemail");
echo $success_sent_msg;
/*
 PHP Form Mailer - phpFormMailer (easy to use and more secure than many cgi form mailers)
 FREE from:

*/


?>

&amp;nbsp;

&amp;nbsp;

Debugging PHP Source Code in the NetBeans

<pre><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>NetBeans PHP debugging sample</title>
        </head>
<body>
    <?php
    $m=5;
    $n=10;
      $sum_of_factorials = calculate_sum_of_factorials ($m, $n);
      echo "The sum of factorials of the entered integers is " . $sum_of_factorials;
   
        function calculate_sum_of_factorials ($argument1, $argument2) {
        $factorial1 = calculate_factorial ($argument1);
        $factorial2 = calculate_factorial ($argument2);
        $result = calculate_sum ($factorial1, $factorial2);
        return $result;
        }
   
      function calculate_factorial ($argument) {
        $factorial_result = 1;
        for ($i=1; $i<=$argument; $i++) {
            $factorial_result = $factorial_result*$i;
        }
            return $factorial_result;
        }
     
        function calculate_sum ($argument1, $argument2) {
            return $argument1 + $argument2;
        }  
?>
  </body>
</html></pre>
&amp;nbsp;

&amp;nbsp;