Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
pack and unpack

Posted by admin (Graham Ellis), 25 November 2004
Unpack in PHP differs from the unpack functions in languages such as Perl in that it returns an associative array, with the keys named in the decode or encoding string.  Very neat!   Here's an example where we take a fixed format data file from our mail server and analyse each line to count the spam and regular emails.

Working sample at http://www.wellho.net/demo/mail_analysis.php4

Code:
<?php

// Spam tables - sample PHP script from Well House Consultants
// Handles our internal "wash.log" data file format

$now = time()/24/60/60;
$fh = fopen("$_SERVER[DOCUMENT_ROOT]/../wash.log","r");
$nlines = 0;
$maxage = 28;

while (1) {
       $nlines ++;
       $line = fgets($fh,1024);
       if (feof($fh)) break;
       $about = unpack("A21from/A21to/A43subject/A3status/".
                       "A6spam/A6limit/A9bytes/A3skipper/".
                       "A11when",$line);
       $daysago = ($about[when]/24/60/60);
       $age = floor($now - $daysago);
       $status = trim($about[status]) == "Yes" ? 1 : 0;
       $tab[$age][$status]++;
       }
for ($k=0; $k<count($tab)-1; $k++) {
       if ($k > $maxage) break;
       $rows .= ("<tr>");
       $rows .= ("<td>less than $k day".(($k==1)?"":"s")." old</td>");
       $rows .= ("<td>".$tab[$k][1]." spams</td>");
       $rows .= ("<td>".$tab[$k][0]." allowed through</td>");
       $rows .= ("</tr>\n");
       $nvalid += $tab[$k][0];
       $nspam += $tab[$k][1];
}
$stamp = date("r");
$percentage = sprintf("%.1f%%",100.0*$nvalid/($nvalid+$nspam));
?>
<html><head><title>Spam Tables - <?= $stamp ?> </title></head>
<body bgcolor=#CCFFFF><h1>Spam Tables</h1>
<b>Spam counts for last month - wellho.net mail server</b><br>
Report timestamped <?= $stamp ?><br><br>
<table border=1><?= $rows ?></table><br>
<?= $nvalid ?> valid and
<?= $nspam ?> spam emails.
<?= $percentage ?> valid.<br><br>
<a href=http://www.wellho.net/resources/privacy.html>Copyright
Well House Consultants</a>,
<?= date("Y") ?><br>
email: <a href=mailto:graham@wellho.net>graham@wellho.net</a><br>
web: <a href=http://www.wellho.net/>http://www.wellho.net</a>
</body>
</html>




This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho