Perl CGI macOS TimeZone Simulation Tutorial

Perl CGI macOS TimeZone Simulation Tutorial

Perl CGI macOS TimeZone Simulation Tutorial

Do you remember how with the recent Perl CGI Spreadsheet Download Detector Tutorial‘s web application, in its results webpage, we showed both a …

  • Server current datetime … down below a …
  • Local current datetime

… and that the Local datetime would show a local TimeZone part to the timestamp shown?

That Local datetime’s TimeZone part is derived via your current device’s operating system’s (perhaps its Language & Region but more basically via) Date & Time settings, using terminology used on this macOS operating system we use on this MacBook Air we are using here.

And so, part of the regime to best test a web application such as last talked about

… in the changed Perl hello_get.cgi code supervised by (and working with) the changed HTML hello_get.html web application we hope you (re-)try for yourself

… is to best try to “sit in the shoes” of a user running your web browser based web application in another part of the woooooorrrrrrlllllldddd! Even harder on yourself, if that user’s Local (ie. clientside) time is not based on a full hour increment different to yours. Calling Adelaide!!!!!

And so, today, we show the macOS System Preferences methodology we got great help compiling via the advice of How to change Mac Region Time Zone, thanks, to test our web application simulating the conditions of a user …

  • in Sydney, Australia (with Local TimeZone Australia/Sydney) … yoo hoo … run a web browser test … then change the macOS Local datetime TimeZone to Australia/Adelaide …
  • in Adelaide, Australia (with Local TimeZone Australia/Adelaide temporarily with Local TimeZone detection unchecked) … run a web browser test, then, via the restoration of the original Date & Time System Preferences, back …
  • in Sydney, Australia (with Local TimeZone set back to Australia/Sydney with Local TimeZone detection checked) run a web browser test

… all while sitting in Sydney.


Previous relevant Perl CGI Spreadsheet Download Detector Tutorial is shown below.

Perl CGI Spreadsheet Download Detector Tutorial

Perl CGI Spreadsheet Download Detector Tutorial

The Intranet Audio functionality within yesterday’s Perl CGI Intranet Audio and Translations Tutorial‘s hello_get HTML and Perl web application relied on all of …

  • macOS … underlying operating system, hosting …
  • MAMP local Apache/PHP/MySql web server on port 8888 … call of …
  • PHP … all necessary ( eg. macos_say_record.php ), downloaded, via …
  • exec method … call of …
  • say … command, performs that Intranet style text to audio functionality

A big ask, indeed! But supposing you only needed the outer two above? If this interests, today, we present a …

  • Korn shell … code solution, working for either …
  • crontab … scheduling arrangement, versus …
  • interactive command line … command arrangement

… alternative approach to allowing for audio functionality, that feeds off the detection of spreadsheet downloaded perl.xls file(s) of the hello_get web application.

Let’s just get to the Korn shell, on macOS, code we’ve had (more bulletproof “listener”) success with …


#!/bin/ksh
# lookforspreadsheet.ksh
# RJM Programming
# February, 2023
# Look for Spreadsheets downloaded off hello_get.html HTML and hello_get.cgi Perl
# crontab usage supply an additional argument (onto a first emailee argument, perhaps) ... or to do as a one off execution usage
# Thanks to ...
# https://www.unix.com/unix-for-dummies-questions-and-answers/123644-converting-binary-file-readable-format-ksh.html
# https://stackoverflow.com/questions/26968159/list-of-files-modified-1-hour-before
# https://www.unix.com/shell-programming-and-scripting/247464-awk-combined-if.html
# https://stackoverflow.com/questions/296536/how-to-urlencode-data-for-curl-command

one="1";
two="2";
emailto="";
if [ ! -z "$1" ]; then
if [ "`echo $1 | tr '@' 'x'`" != "`echo $1`" ]; then
emailto="$1";
shift;
fi
fi

while test "$one" -ne "$two" ; do
axls=`find $HOME/Downloads -name "perl*.xls*" -type f -mmin 1`;
if [ ! -z "$axls" ]; then
# res=`hexdump -C "${axls}" | cut -f2 -d '|' | tr -d '\n' | sed "s/'//" | cut -d':' -f 2- | grep '.8.8.8.8./.m.a.c.o.s._.s.a.y._.r.e.c.o.r.d...p.h.p.?.d.o.c.r.o.n.w.o.r.k.=.s.a.y.' | sed '/[.][.][.][.]/s//~/g' | sed '/[%][.]2[.]0/s//"/g' | awk -F'.s.a.y.' '{for(i=2;i<=NF;i++){if($i){split($i,a,"~");print a[1] "@";}}}' | tr -d '&' | sed '/[.][.]/s//.~/g' | sed '/[.]/s///g' | sed '/[~]/s//./g' | sed '/\_record\.php\?docronwork\=\@/s//say/g' | sed '/[@]/s//"; sleep 10; /g'`
res=`hexdump -C "${axls}" | sed '/[.][|][.]/s//.!@!./g' | cut -f2 -d '|' | sed '/[.][!][@][!][.]/s//.|./g' | tr -d '\n' | sed -e 's/=.s.a.y./=.S.a.Y./g' | tr -d "'" | cut -d':' -f 2- | grep '.8.8.8.8./.m.a.c.o.s._.s.a.y._.r.e.c.o.r.d...p.h.p.?.d.o.c.r.o.n.w.o.r.k.=.S.a.Y.' | sed '/[.][.][.][.]/s//~/g' | sed '/[%][.]2[.]0/s//"/g' | awk -F'.S.a.Y.' '{for(i=2;i<=NF;i++){if($i){split($i,a,"~");print "say " a[1] "@";}}}' | tr -d '&' | sed '/[.][.]/s//.~/g' | sed '/[.]/s///g' | sed '/[~]/s//./g' | sed '/\_record\.php\?docronwork\=\@/s//SaY/g' | sed '/[@]/s//"; sleep 10; /g'`
if [ ! -z "$res" ]; then
if [ -z "$1" -a -z "$emailto" ]; then
echo $res > /tmp/idea.ksh;
ksh /tmp/idea.ksh &;
else
if [ ! -z "$emailto" ]; then
echo $res | sed -e 's/%/%25/g' -e 's/ /%20/g' -e 's/!/%21/g' -e 's/"/%22/g' -e 's/#/%23/g' -e 's/\$/%24/g' -e 's/\&/%26/g' -e 's/'\''/%27/g' -e 's/(/%28/g' -e 's/)/%29/g' -e 's/\*/%2a/g' -e 's/+/%2b/g' -e 's/,/%2c/g' -e 's/-/%2d/g' -e 's/\./%2e/g' -e 's/\//%2f/g' -e 's/:/%3a/g' -e 's/;/%3b%0a%0a/g' -e 's//%3e/g' -e 's/?/%3f/g' -e 's/@/%40/g' -e 's/\[/%5b/g' -e 's/\\/%5c/g' -e 's/\]/%5d/g' -e 's/\^/%5e/g' -e 's/_/%5f/g' -e 's/`/%60/g' -e 's/{/%7b/g' -e 's/|/%7c/g' -e 's/}/%7d/g' -e 's/~/%7e/g' > /tmp/idea.ksh;
# restwo=`echo $res | sed '/"/s//@/g' | sed "/@/s//'/g"`
#cat /tmp/idea.ksh | mailx -s "Proposed macos say audio ideas ..." $1;
open "mailto:${emailto}?subject=Proposed%20macos%20say%20audio%20ideas%20...&body=`cat /tmp/idea.ksh`";
echo $res > /tmp/idea.ksh;
else
echo $res > /tmp/idea.ksh;
ksh /tmp/idea.ksh &;
fi
fi
fi
fi
if [ -z "$1" ]; then
sleep 60;
else
two=$one;
fi
done
exit

… in lookforspreadsheet.ksh where you can chmod 744 lookforspreadsheet.ksh to not need the ksh parts to (where our best local email is the rmetcalfe15@gmail.com used below, that you should change as per your needs) …

Interactive
continuous
Interactive
continuous
in background
Interactive
continuous
emailing
in background
Scheduled
audio
(via
crontab -e)
Scheduled
audio
email
ksh lookforspreadsheet.ksh ksh lookforspreadsheet.ksh & ksh lookforspreadsheet.ksh rmetcalfe15@gmail.com & * * * * * ksh lookforspreadsheet.ksh cron * * * * * ksh lookforspreadsheet.ksh rmetcalfe15@gmail.com cron

… as food for thought to simplify a macOS user’s thinking regarding the hello_get web application Spreadsheet downloading detection, and action, if audio hyperlinks have been prepared.


Previous relevant Perl CGI Intranet Audio and Translations Tutorial is shown below.

Perl CGI Intranet Audio and Translations Tutorial

Perl CGI Intranet Audio and Translations Tutorial

Yesterday’s Perl CGI Intranet Audio Tutorial gave us “an in” to audio functionality, but if you get into the innards of the macOS say command you’ll see how an audio voice is our connection with a translation language code. And once there we can utilize the excellent Google Translation functionality, thanks, to broaden the scope of all this being of some usefulness to a wider audience (unless you’ve been on a diet).

It can even extend into new hyperlink arrangements in the downloadable spreadsheets, where a pre-emptive assumption of the Intranet say URLs, does no harm until a user clicks on the hyperlink to find out the conditions are not apt for them.

So take a look at our changed Perl code in …


#!/usr/bin/perl
# hello_get.cgi
# RJM Programming
# February, 2023

use DateTime;
use DateTime::TimeZone;
use DBI;
use DBD::mysql;
use Spreadsheet::WriteExcel;
use Data::Dumper qw(Dumper);
use LWP::UserAgent ();
#use PDF::Create;
use utf8;
#use Unicode::Escape;

# https://www-rjmprogramming-com-au.translate.goog/ITblog/perl-cgi-intranet-audio-tutorial/?_x_tr_sl=en&_x_tr_tl=eu&_x_tr_hl=en-GB&_x_tr_pto=nui

local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

if ($ENV{'REQUEST_METHOD'} eq "GET") {
$buffer = $ENV{'QUERY_STRING'};
} elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
read (STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}

# Split information into name/value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}

my $rest = "";
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
$inurl = $FORM{inurl};
my $outurl = $inurl;
my $voice = "";
if (defined $FORM{voice}) {
$voice = $FORM{voice};
$voice =~ s/%20/ /ig;
$voice =~ s/%2D/-/ig;
$voice =~ s/%2d/-/ig;
}
my $lang = "";
if (defined $FORM{lang}) {
$lang = $FORM{lang};
}
my $before_page = "";
my $allbutlastbit = "";
my $lastbit = (split '/', $ENV{REQUEST_URI})[-1];
my $page_url = 'http';
$page_url.='s' if $ENV{HTTPS};
$page_url.='://';
if ($ENV{SERVER_PORT} != 80) {
$before_page="$ENV{SERVER_NAME}:$ENV{SERVER_PORT}/";
$page_url.="$ENV{SERVER_NAME}:$ENV{SERVER_PORT}$ENV{REQUEST_URI}";
} else {
$before_page="$ENV{SERVER_NAME}/";
$page_url.="$ENV{SERVER_NAME}.$ENV{REQUEST_URI}";
}
if (length($lastbit) > 0) {
$allbutlastbit = substr($page_url, 0, (length($page_url) - length($lastbit)));
} else {
$allbutlastbit = $page_url;
}

if (length($inurl) == 0) {
$inurl = $inurl;
} else {
$inurl =~ s/%3A/:/ig;
$inurl =~ s/%2F/\//ig;
$inurl =~ s/%3F/?/ig;
$inurl =~ s/%26/&/ig;
$outurl = $inurl;
my $ipage_url = $inurl;
my $ibefore_page = "";
my $iallbutlastbit = "";
my $ilastbit = (split '/', $inurl)[-1];
my $lenseven = (7 + length($ilastbit));
my $leneight = (8 + length($ilastbit));
my $leni = length($inurl);
if (length($ilastbit) > 0) {
if ($lenseven == $leni) {
$iallbutlastbit = "${inurl}/";
} elsif ($leneight == $leni) {
$iallbutlastbit = "${inurl}/";
} else {
$iallbutlastbit = substr($ipage_url, 0, (length($ipage_url) - length($ilastbit)));
}
} else {
$iallbutlastbit = $ipage_url;
}

my $ua = LWP::UserAgent->new(timeout => 10);
$ua->env_proxy;

my $response = $ua->get($inurl);

if ($response->is_success) {
my $dcont = $response->decoded_content;
#$dcont =~ s/html\>/div\>/ig;
#$dcont =~ s/body\>/div\>/ig;
$dcont =~ s/"\/\//&#34;\/\//ig;
$dcont =~ s/"http/&#34;http/ig;
$dcont =~ s/"file/&#34;file/ig;
$dotdot = "..\/";
if (index($dcont, "rjmprogramming.com.au") >= 0) {
$allbutlastbit =~ s/:443//ig;
$allbutlastbit =~ s/\/cgi-bin\//\//ig;
if (substr($allbutlastbit, -1, 1) == "/") {
$allbutlastbit = substr($allbutlastbit, 0, (-1 + length($allbutlastbit)));
}
$dcont =~ s/"\//&#34;${allbutlastbit}\//ig;
#$dcont =~ s/ src="/ src="..\//ig;
#$dcont =~ s/ href="/ href="..\//ig;
$dcont =~ s/ src="/ src="${dotdot}/ig;
$dcont =~ s/ action="/ action="${dotdot}/ig;
$dcont =~ s/ srcset="/ srcset="${dotdot}/ig;
$dcont =~ s/ href="/ href="${dotdot}/ig;
} else {
if (index($dcont, "wikipedia.org") >= 0) {
$dotdot =~ s/\/wiki\//\//ig;
${iallbutlastbit} =~ s/\/wiki\//\//ig;
} else {
$dotdot = $iallbutlastbit;
}
if (substr($iallbutlastbit, -1, 1) == "/") {
$iallbutlastbit = substr($iallbutlastbit, 0, (-1 + length($iallbutlastbit)));
}
$dcont =~ s/"\//&#34;${iallbutlastbit}\//ig;
$dcont =~ s/ src="/ src="${dotdot}/ig;
$dcont =~ s/ srcset="/ srcset="${dotdot}/ig;
$dcont =~ s/ action="/ action="${dotdot}/ig;
$dcont =~ s/ href="/ href="${dotdot}/ig;
$dcont =~ s/url\("/url\("${dotdot}/ig;
$dcont =~ s/url\(portal\//url\(${dotdot}portal\//ig;
$dcont =~ s/url\(static\//url\(${dotdot}static\//ig;
$dcont =~ s/url\(wiki\//url\(${dotdot}wiki\//ig;
$dcont =~ s/url\(er\//url\(${dotdot}er\//ig;
}
$dcont =~ s/"/&#34;/ig;
$dcont =~ s/\r\n//ig;
$dcont =~ s/\n//ig;
$dcont =~ s/\r//ig;
# print "Content-type: text/html\n\n";
if ($lang eq "") {
$rest .= "<br><details id=drest><summary><h3><a target=_blank href=$inurl>$inurl</a></h3></summary><br><iframe style=width:100%;height:900px; srcdoc=\"" . $dcont . "\"></iframe></details><br>";
} elsif (index($inurl, "www.wikipedia.") >= 0) {
$outurl =~ s/www\./${lang}\./ig;
$rest .= "<br><details id=drest><summary><h3><a target=_blank href=$inurl>$inurl</a>&nbsp;&nbsp;<a target=_blank href=$outurl>$outurl</a></h3></summary><br><iframe style=width:100%;height:900px; srcdoc=\"" . $dcont . "\"></iframe></details><br>";
} elsif (index($inurl, "/wikipedia.") >= 0) {
$outurl =~ s/\/wikipedia\./\/${lang}\.wikipedia\./ig;
$rest .= "<br><details id=drest><summary><h3><a target=_blank href=$inurl>$inurl</a>&nbsp;&nbsp;<a target=_blank href=$outurl>$outurl</a></h3></summary><br><iframe style=width:100%;height:900px; srcdoc=\"" . $dcont . "\"></iframe></details><br>";
} else {
$rest .= "<br><details id=drest><summary><h3><a target=_blank href=$inurl>$inurl</a></h3></summary><br><iframe style=width:100%;height:900px; srcdoc=\"" . $dcont . "\"></iframe></details><br>";
}
}
#else {
# die $response->status_line;
#}
}
$blogp = $FORM{blogp};
$blogp =~ s/%2C/,/ig;
$blogi = $blogp;
my $blogt = $FORM{blogt};
$blogt =~ s/%2C/,/ig;
$oneletter = substr( $first_name, 0, 1 );

#my $uemoji = Unicode::Escape->new($FORM{emoji});
my $emoji = chr(0x0001F517); # "\xf0\x9f\x98\x80"; #$uemoji->unescape;
#my $ucutei = Unicode::Escape->new($FORM{cutei});
my $cutei = chr(0x0001F3C3); # "\xf0\x9f\x98\x80"; #$ucutei->unescape;
#my $uimgei = Unicode::Escape->new($FORM{imgei});
my $imgei = chr(0x0001F5BC); # "\xf0\x9f\x98\x80"; #$uimgei->unescape;

$dt = DateTime->now; # same as ( epoch => time )

$dttz = DateTime::TimeZone->new( name => 'local' )->name();

$dt->set_time_zone( $dttz );

$year = $dt->year;
$month = $dt->month; # 1-12

$day = $dt->day; # 1-31

$dow = $dt->day_of_week; # 1-7 (Monday is 1)

$hour = $dt->hour; # 0-23
$minute = $dt->minute; # 0-59

$second = $dt->second; # 0-61 (leap seconds!)

$doy = $dt->day_of_year; # 1-366 (leap years)

$doq = $dt->day_of_quarter; # 1..

$qtr = $dt->quarter; # 1-4

$dmy = $dt->dmy('/'); # 06/12/2002

$hms = $dt->hms; # 14:02:29

my $utt = "";
my $bigtt = "";
$tt = "";
$cont = "";
$oneletter = " ";

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "<script type=text/javascript>";
print " var ls='', ns='', qwr='', wo=null, hears=[], vsexthears=[], exthears=[], jd=0, yes=false, lhear='', lang='${lang}', latestu=''; ";
print " function windowopen(p1,p2,p3) { ";
print " if (lang != '') { window.open('https://translate.google.com/?sl=en&tl=' + lang + '&text=' + encodeURIComponent(document.getElementById('mya').innerHTML) + '&op=translate',p2,'top=200,left=200,width=800,height=800'); } ";
print " return window.open(p1,p2,p3); ";
print " } ";
print " function zeroize(iinsf) { var insf=iinsf; var sep='/', i=0; while (insf.substring(i).substring(0,1) >= '0' && insf.substring(i).substring(0,1) <= '9') { i++; } sep=insf.substring(i).substring(0,1); ";
print " var arr=insf.split(sep); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(sep + arr[1] + sep, sep + '0' + arr[1] + sep); } ";
print " if (eval('' + arr[0].length) == 1) { insf='0' + insf; } ";
print " arr=insf.split(' ')[1].split(':'); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (insf.indexOf(' pm') != -1) { insf=insf.replace(' ' + arr[0].trim() + ':', ' ' + eval(12 + eval('' + arr[0].trim())) + ':').replace(' pm', ' '); arr=insf.split(' ')[1].split(':'); } ";
print " if (eval(-1 + eval('' + arr[1])) == eval('' + document.getElementById('mystime').innerHTML.split(':')[1])) { insf=insf.replace(':' + arr[1] + ':', ':' + document.getElementById('mystime').innerHTML.split(':')[1] + ':'); arr[1]='zz'; } ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(':' + arr[1] + ':', ':0' + arr[1] + ':'); } ";
print " if (eval('' + arr[0].trim().length) == 1) { insf=insf.replace(arr[0].trim() + ':', '0' + arr[0].trim() + ':'); } ";
print " } ";
print " } ";
print " return insf; ";
print " } ";
print " function loctime() { if (ls == '') { hearall(); ";
print " qwr='' + Intl.DateTimeFormat().resolvedOptions().timeZone; ";
print " var d = new Date(); ";
print " d.toLocaleString('en-US', { timeZone: qwr }); ";
print " ns=document.getElementById('mystime').innerHTML.split(':')[2].split(' ')[0]; ";
print " ls=zeroize(('' + d.toLocaleString()).replace(',','')) + ' <a onclick=alert(qwr); style=cursor:pointer;text-decoration:underline;>GMT' + d.toString().split(' GMT')[1] + '</a>'; } if (!document.getElementById('mytime')) { setTimeout(loctime,1000); } else { ";
print " document.getElementById('mytime').innerHTML=ls.replace(':' + ls.split(':')[2].split(' ')[0] + ' ', ':' + ns + ' '); } ";
#print " window.open('HTTP://localhost:8888/macos_say_record.php?docronwork=say%20Hello%20$first_name%20$last_name','_blank','top=150,left=50,width=50,height=50'); ";
print " if (lang != '') { ";
print " var alst=document.getElementsByTagName('a'); ";
print " for (var ia=0; ia<alst.length; ia++) { ";
print " if (alst[ia].outerHTML.indexOf('_blank') != -1 && ('' + alst[ia].href) != '' && alst[ia].outerHTML.indexOf('rjmprogramming.com.au/ITblog') != -1) { ";
print " alst[ia].title='Click also opens Google Translated content'; ";
print " alst[ia].setAttribute('data-nongt', alst[ia].href); ";
#print " alst[ia].setAttribute('data-gt', 'https://www-rjmprogramming-com-au.translate.goog/ITblog/' + alst[ia].innerHTML.toLowerCase().replace(/\ /g,'-') + '/?_x_tr_sl=en&_x_tr_tl=' + lang + '&_x_tr_hl=en-GB&_x_tr_pto=nui'); ";
print " alst[ia].setAttribute('data-gt', 'https://www-rjmprogramming-com-au.translate.goog/ITblog/' + alst[ia].innerHTML.toLowerCase().replace('+','').replace('/','').replace(' ','-').replace('/','').replace(' ','-').replace('/','').replace(' ','-').replace('/','').replace(' ','-').replace('/','').replace(' ','-').replace(' ','-').replace(' ','-').replace(' ','-').replace(' ','-').replace(' ','-').replace(/---/g,'-').replace(/--/g,'-').replace(/\ /g,'-') + '/?_x_tr_sl=en&_x_tr_tl=' + lang + '&_x_tr_hl=en-GB&_x_tr_pto=nui'); ";
print " alst[ia].onclick = function(evt){ onc(evt.target); };";
print " alst[ia].href = 'https://www-rjmprogramming-com-au.translate.goog/ITblog/' + alst[ia].innerHTML.toLowerCase().replace(/\ /g,'-') + '/?_x_tr_sl=en&_x_tr_tl=' + lang + '&_x_tr_hl=en-GB&_x_tr_pto=nui'; ";
print " } ";
print " } ";
print " } ";
print " } ";
print " function postonc() { ";
print " if (latestu != '') { window.open(latestu,'mywif'); document.getElementById('premywif').style.display='block'; document.getElementById('mywif').style.display='block'; document.getElementById('premywif').scrollIntoView(); } latestu=''; ";
print " } ";
print " function onc(thisa) { ";
print " latestu=('' + thisa.getAttribute('data-nongt')).replace('null','').replace('undefined',''); setTimeout(postonc, 3000); ";
print " } ";
print " function ihit(proposed) { ";
print " var beg=proposed.split('<')[0].split('[')[0]; var prebegs=proposed.split('<?php'); for (var jjj=1; jjj<prebegs.length; jjj++) { proposed=proposed.replace('<?php' + prebegs[jjj].split('?>')[0] + '?>', 'code'); } prebegs=proposed.split('&#'); for (jjj=1; jjj<prebegs.length; jjj++) { proposed=proposed.replace('&#' + prebegs[jjj].split(';')[0] + ';', ' '); } var begs=proposed.split('>'); for (var jj=1; jj<begs.length; jj++) { if (begs[jj].indexOf('</code') != -1) { beg+=' code'; } else { beg+=' ' + begs[jj].split('<')[0].split('[')[0]; } } ";
print " return beg; } ";
print " function closeit() { if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } if (yes && hears.length > 0) { hear(hears[0]); hears.shift(); } else if (yes) { yes=false; hears=exthears; } return ''; } setTimeout(closeit, 15000); ";
print " } ";
print " function exthear(xwhat) { lhear=''; var what=xwhat; for (var iijj=0; iijj<vsexthears.length; iijj++) { if (1 == 2 && xwhat.toLowerCase().trim().indexOf(vsexthears[iijj].toLowerCase().trim()) == -1) { alert(xwhat + ' does not contain ' + vsexthears[iijj].toLowerCase().trim()); } else if (xwhat.toLowerCase().trim().indexOf(vsexthears[iijj].toLowerCase().trim()) != -1) { what=exthears[iijj]; while (what.indexOf(String.fromCharCode(10)) != -1) { what=what.replace(String.fromCharCode(10),' '); } while (what.indexOf(String.fromCharCode(39)) != -1) { what=what.replace(String.fromCharCode(39),''); } while (what.indexOf(String.fromCharCode(34)) != -1) { what=what.replace(String.fromCharCode(34),' '); } while (what.indexOf('(') != -1) { what=what.replace('(',' '); } while (what.indexOf(')') != -1) { what=what.replace(')',' '); } while (what.indexOf(' ') != -1) { what=what.replace(' ',' '); } while (what.indexOf(' ') != -1) { what=what.replace(' ',' '); } } } lhear=''; if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } } wo=window.open('HTTP://localhost:8888/macos_say_record.php?docronwork=say${voice}%20' + encodeURIComponent(what.split('($#@!')[0]).substring(0,600),'_blank','top=150,left=50,width=50,height=50'); setTimeout(closeit, 65000); ";
print " } ";
print " function lhears() { what=lhear; if (what == '') { return ''; } if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } } wo=window.open('HTTP://localhost:8888/macos_say_record.php?docronwork=say${voice}%20' + encodeURIComponent(what),'_blank','top=150,left=50,width=50,height=50'); setTimeout(closeit, 15000); ";
print " } ";
print " function hear(what) { if (lhear == '') { lhear=what; setTimeout(lhears, 4000); } if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } } wo=window.open('HTTP://localhost:8888/macos_say_record.php?docronwork=say${voice}%20' + encodeURIComponent(what),'_blank','top=150,left=50,width=50,height=50'); setTimeout(closeit, 15000); ";
print " } ";
print " function hearall() { var dasis=document.getElementsByTagName('div'); var asis=document.getElementsByTagName('button'); var thisjd=0; jd=0; while (thisjd < dasis.length && ('' + dasis[thisjd].className) != 'divcont') { thisjd++; } jd=thisjd; for (var ii=0; ii<asis.length; ii++) { if (('' + asis[ii].className) == 'hear') { vsexthears.push((asis[ii].getAttribute('data-alt'))); exthears.push(ihit(asis[ii].getAttribute('data-alt') + ' ' + dasis[jd].innerHTML)); hears.push(asis[ii].getAttribute('data-alt')); thisjd++; while (thisjd < dasis.length && ('' + dasis[thisjd].className) != 'divcont') { thisjd++; } jd=thisjd; } } ";
print " } ";
print "</script>";
print "</head>";
print "<body onload=setTimeout(loctime,1000);>";
print "<h2 style='font-family:Courier New;'><span id=myspan><a ondblclick='yes=true; setTimeout(hearall,1000);' id=mya title='MacOS MAMP HTTP://localhost:8888/macos_say_record.php text to audio ... download instructions, as relevant, can be determined via a read of https://www.rjmprogramming.com.au/ITblog/mamp-timekeeping-web-application-visibility-tutorial/ ... double click for all Tutorial Title audios, also, sequenced' style=cursor:pointer;background-color:lightgreen; onclick=\" if (wo) { return ''; } if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } } wo=windowopen('HTTP://localhost:8888/macos_say_record.php?docronwork=say${voice}%20Hello%20$first_name%20$last_name','_blank','top=150,left=50,width=50,height=50'); setTimeout(closeit, 15000); \">Hello $first_name $last_name</a></span><br>&nbsp;Local: <span id=mytime></span><br>Server: <span id=mystime>$dmy $hms</span> $dttz </h2><h4>";

if ($blogp == "") {
$blogp = $first_name;
$oneletter = substr( $blogp, 0, 1 );
}

if ($blogp != "") {
$oneletter = substr( $blogp, 0, 1 );

if ((ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) || ord($oneletter) == 40 ){
my ($oneurl) = split /,/, $blogp;

if ($oneurl == $blogp) {
$oneletter = substr( $blogp, 0, 1 );
} else {
if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) {
$oneletter = "1";
$blogp = "( $blogp )";
} else {
$oneletter = "2";
}
}

}
}

if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")){
# /*** mysql hostname ***/
$hostname = 'localhost';

# /*** mysql username ***/
$username = 'rjmprogr_root';
$username = 'root';

# /*** mysql ***/
$password = 'mypasswd';
$password = 'krU|KaJy@g_$4';

$dbname = 'rjmprogr_wordpress';
$dbname = 'itblog';

$tname = 'wp_posts';
$tname = 'wps_posts';
$hostname = "DBI:mysql:$dbname:$hostname";

$dbh = DBI->connect($hostname, $username, $password);

my ($oneaurl) = split /,/, $blogp;
if (index($blogp, ',') <= 0) {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID=?");
} else {
if (ord($oneletter) != 40) {
$blogp = "($blogp)";
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
} else {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
}
}

if ($blogp == "") {
$sth->execute();
} else {
$sth->execute( $blogp );
}

$one = 0;
$two = 10;
$exc = 0;
$coln = "A";
$dcol = 1;
$rown = 6;
$trown = 6;
$alinkis = "";
my $pdf = 0;
my $workbook = 0; # Spreadsheet::WriteExcel->new('../perl.xls');
my $date_format = 0;
my $date = 0;
my $innards = "";
my $jinn = "";
if (defined $FORM{jinn}) {
$innards = $FORM{jinn};
}
my $myrelinnards = "";

# Set the default format for dates.

while (($tt, $cont, $iid) = $sth->fetchrow_array()) {
$jinn = "d${idd}";
my ($idis) = split /,/, $blogi, 1;
my ($yyyymmdd) = substr( $blogt, $one, $two ); # split /,/, $blogt, 1;
my ($junk, $imageu) = split / src="/, $cont;
my ($imageurl) = split /"/, $imageu;
my ($junk, $cutto) = split / href="/, $cont;
my ($cuttothechase) = split /"/, $cutto;
if (length($innards) > 0) {
if (index(substr($innards, (index($innards, " djzx${iid} ") + length(" djzx${iid} "))), $tt) == 0) {
$myrelinnards = substr($innards, (index($innards, " djzx${iid} ") + length(" djzx${iid} "))); # split / djzx${iid} /, $innards;
} else {
$myrelinnards = "$tt " . substr($innards, (index($innards, " djzx${iid} ") + length(" djzx${iid} "))); # split / djzx${iid} /, $innards;
}
if (index($myrelinnards, " djzx") >= 0) {
$myrelinnards = substr($myrelinnards, 0, index($myrelinnards, " djzx"));
}
}
if ($lang eq "") {
$utt = "";
} else {
$utt = lc $tt;
$utt =~ s/\+//ig;
$utt =~ s/\///ig;
$utt =~ s/\ /-/ig;
$utt =~ s/\-\-\-/\-/ig;
$bigtt = "https://www-rjmprogramming-com-au.translate.goog/ITblog/" . $utt . "/?_x_tr_sl=en&_x_tr_tl=" . $lang . "&_x_tr_hl=en-GB&_x_tr_pto=nui";
}
$blogt = substr( $blogt, 11 );
if ($exc == 0) {
$exc = 1;

#my $pdf = PDF::Create->new(
# 'filename' => '../perl.pdf',
# 'Author' => "$first_name $last_name",
# 'Title' => 'Sample PDF',
# 'CreationDate' => [ localtime ]
#);

# Add a A4 sized page
#my $root = $pdf->new_page('MediaBox' => $pdf->get_page_size('A4'));

# Add a page which inherits its attributes from $root
#my $page1 = $root->new_page;

# Prepare a font
#my $font = $pdf->font('BaseFont' => 'Helvetica');

# Prepare a Table of Content
#my $toc = $pdf->new_outline('Title' => 'Title Page', 'Destination' => $page1);

# Create a new Excel workbook
$workbook = Spreadsheet::WriteExcel->new('../perl.xls');

# Add a worksheet
$worksheet = $workbook->add_worksheet();
$worksheet->set_column(0, 0, 90);
$worksheet->set_column(1, 0, 30);

# Add and define a format
$format = $workbook->add_format(); # Add a format
$format->set_bold();
$format->set_color('red');
$format->set_align('center');

$formatb = $workbook->add_format(); # Add a format
$formatb->set_bold();
$formatb->set_color('black');

# my $date_format = $workbook->add_format({num_format => 'yyyy-mm-ddThh:mm:ss.sss'});
$date_format = $workbook->add_format(
bold => 1,
align => 'center',
num_format => 'yyyy-mm-dd hh:mm'
);

# Write a formatted and unformatted string, row and column notation.
$col = $row = 0;
$worksheet->write($row, $col, "$first_name $last_name", $format);
$worksheet->write(1, $col, 'My Study Guide', $format);

# Write some text
#$page1->stringc($font, 40, 306, 426, "$first_name $last_name");
#$page1->stringc($font, 20, 306, 396, "My Study Guide");
##$page1->stringc($font, 20, 306, 300, 'by John Doe <john.doe@example.com>');

# my $status = system("open HTTP://localhost:8888/macos_say_record.php?docronwork=say%20$first_name%20$last_name");

# Write a number and a formula using A1 notation
if ($lang eq "") {
$worksheet->write("${coln}3", "$tt");
} else {
$worksheet->write_url("${coln}3", $bigtt, "$tt", $formatb);
}
if (length($myrelinnards) > 0) {
$myrelinnards =~ s/%20/ /ig;
$myrelinnards =~ s/%2D/-/ig;
$myrelinnards =~ s/%2d/-/ig;
$worksheet->write_url("C3", "HTTP://localhost:8888/macos_say_record.php?docronwork=say${voice}%20$myrelinnards", chr(0x0001F442), $formatb);
}
$date = sprintf "%sT03:00:00.000Z", $yyyymmdd;
$worksheet->write_date_time(2, $dcol, $date, $date_format);
$worksheet->write("${coln}4", "https://www.rjmprogramming.com.au/ITblog/?p=$iid" . "#$emoji");
$date = sprintf "%sT03:01:00.000Z", $yyyymmdd;
$worksheet->write_date_time(3, $dcol, $date, $date_format);
$worksheet->write("${coln}5", "$cuttothechase" . "#$cutei");
$date = sprintf "%sT03:02:00.000Z", $yyyymmdd;
$worksheet->write_date_time(4, $dcol, $date, $date_format);
$worksheet->write("${coln}6", "$imageurl" . "#$imgei");
$date = sprintf "%sT03:03:00.000Z", $yyyymmdd;
$worksheet->write_date_time(5, $dcol, $date, $date_format);
$alinkis = "<a download=perl.xls href='//www.rjmprogramming.com.au/perl.xls' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<button data-alt=\"$tt\" class=hear style=cursor:pointer;background-color:lightgreen;display:inline-block; ondblclick=\"exthear('$tt');\" onclick=\"hear('$tt');\" data-href='//www.rjmprogramming.com.au/perl.pdf' title='Hear This Perhaps ... relies on MacOS MAMP HTTP://localhost:8888/macos_say_record.php text to audio ... download instructions, as relevant, can be determined via a read of https://www.rjmprogramming.com.au/ITblog/mamp-timekeeping-web-application-visibility-tutorial/ ... double click tries audio into the wording of the blog posting content'>&#128066;</button>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details id=myd><summary style=background-color:#f0f0f0; id=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary><div class=divcont>$cont</div></details>\n";
} else {
$trown += 4;
$date = sprintf "%sT03:00:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
if ($lang eq "") {
$worksheet->write("${coln}${rown}", "$tt");
} else {
$worksheet->write_url("${coln}${rown}", $bigtt, "$tt", $formatb);
}
if (length($myrelinnards) > 0) {
$myrelinnards =~ s/%20/ /ig;
$myrelinnards =~ s/%2D/-/ig;
$myrelinnards =~ s/%2d/-/ig;
$worksheet->write_url("C${rown}", "HTTP://localhost:8888/macos_say_record.php?docronwork=say${voice}%20$myrelinnards", chr(0x0001F442), $formatb);
}
$date = sprintf "%sT03:01:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "https://www.rjmprogramming.com.au/ITblog/?p=$iid" . "#$emoji");
$date = sprintf "%sT03:02:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "$cuttothechase" . "#$cutei");
$date = sprintf "%sT03:03:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "$imageurl" . "#$imgei");
$alinkis = "<a download=perl.xls href='//www.rjmprogramming.com.au/perl.xls' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<button data-alt=\"$tt\" class=hear style=cursor:pointer;background-color:lightgreen;display:inline-block; ondblclick=\"exthear('$tt');\" onclick=\"hear('$tt');\" data-href='//www.rjmprogramming.com.au/perl.pdf' title='Hear This Perhaps ... relies on MacOS MAMP HTTP://localhost:8888/macos_say_record.php text to audio ... download instructions, as relevant, can be determined via a read of https://www.rjmprogramming.com.au/ITblog/mamp-timekeeping-web-application-visibility-tutorial/ ... double click tries audio into the wording of the blog posting content'>&#128066;</button>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details class=myd><summary style=background-color:#f0f0f0; class=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary><div class=divcont>$cont</div></details>\n";
}
# print "@row\n";
}
# }
}

print "</h4>" . $rest . "<br><br><iframe id=myif src='/hello_get.html' style='width:100%; height:1500px;'></iframe><br><a href='#myspan' title='Back to top' id=premywif style=display:none;>&#11014; Back to top</a><br><iframe id=mywif name=mywif src='' style='display:none; width:100%; height:1500px;'></iframe></body>";
print "</html>";

1;

… in the changed Perl hello_get.cgi code supervised by (and working with) the changed HTML hello_get.html web application we hope you (re-)try for yourself.


Previous relevant Perl CGI Intranet Audio Tutorial is shown below.

Perl CGI Intranet Audio Tutorial

Perl CGI Intranet Audio Tutorial

We’ve got a couple of changes onto yesterday’s Perl CGI URL Content Tutorial‘s progress regarding our Perl CGI Modules explorations …

  • base the navigation to Perl as HTML form method=POST rather than method=GET … allowing for larger data sets … and …
  • if you can …
    1. be on macOS
    2. be on an actively started MAMP local Apache/PHP/MySql web server that uses port 8888 for the HTTP: protocol parts of the access
    3. have downloaded the necessary inhouse code (primarily macos_say_record.php)

    … we can offer you text to audio via an Intranet arrangement accessing the macOS say command line command

… within the Perl Code …


#!/usr/bin/perl

use DateTime;
use DateTime::TimeZone;
use DBI;
use DBD::mysql;
use Spreadsheet::WriteExcel;
use Data::Dumper qw(Dumper);
use LWP::UserAgent ();
#use PDF::Create;
use utf8;
#use Unicode::Escape;

local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

if ($ENV{'REQUEST_METHOD'} eq "GET") {
$buffer = $ENV{'QUERY_STRING'};
} elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
read (STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}


# Split information into name/value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}

my $rest = "";
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
$inurl = $FORM{inurl};
my $before_page = "";
my $allbutlastbit = "";
my $lastbit = (split '/', $ENV{REQUEST_URI})[-1];
my $page_url = 'http';
$page_url.='s' if $ENV{HTTPS};
$page_url.='://';
if ($ENV{SERVER_PORT} != 80) {
$before_page="$ENV{SERVER_NAME}:$ENV{SERVER_PORT}/";
$page_url.="$ENV{SERVER_NAME}:$ENV{SERVER_PORT}$ENV{REQUEST_URI}";
} else {
$before_page="$ENV{SERVER_NAME}/";
$page_url.="$ENV{SERVER_NAME}.$ENV{REQUEST_URI}";
}
if (length($lastbit) > 0) {
$allbutlastbit = substr($page_url, 0, (length($page_url) - length($lastbit)));
} else {
$allbutlastbit = $page_url;
}

if (length($inurl) == 0) {
$inurl = $inurl;
} else {
$inurl =~ s/%3A/:/ig;
$inurl =~ s/%2F/\//ig;
$inurl =~ s/%3F/?/ig;
$inurl =~ s/%26/&/ig;
my $ipage_url = $inurl;
my $ibefore_page = "";
my $iallbutlastbit = "";
my $ilastbit = (split '/', $inurl)[-1];
my $lenseven = (7 + length($ilastbit));
my $leneight = (8 + length($ilastbit));
my $leni = length($inurl);
if (length($ilastbit) > 0) {
if ($lenseven == $leni) {
$iallbutlastbit = "${inurl}/";
} elsif ($leneight == $leni) {
$iallbutlastbit = "${inurl}/";
} else {
$iallbutlastbit = substr($ipage_url, 0, (length($ipage_url) - length($ilastbit)));
}
} else {
$iallbutlastbit = $ipage_url;
}

my $ua = LWP::UserAgent->new(timeout => 10);
$ua->env_proxy;

my $response = $ua->get($inurl);

if ($response->is_success) {
my $dcont = $response->decoded_content;
#$dcont =~ s/html\>/div\>/ig;
#$dcont =~ s/body\>/div\>/ig;
$dcont =~ s/"\/\//&#34;\/\//ig;
$dcont =~ s/"http/&#34;http/ig;
$dcont =~ s/"file/&#34;file/ig;
$dotdot = "..\/";
if (index($dcont, "rjmprogramming.com.au") >= 0) {
$allbutlastbit =~ s/:443//ig;
$allbutlastbit =~ s/\/cgi-bin\//\//ig;
if (substr($allbutlastbit, -1, 1) == "/") {
$allbutlastbit = substr($allbutlastbit, 0, (-1 + length($allbutlastbit)));
}
$dcont =~ s/"\//&#34;${allbutlastbit}\//ig;
#$dcont =~ s/ src="/ src="..\//ig;
#$dcont =~ s/ href="/ href="..\//ig;
$dcont =~ s/ src="/ src="${dotdot}/ig;
$dcont =~ s/ action="/ action="${dotdot}/ig;
$dcont =~ s/ srcset="/ srcset="${dotdot}/ig;
$dcont =~ s/ href="/ href="${dotdot}/ig;
} else {
if (index($dcont, "wikipedia.org") >= 0) {
$dotdot =~ s/\/wiki\//\//ig;
${iallbutlastbit} =~ s/\/wiki\//\//ig;
} else {
$dotdot = $iallbutlastbit;
}
if (substr($iallbutlastbit, -1, 1) == "/") {
$iallbutlastbit = substr($iallbutlastbit, 0, (-1 + length($iallbutlastbit)));
}
$dcont =~ s/"\//&#34;${iallbutlastbit}\//ig;
$dcont =~ s/ src="/ src="${dotdot}/ig;
$dcont =~ s/ srcset="/ srcset="${dotdot}/ig;
$dcont =~ s/ action="/ action="${dotdot}/ig;
$dcont =~ s/ href="/ href="${dotdot}/ig;
$dcont =~ s/url\("/url\("${dotdot}/ig;
$dcont =~ s/url\(portal\//url\(${dotdot}portal\//ig;
$dcont =~ s/url\(static\//url\(${dotdot}static\//ig;
$dcont =~ s/url\(wiki\//url\(${dotdot}wiki\//ig;
$dcont =~ s/url\(er\//url\(${dotdot}er\//ig;
}
$dcont =~ s/"/&#34;/ig;
$dcont =~ s/\r\n//ig;
$dcont =~ s/\n//ig;
$dcont =~ s/\r//ig;
# print "Content-type: text/html\n\n";
$rest .= "<br><details id=drest><summary><h3><a target=_blank href=$inurl>$inurl</a></h3></summary><br><iframe style=width:100%;height:900px; srcdoc=\"" . $dcont . "\"></iframe></details><br>";
}
#else {
# die $response->status_line;
#}
}
$blogp = $FORM{blogp};
$blogp =~ s/%2C/,/ig;
$blogi = $blogp;
my $blogt = $FORM{blogt};
$blogt =~ s/%2C/,/ig;
$oneletter = substr( $first_name, 0, 1 );

#my $uemoji = Unicode::Escape->new($FORM{emoji});
my $emoji = chr(0x0001F517); # "\xf0\x9f\x98\x80"; #$uemoji->unescape;
#my $ucutei = Unicode::Escape->new($FORM{cutei});
my $cutei = chr(0x0001F3C3); # "\xf0\x9f\x98\x80"; #$ucutei->unescape;
#my $uimgei = Unicode::Escape->new($FORM{imgei});
my $imgei = chr(0x0001F5BC); # "\xf0\x9f\x98\x80"; #$uimgei->unescape;

$dt = DateTime->now; # same as ( epoch => time )

$dttz = DateTime::TimeZone->new( name => 'local' )->name();

$dt->set_time_zone( $dttz );

$year = $dt->year;
$month = $dt->month; # 1-12

$day = $dt->day; # 1-31

$dow = $dt->day_of_week; # 1-7 (Monday is 1)

$hour = $dt->hour; # 0-23
$minute = $dt->minute; # 0-59

$second = $dt->second; # 0-61 (leap seconds!)

$doy = $dt->day_of_year; # 1-366 (leap years)

$doq = $dt->day_of_quarter; # 1..

$qtr = $dt->quarter; # 1-4

$dmy = $dt->dmy('/'); # 06/12/2002

$hms = $dt->hms; # 14:02:29

$tt = "";
$cont = "";
$oneletter = " ";

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "<script type=text/javascript>";
print " var ls='', ns='', qwr='', wo=null, hears=[], vsexthears=[], exthears=[], jd=0, yes=false, lhear=''; ";
print " function zeroize(iinsf) { var insf=iinsf; var sep='/', i=0; while (insf.substring(i).substring(0,1) >= '0' && insf.substring(i).substring(0,1) <= '9') { i++; } sep=insf.substring(i).substring(0,1); ";
print " var arr=insf.split(sep); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(sep + arr[1] + sep, sep + '0' + arr[1] + sep); } ";
print " if (eval('' + arr[0].length) == 1) { insf='0' + insf; } ";
print " arr=insf.split(' ')[1].split(':'); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (insf.indexOf(' pm') != -1) { insf=insf.replace(' ' + arr[0].trim() + ':', ' ' + eval(12 + eval('' + arr[0].trim())) + ':').replace(' pm', ' '); arr=insf.split(' ')[1].split(':'); } ";
print " if (eval(-1 + eval('' + arr[1])) == eval('' + document.getElementById('mystime').innerHTML.split(':')[1])) { insf=insf.replace(':' + arr[1] + ':', ':' + document.getElementById('mystime').innerHTML.split(':')[1] + ':'); arr[1]='zz'; } ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(':' + arr[1] + ':', ':0' + arr[1] + ':'); } ";
print " if (eval('' + arr[0].trim().length) == 1) { insf=insf.replace(arr[0].trim() + ':', '0' + arr[0].trim() + ':'); } ";
print " } ";
print " } ";
print " return insf; ";
print " } ";
print " function loctime() { if (ls == '') { hearall(); ";
print " qwr='' + Intl.DateTimeFormat().resolvedOptions().timeZone; ";
print " var d = new Date(); ";
print " d.toLocaleString('en-US', { timeZone: qwr }); ";
print " ns=document.getElementById('mystime').innerHTML.split(':')[2].split(' ')[0]; ";
print " ls=zeroize(('' + d.toLocaleString()).replace(',','')) + ' <a onclick=alert(qwr); style=cursor:pointer;text-decoration:underline;>GMT' + d.toString().split(' GMT')[1] + '</a>'; } if (!document.getElementById('mytime')) { setTimeout(loctime,1000); } else { ";
print " document.getElementById('mytime').innerHTML=ls.replace(':' + ls.split(':')[2].split(' ')[0] + ' ', ':' + ns + ' '); } ";
#print " window.open('HTTP://localhost:8888/macos_say_record.php?docronwork=say%20Hello%20$first_name%20$last_name','_blank','top=150,left=50,width=50,height=50'); ";
print " } ";
print " function ihit(proposed) { ";
print " var beg=proposed.split('<')[0].split('[')[0]; var begs=proposed.split('>'); for (var jj=1; jj<begs.length; jj++) { beg+=' ' + begs[jj].split('<')[0].split('[')[0]; } ";
print " return beg; } ";
print " function closeit() { if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } if (yes && hears.length > 0) { hear(hears[0]); hears.shift(); } return ''; } setTimeout(closeit, 15000); ";
print " } ";
print " function exthear(xwhat) { lhear=''; var what=xwhat; for (var iijj=0; iijj<vsexthears.length; iijj++) { if (1 == 2 && xwhat.toLowerCase().trim().indexOf(vsexthears[iijj].toLowerCase().trim()) == -1) { alert(xwhat + ' does not contain ' + vsexthears[iijj].toLowerCase().trim()); } else if (xwhat.toLowerCase().trim().indexOf(vsexthears[iijj].toLowerCase().trim()) != -1) { what=exthears[iijj]; while (what.indexOf(String.fromCharCode(10)) != -1) { what=what.replace(String.fromCharCode(10),' '); } while (what.indexOf(String.fromCharCode(39)) != -1) { what=what.replace(String.fromCharCode(39),' '); } while (what.indexOf(String.fromCharCode(34)) != -1) { what=what.replace(String.fromCharCode(34),' '); } while (what.indexOf(' ') != -1) { what=what.replace(' ',' '); } while (what.indexOf(' ') != -1) { what=what.replace(' ',' '); } } } lhear=''; if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } } wo=window.open('HTTP://localhost:8888/macos_say_record.php?docronwork=say%20' + encodeURIComponent(what).substring(0,600),'_blank','top=150,left=50,width=50,height=50'); setTimeout(closeit, 65000); ";
print " } ";
print " function lhears() { what=lhear; if (what == '') { return ''; } if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } } wo=window.open('HTTP://localhost:8888/macos_say_record.php?docronwork=say%20' + encodeURIComponent(what),'_blank','top=150,left=50,width=50,height=50'); setTimeout(closeit, 15000); ";
print " } ";
print " function hear(what) { if (lhear == '') { lhear=what; setTimeout(lhears, 4000); } if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } } wo=window.open('HTTP://localhost:8888/macos_say_record.php?docronwork=say%20' + encodeURIComponent(what),'_blank','top=150,left=50,width=50,height=50'); setTimeout(closeit, 15000); ";
print " } ";
print " function hearall() { var dasis=document.getElementsByTagName('div'); var asis=document.getElementsByTagName('button'); var thisjd=0; jd=0; while (thisjd < dasis.length && ('' + dasis[thisjd].className) != 'divcont') { thisjd++; } jd=thisjd; for (var ii=0; ii<asis.length; ii++) { if (('' + asis[ii].className) == 'hear') { vsexthears.push((asis[ii].getAttribute('data-alt'))); exthears.push(ihit(asis[ii].getAttribute('data-alt') + ' ' + dasis[jd].innerHTML)); hears.push(asis[ii].getAttribute('data-alt')); thisjd++; while (thisjd < dasis.length && ('' + dasis[thisjd].className) != 'divcont') { thisjd++; } jd=thisjd; } } ";
print " } ";

print "</script>";
print "</head>";
print "<body onload=setTimeout(loctime,1000);>";
print "<h2 style='font-family:Courier New;'><span id=myspan><a ondblclick='yes=true; setTimeout(hearall,1000);' id=mya title='MacOS MAMP HTTP://localhost:8888/macos_say_record.php text to audio ... download instructions, as relevant, can be determined via a read of https://www.rjmprogramming.com.au/ITblog/mamp-timekeeping-web-application-visibility-tutorial/ ... double click for all Tutorial Title audios, also, sequenced' style=cursor:pointer;background-color:lightgreen; onclick=\" if (wo) { return ''; } if (wo) { if (!wo.closed) { wo.close(); wo=null; } else { wo=null; } } wo=window.open('HTTP://localhost:8888/macos_say_record.php?docronwork=say%20Hello%20$first_name%20$last_name','_blank','top=150,left=50,width=50,height=50'); setTimeout(closeit, 15000); \">Hello $first_name $last_name</a></span><br>&nbsp;Local: <span id=mytime></span><br>Server: <span id=mystime>$dmy $hms</span> $dttz </h2><h4>";

if ($blogp == "") {
$blogp = $first_name;
$oneletter = substr( $blogp, 0, 1 );
}

if ($blogp != "") {
$oneletter = substr( $blogp, 0, 1 );

if ((ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) || ord($oneletter) == 40 ){
my ($oneurl) = split /,/, $blogp;

if ($oneurl == $blogp) {
$oneletter = substr( $blogp, 0, 1 );
} else {
if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) {
$oneletter = "1";
$blogp = "( $blogp )";
} else {
$oneletter = "2";
}
}

}
}

if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")){
# /*** mysql hostname ***/
$hostname = 'dbhost';

# /*** mysql username ***/
$username = 'username';

# /*** mysql ***/
$password = 'password';

$dbname = 'dbname';

$tname = 'table_name';
$hostname = "DBI:mysql:$dbname:$hostname";

$dbh = DBI->connect($hostname, $username, $password);

my ($oneaurl) = split /,/, $blogp;
if (index($blogp, ',') <= 0) {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID=?");
} else {
if (ord($oneletter) != 40) {
$blogp = "($blogp)";
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
} else {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
}
}

if ($blogp == "") {
$sth->execute();
} else {
$sth->execute( $blogp );
}

$one = 0;
$two = 10;
$exc = 0;
$coln = "A";
$dcol = 1;
$rown = 6;
$trown = 6;
$alinkis = "";
my $pdf = 0;
my $workbook = 0; # Spreadsheet::WriteExcel->new('../perl.xls');
my $date_format = 0;
my $date = 0;

# Set the default format for dates.

while (($tt, $cont, $iid) = $sth->fetchrow_array()) {
my ($idis) = split /,/, $blogi, 1;
my ($yyyymmdd) = substr( $blogt, $one, $two ); # split /,/, $blogt, 1;
my ($junk, $imageu) = split / src="/, $cont;
my ($imageurl) = split /"/, $imageu;
my ($junk, $cutto) = split / href="/, $cont;
my ($cuttothechase) = split /"/, $cutto;
$blogt = substr( $blogt, 11 );
if ($exc == 0) {
$exc = 1;

#my $pdf = PDF::Create->new(
# 'filename' => '../perl.pdf',
# 'Author' => "$first_name $last_name",
# 'Title' => 'Sample PDF',
# 'CreationDate' => [ localtime ]
#);

# Add a A4 sized page
#my $root = $pdf->new_page('MediaBox' => $pdf->get_page_size('A4'));

# Add a page which inherits its attributes from $root
#my $page1 = $root->new_page;

# Prepare a font
#my $font = $pdf->font('BaseFont' => 'Helvetica');

# Prepare a Table of Content
#my $toc = $pdf->new_outline('Title' => 'Title Page', 'Destination' => $page1);

# Create a new Excel workbook
$workbook = Spreadsheet::WriteExcel->new('../perl.xlsm');

# Add a worksheet
$worksheet = $workbook->add_worksheet();
$worksheet->set_column(0, 0, 90);
$worksheet->set_column(1, 0, 30);

# Add and define a format
$format = $workbook->add_format(); # Add a format
$format->set_bold();
$format->set_color('red');
$format->set_align('center');
# my $date_format = $workbook->add_format({num_format => 'yyyy-mm-ddThh:mm:ss.sss'});
$date_format = $workbook->add_format(
bold => 1,
align => 'center',
num_format => 'yyyy-mm-dd hh:mm'
);

# Write a formatted and unformatted string, row and column notation.
$col = $row = 0;
$worksheet->write($row, $col, "$first_name $last_name", $format);
$worksheet->write(1, $col, 'My Study Guide', $format);

# Write some text
#$page1->stringc($font, 40, 306, 426, "$first_name $last_name");
#$page1->stringc($font, 20, 306, 396, "My Study Guide");
##$page1->stringc($font, 20, 306, 300, 'by John Doe <john.doe@example.com>');

# my $status = system("open HTTP://localhost:8888/macos_say_record.php?docronwork=say%20$first_name%20$last_name");

# Write a number and a formula using A1 notation
$worksheet->write("${coln}3", "$tt");
$date = sprintf "%sT03:00:00.000Z", $yyyymmdd;
$worksheet->write_date_time(2, $dcol, $date, $date_format);
$worksheet->write("${coln}4", "https://www.rjmprogramming.com.au/ITblog/?p=$iid" . "#$emoji");
$date = sprintf "%sT03:01:00.000Z", $yyyymmdd;
$worksheet->write_date_time(3, $dcol, $date, $date_format);
$worksheet->write("${coln}5", "$cuttothechase" . "#$cutei");
$date = sprintf "%sT03:02:00.000Z", $yyyymmdd;
$worksheet->write_date_time(4, $dcol, $date, $date_format);
$worksheet->write("${coln}6", "$imageurl" . "#$imgei");
$date = sprintf "%sT03:03:00.000Z", $yyyymmdd;
$worksheet->write_date_time(5, $dcol, $date, $date_format);
$alinkis = "<a download=perl.xlsm href='//www.rjmprogramming.com.au/perl.xlsm' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<button data-alt=\"$tt\" class=hear style=cursor:pointer;background-color:lightgreen;display:inline-block; ondblclick=\"exthear('$tt');\" onclick=\"hear('$tt');\" data-href='//www.rjmprogramming.com.au/perl.pdf' title='Hear This Perhaps ... relies on MacOS MAMP HTTP://localhost:8888/macos_say_record.php text to audio ... download instructions, as relevant, can be determined via a read of https://www.rjmprogramming.com.au/ITblog/mamp-timekeeping-web-application-visibility-tutorial/ ... double click tries audio into the wording of the blog posting content'>&#128066;</button>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details id=myd><summary style=background-color:#f0f0f0; id=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary><div class=divcont>$cont</div></details>\n";
} else {
$trown += 4;
$date = sprintf "%sT03:00:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "$tt");
$date = sprintf "%sT03:01:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "https://www.rjmprogramming.com.au/ITblog/?p=$iid" . "#$emoji");
$date = sprintf "%sT03:02:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "$cuttothechase" . "#$cutei");
$date = sprintf "%sT03:03:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "$imageurl" . "#$imgei");
$alinkis = "<a download=perl.xlsm href='//www.rjmprogramming.com.au/perl.xlsm' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<button data-alt=\"$tt\" class=hear style=cursor:pointer;background-color:lightgreen;display:inline-block; ondblclick=\"exthear('$tt');\" onclick=\"hear('$tt');\" data-href='//www.rjmprogramming.com.au/perl.pdf' title='Hear This Perhaps ... relies on MacOS MAMP HTTP://localhost:8888/macos_say_record.php text to audio ... download instructions, as relevant, can be determined via a read of https://www.rjmprogramming.com.au/ITblog/mamp-timekeeping-web-application-visibility-tutorial/ ... double click tries audio into the wording of the blog posting content'>&#128066;</button>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details class=myd><summary style=background-color:#f0f0f0; class=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary><div class=divcont>$cont</div></details>\n";
}
# print "@row\n";
}
# }
}

print "</h4>" . $rest . "<br><br><iframe id=myif src='/hello_get.html' style='width:100%; height:1500px;'></iframe></body>";
print "</html>";

1;

… in the changed Perl hello_get.cgi code supervised by (and working with) the changed HTML hello_get.html web application we hope you (re-)try for yourself.


Previous relevant Perl CGI URL Content Tutorial is shown below.

Perl CGI URL Content Tutorial

Perl CGI URL Content Tutorial

Onto yesterday’s Perl CGI Spreadsheet Module Sorting Tutorial, today, we introduce a new Perl module …


LWP::UserAgent

… which can help us reach the content of a user nominated URL.

From LWP::UserAgent doing it’s stuff, the rest of the changed Perl code below …

  • turns relative references into absolute ones … within an …
  • iframe … with …
  • reworked content placed into the srcdoc attribute … nested in …
  • details/summary (with an “a” link) “reveal” scenario

… in …


#!/usr/bin/perl

use DateTime;
use DateTime::TimeZone;
use DBI;
use DBD::mysql;
use Spreadsheet::WriteExcel;
use Data::Dumper qw(Dumper);
use LWP::UserAgent ();
#use Unicode::Escape;

local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

if ($ENV{'REQUEST_METHOD'} eq "GET") {
$buffer = $ENV{'QUERY_STRING'};
}

# Split information into name/value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}

my $rest = "";
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
$inurl = $FORM{inurl};
my $before_page = "";
my $allbutlastbit = "";
my $lastbit = (split '/', $ENV{REQUEST_URI})[-1];
my $page_url = 'http';
$page_url.='s' if $ENV{HTTPS};
$page_url.='://';
if ($ENV{SERVER_PORT} != 80) {
$before_page="$ENV{SERVER_NAME}:$ENV{SERVER_PORT}/";
$page_url.="$ENV{SERVER_NAME}:$ENV{SERVER_PORT}$ENV{REQUEST_URI}";
} else {
$before_page="$ENV{SERVER_NAME}/";
$page_url.="$ENV{SERVER_NAME}.$ENV{REQUEST_URI}";
}
if (length($lastbit) > 0) {
$allbutlastbit = substr($page_url, 0, (length($page_url) - length($lastbit)));
} else {
$allbutlastbit = $page_url;
}

if (length($inurl) == 0) {
$inurl = $inurl;
} else {
$inurl =~ s/%3A/:/ig;
$inurl =~ s/%2F/\//ig;
$inurl =~ s/%3F/?/ig;
$inurl =~ s/%26/&/ig;
my $ipage_url = $inurl;
my $ibefore_page = "";
my $iallbutlastbit = "";
my $ilastbit = (split '/', $inurl)[-1];
my $lenseven = (7 + length($ilastbit));
my $leneight = (8 + length($ilastbit));
my $leni = length($inurl);
if (length($ilastbit) > 0) {
if ($lenseven == $leni) {
$iallbutlastbit = "${inurl}/";
} elsif ($leneight == $leni) {
$iallbutlastbit = "${inurl}/";
} else {
$iallbutlastbit = substr($ipage_url, 0, (length($ipage_url) - length($ilastbit)));
}
} else {
$iallbutlastbit = $ipage_url;
}

my $ua = LWP::UserAgent->new(timeout => 10);
$ua->env_proxy;

my $response = $ua->get($inurl);

if ($response->is_success) {
my $dcont = $response->decoded_content;
#$dcont =~ s/html\>/div\>/ig;
#$dcont =~ s/body\>/div\>/ig;
$dcont =~ s/"\/\//&#34;\/\//ig;
$dcont =~ s/"http/&#34;http/ig;
$dcont =~ s/"file/&#34;file/ig;
$dotdot = "..\/";
if (index($dcont, "rjmprogramming.com.au") >= 0) {
$allbutlastbit =~ s/:443//ig;
$allbutlastbit =~ s/\/cgi-bin\//\//ig;
if (substr($allbutlastbit, -1, 1) == "/") {
$allbutlastbit = substr($allbutlastbit, 0, (-1 + length($allbutlastbit)));
}
$dcont =~ s/"\//&#34;${allbutlastbit}\//ig;
#$dcont =~ s/ src="/ src="..\//ig;
#$dcont =~ s/ href="/ href="..\//ig;
$dcont =~ s/ src="/ src="${dotdot}/ig;
$dcont =~ s/ action="/ action="${dotdot}/ig;
$dcont =~ s/ srcset="/ srcset="${dotdot}/ig;
$dcont =~ s/ href="/ href="${dotdot}/ig;
} else {
if (index($dcont, "wikipedia.org") >= 0) {
$dotdot =~ s/\/wiki\//\//ig;
${iallbutlastbit} =~ s/\/wiki\//\//ig;
} else {
$dotdot = $iallbutlastbit;
}
if (substr($iallbutlastbit, -1, 1) == "/") {
$iallbutlastbit = substr($iallbutlastbit, 0, (-1 + length($iallbutlastbit)));
}
$dcont =~ s/"\//&#34;${iallbutlastbit}\//ig;
$dcont =~ s/ src="/ src="${dotdot}/ig;
$dcont =~ s/ srcset="/ srcset="${dotdot}/ig;
$dcont =~ s/ action="/ action="${dotdot}/ig;
$dcont =~ s/ href="/ href="${dotdot}/ig;
$dcont =~ s/url\("/url\("${dotdot}/ig;
$dcont =~ s/url\(portal\//url\(${dotdot}portal\//ig;
$dcont =~ s/url\(static\//url\(${dotdot}static\//ig;
$dcont =~ s/url\(wiki\//url\(${dotdot}wiki\//ig;
$dcont =~ s/url\(er\//url\(${dotdot}er\//ig;
}
$dcont =~ s/"/&#34;/ig;
$dcont =~ s/\r\n//ig;
$dcont =~ s/\n//ig;
$dcont =~ s/\r//ig;
# print "Content-type: text/html\n\n";
$rest .= "<br><details id=drest><summary><h3><a target=_blank href=$inurl>$inurl</a></h3></summary><br><iframe style=width:100%;height:900px; srcdoc=\"" . $dcont . "\"></iframe></details><br>";
}
#else {
# die $response->status_line;
#}
}

$blogp = $FORM{blogp};
$blogp =~ s/%2C/,/ig;
$blogi = $blogp;
my $blogt = $FORM{blogt};
$blogt =~ s/%2C/,/ig;
$oneletter = substr( $first_name, 0, 1 );

#my $uemoji = Unicode::Escape->new($FORM{emoji});
my $emoji = chr(0x0001F517); # "\xf0\x9f\x98\x80"; #$uemoji->unescape;
#my $ucutei = Unicode::Escape->new($FORM{cutei});
my $cutei = chr(0x0001F3C3); # "\xf0\x9f\x98\x80"; #$ucutei->unescape;
#my $uimgei = Unicode::Escape->new($FORM{imgei});
my $imgei = chr(0x0001F5BC); # "\xf0\x9f\x98\x80"; #$uimgei->unescape;

$dt = DateTime->now; # same as ( epoch => time )

$dttz = DateTime::TimeZone->new( name => 'local' )->name();

$dt->set_time_zone( $dttz );

$year = $dt->year;
$month = $dt->month; # 1-12

$day = $dt->day; # 1-31

$dow = $dt->day_of_week; # 1-7 (Monday is 1)

$hour = $dt->hour; # 0-23
$minute = $dt->minute; # 0-59

$second = $dt->second; # 0-61 (leap seconds!)

$doy = $dt->day_of_year; # 1-366 (leap years)

$doq = $dt->day_of_quarter; # 1..

$qtr = $dt->quarter; # 1-4

$dmy = $dt->dmy('/'); # 06/12/2002

$hms = $dt->hms; # 14:02:29

$tt = "";
$cont = "";
$oneletter = " ";

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "<script type=text/javascript>";
print " var ls='', ns='', qwr=''; ";
print " function zeroize(iinsf) { var insf=iinsf; var sep='/', i=0; while (insf.substring(i).substring(0,1) >= '0' && insf.substring(i).substring(0,1) <= '9') { i++; } sep=insf.substring(i).substring(0,1); ";
print " var arr=insf.split(sep); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(sep + arr[1] + sep, sep + '0' + arr[1] + sep); } ";
print " if (eval('' + arr[0].length) == 1) { insf='0' + insf; } ";
print " arr=insf.split(' ')[1].split(':'); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (insf.indexOf(' pm') != -1) { insf=insf.replace(' ' + arr[0].trim() + ':', ' ' + eval(12 + eval('' + arr[0].trim())) + ':').replace(' pm', ' '); arr=insf.split(' ')[1].split(':'); } ";
print " if (eval(-1 + eval('' + arr[1])) == eval('' + document.getElementById('mystime').innerHTML.split(':')[1])) { insf=insf.replace(':' + arr[1] + ':', ':' + document.getElementById('mystime').innerHTML.split(':')[1] + ':'); arr[1]='zz'; } ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(':' + arr[1] + ':', ':0' + arr[1] + ':'); } ";
print " if (eval('' + arr[0].trim().length) == 1) { insf=insf.replace(arr[0].trim() + ':', '0' + arr[0].trim() + ':'); } ";
print " } ";
print " } ";
print " return insf; ";
print " } ";
print " function loctime() { if (ls == '') { ";
print " qwr='' + Intl.DateTimeFormat().resolvedOptions().timeZone; ";
print " var d = new Date(); ";
print " d.toLocaleString('en-US', { timeZone: qwr }); ";
print " ns=document.getElementById('mystime').innerHTML.split(':')[2].split(' ')[0]; ";
print " ls=zeroize(('' + d.toLocaleString()).replace(',','')) + ' <a onclick=alert(qwr); style=cursor:pointer;text-decoration:underline;>GMT' + d.toString().split(' GMT')[1] + '</a>'; } if (!document.getElementById('mytime')) { setTimeout(loctime,1000); } else { ";
print " document.getElementById('mytime').innerHTML=ls.replace(':' + ls.split(':')[2].split(' ')[0] + ' ', ':' + ns + ' '); } ";
print " } ";
print "</script>";
print "</head>";
print "<body onload=setTimeout(loctime,1000);>";
print "<h2 style='font-family:Courier New;'>Hello $first_name $last_name <br>&nbsp;Local: <span id=mytime></span><br>Server: <span id=mystime>$dmy $hms</span> $dttz </h2><h4>";

if ($blogp == "") {
$blogp = $first_name;
$oneletter = substr( $blogp, 0, 1 );
}

if ($blogp != "") {
$oneletter = substr( $blogp, 0, 1 );

if ((ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) || ord($oneletter) == 40 ){
my ($oneurl) = split /,/, $blogp;

if ($oneurl == $blogp) {
$oneletter = substr( $blogp, 0, 1 );
} else {
if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) {
$oneletter = "1";
$blogp = "( $blogp )";
} else {
$oneletter = "2";
}
}

}
}

if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")){
# /*** mysql hostname ***/
$hostname = 'dbhost';

# /*** mysql username ***/
$username = 'username';

# /*** mysql ***/
$password = 'password';

$dbname = 'dbname';

$tname = 'table_name';
$hostname = "DBI:mysql:$dbname:$hostname";

$dbh = DBI->connect($hostname, $username, $password);

my ($oneaurl) = split /,/, $blogp;
if (index($blogp, ',') <= 0) {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID=?");
} else {
if (ord($oneletter) != 40) {
$blogp = "($blogp)";
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
} else {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
}
}

if ($blogp == "") {
$sth->execute();
} else {
$sth->execute( $blogp );
}

$one = 0;
$two = 10;
$exc = 0;
$coln = "A";
$dcol = 1;
$rown = 6;
$trown = 6;
$alinkis = "";
my $workbook = 0; # Spreadsheet::WriteExcel->new('../perl.xls');
my $date_format = 0;
my $date = 0;

# Set the default format for dates.

while (($tt, $cont, $iid) = $sth->fetchrow_array()) {
my ($idis) = split /,/, $blogi, 1;
my ($yyyymmdd) = substr( $blogt, $one, $two ); # split /,/, $blogt, 1;
my ($junk, $imageu) = split / src="/, $cont;
my ($imageurl) = split /"/, $imageu;
my ($junk, $cutto) = split / href="/, $cont;
my ($cuttothechase) = split /"/, $cutto;
$blogt = substr( $blogt, 11 );
if ($exc == 0) {
$exc = 1;
# Create a new Excel workbook
$workbook = Spreadsheet::WriteExcel->new('../perl.xlsm');

# Add a worksheet
$worksheet = $workbook->add_worksheet();
$worksheet->set_column(0, 0, 90);
$worksheet->set_column(1, 0, 30);

# Add and define a format
$format = $workbook->add_format(); # Add a format
$format->set_bold();
$format->set_color('red');
$format->set_align('center');
# my $date_format = $workbook->add_format({num_format => 'yyyy-mm-ddThh:mm:ss.sss'});
$date_format = $workbook->add_format(
bold => 1,
align => 'center',
num_format => 'yyyy-mm-dd hh:mm'
);

# Write a formatted and unformatted string, row and column notation.
$col = $row = 0;
$worksheet->write($row, $col, "$first_name $last_name", $format);
$worksheet->write(1, $col, 'My Study Guide');

# Write a number and a formula using A1 notation
$worksheet->write("${coln}3", "$tt");
$date = sprintf "%sT03:00:00.000Z", $yyyymmdd;
$worksheet->write_date_time(2, $dcol, $date, $date_format);
$worksheet->write("${coln}4", "https://www.rjmprogramming.com.au/ITblog/?p=$iid" . "#$emoji");
$date = sprintf "%sT03:01:00.000Z", $yyyymmdd;
$worksheet->write_date_time(3, $dcol, $date, $date_format);
$worksheet->write("${coln}5", "$cuttothechase" . "#$cutei");
$date = sprintf "%sT03:02:00.000Z", $yyyymmdd;
$worksheet->write_date_time(4, $dcol, $date, $date_format);
$worksheet->write("${coln}6", "$imageurl" . "#$imgei");
$date = sprintf "%sT03:03:00.000Z", $yyyymmdd;
$worksheet->write_date_time(5, $dcol, $date, $date_format);
$alinkis = "<a download=perl.xlsm href='//www.rjmprogramming.com.au/perl.xlsm' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details id=myd><summary style=background-color:#f0f0f0; id=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary>$cont</details>\n";
} else {
$trown += 4;
$date = sprintf "%sT03:00:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "$tt");
$date = sprintf "%sT03:01:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "https://www.rjmprogramming.com.au/ITblog/?p=$iid" . "#$emoji");
$date = sprintf "%sT03:02:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "$cuttothechase" . "#$cutei");
$date = sprintf "%sT03:03:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;
$worksheet->write("${coln}${rown}", "$imageurl" . "#$imgei");
$alinkis = "<a download=perl.xlsm href='//www.rjmprogramming.com.au/perl.xlsm' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details class=myd><summary style=background-color:#f0f0f0; class=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary>$cont</details>\n";
}
# print "@row\n";
}
# }
}

print "</h4>" . $rest . "<br><br><iframe id=myif src='/hello_get.html' style='width:100%; height:1500px;'></iframe></body>";
print "</html>";

1;

… in the changed Perl hello_get.cgi code supervised by (and working with) the changed HTML hello_get.html web application we hope you (re-)try for yourself.


Previous relevant Perl CGI Spreadsheet Module Sorting Tutorial is shown below.

Perl CGI Spreadsheet Module Sorting Tutorial

Perl CGI Spreadsheet Module Sorting Tutorial

Spreadsheets can be a great aid where online activities might coincide, via downloading, to desktop activities. So, we want to delve further into the spreadsheet functionality we started with yesterday’s Perl CGI Spreadsheet Module Tutorial.

We decided …

  • to add a second column with timestamps … to facilitate …
  • spreadsheet sorting possibilities via Excel (or LibreOffice) …

    Data -> Sort

    … as well as …
  • column width setting … via …

    $worksheet->set_column(0, 0, 90);
    $worksheet->set_column(1, 0, 30);

    … and …
  • add an emoji hashtag component to the three links associated with each blog posting reference … so that …
    1. the link cells become more self explanatory without the need for any new columns to explain …
    2. we add graphical interest to the spreadsheet data

… in the changed


#!/usr/bin/perl

use DateTime;
use DateTime::TimeZone;
use DBI;
use DBD::mysql;
use Spreadsheet::WriteExcel;
use Data::Dumper qw(Dumper);
#use Unicode::Escape;

local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

if ($ENV{'REQUEST_METHOD'} eq "GET") {
$buffer = $ENV{'QUERY_STRING'};
}

# Split information into name/value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}

$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
$blogp = $FORM{blogp};
$blogp =~ s/%2C/,/ig;
$blogi = $blogp;
my $blogt = $FORM{blogt};
$blogt =~ s/%2C/,/ig;

$oneletter = substr( $first_name, 0, 1 );

#my $uemoji = Unicode::Escape->new($FORM{emoji});
my $emoji = chr(0x0001F517); # "\xf0\x9f\x98\x80"; #$uemoji->unescape;
#my $ucutei = Unicode::Escape->new($FORM{cutei});
my $cutei = chr(0x0001F3C3); # "\xf0\x9f\x98\x80"; #$ucutei->unescape;
#my $uimgei = Unicode::Escape->new($FORM{imgei});
my $imgei = chr(0x0001F5BC); # "\xf0\x9f\x98\x80"; #$uimgei->unescape;


$dt = DateTime->now; # same as ( epoch => time )

$dttz = DateTime::TimeZone->new( name => 'local' )->name();

$dt->set_time_zone( $dttz );

$year = $dt->year;
$month = $dt->month; # 1-12

$day = $dt->day; # 1-31

$dow = $dt->day_of_week; # 1-7 (Monday is 1)

$hour = $dt->hour; # 0-23
$minute = $dt->minute; # 0-59

$second = $dt->second; # 0-61 (leap seconds!)

$doy = $dt->day_of_year; # 1-366 (leap years)

$doq = $dt->day_of_quarter; # 1..

$qtr = $dt->quarter; # 1-4

$dmy = $dt->dmy('/'); # 06/12/2002

$hms = $dt->hms; # 14:02:29

$tt = "";
$cont = "";
$oneletter = " ";

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "<script type=text/javascript>";
print " var ls='', ns='', qwr=''; ";
print " function zeroize(iinsf) { var insf=iinsf; var sep='/', i=0; while (insf.substring(i).substring(0,1) >= '0' && insf.substring(i).substring(0,1) <= '9') { i++; } sep=insf.substring(i).substring(0,1); ";
print " var arr=insf.split(sep); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(sep + arr[1] + sep, sep + '0' + arr[1] + sep); } ";
print " if (eval('' + arr[0].length) == 1) { insf='0' + insf; } ";
print " arr=insf.split(' ')[1].split(':'); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (insf.indexOf(' pm') != -1) { insf=insf.replace(' ' + arr[0].trim() + ':', ' ' + eval(12 + eval('' + arr[0].trim())) + ':').replace(' pm', ' '); arr=insf.split(' ')[1].split(':'); } ";
print " if (eval(-1 + eval('' + arr[1])) == eval('' + document.getElementById('mystime').innerHTML.split(':')[1])) { insf=insf.replace(':' + arr[1] + ':', ':' + document.getElementById('mystime').innerHTML.split(':')[1] + ':'); arr[1]='zz'; } ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(':' + arr[1] + ':', ':0' + arr[1] + ':'); } ";
print " if (eval('' + arr[0].trim().length) == 1) { insf=insf.replace(arr[0].trim() + ':', '0' + arr[0].trim() + ':'); } ";
print " } ";
print " } ";
print " return insf; ";
print " } ";
print " function loctime() { if (ls == '') { ";
print " qwr='' + Intl.DateTimeFormat().resolvedOptions().timeZone; ";
print " var d = new Date(); ";
print " d.toLocaleString('en-US', { timeZone: qwr }); ";
print " ns=document.getElementById('mystime').innerHTML.split(':')[2].split(' ')[0]; ";
print " ls=zeroize(('' + d.toLocaleString()).replace(',','')) + ' <a onclick=alert(qwr); style=cursor:pointer;text-decoration:underline;>GMT' + d.toString().split(' GMT')[1] + '</a>'; } if (!document.getElementById('mytime')) { setTimeout(loctime,1000); } else { ";
print " document.getElementById('mytime').innerHTML=ls.replace(':' + ls.split(':')[2].split(' ')[0] + ' ', ':' + ns + ' '); } ";
print " } ";
print "</script>";
print "</head>";
print "<body onload=setTimeout(loctime,1000);>";
print "<h2 style='font-family:Courier New;'>Hello $first_name $last_name <br>&nbsp;Local: <span id=mytime></span><br>Server: <span id=mystime>$dmy $hms</span> $dttz </h2><h4>";

if ($blogp == "") {
$blogp = $first_name;
$oneletter = substr( $blogp, 0, 1 );
}

if ($blogp != "") {
$oneletter = substr( $blogp, 0, 1 );

if ((ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) || ord($oneletter) == 40 ){
my ($oneurl) = split /,/, $blogp;

if ($oneurl == $blogp) {
$oneletter = substr( $blogp, 0, 1 );
} else {
if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) {
$oneletter = "1";
$blogp = "( $blogp )";
} else {
$oneletter = "2";
}
}

}
}

if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")){
# /*** mysql hostname ***/
$hostname = 'dbhost';

# /*** mysql username ***/
$username = 'username';

# /*** mysql ***/
$password = 'password';

$dbname = 'dbname';

$tname = 'table_name';
$hostname = "DBI:mysql:$dbname:$hostname";

$dbh = DBI->connect($hostname, $username, $password);

my ($oneaurl) = split /,/, $blogp;
if (index($blogp, ',') <= 0) {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID=?");
} else {
if (ord($oneletter) != 40) {
$blogp = "($blogp)";
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
} else {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
}
}

if ($blogp == "") {
$sth->execute();
} else {
$sth->execute( $blogp );
}

$one = 0;
$two = 10;

$exc = 0;
$coln = "A";
$dcol = 1;
$rown = 6;
$trown = 6;
$alinkis = "";
my $workbook = 0; # Spreadsheet::WriteExcel->new('../perl.xls');
my $date_format = 0;
my $date = 0;


# Set the default format for dates.

while (($tt, $cont, $iid) = $sth->fetchrow_array()) {
my ($idis) = split /,/, $blogi, 1;
my ($yyyymmdd) = substr( $blogt, $one, $two ); # split /,/, $blogt, 1;

my ($junk, $imageu) = split / src="/, $cont;
my ($imageurl) = split /"/, $imageu;
my ($junk, $cutto) = split / href="/, $cont;
my ($cuttothechase) = split /"/, $cutto;
$blogt = substr( $blogt, 11 );
if ($exc == 0) {
$exc = 1;
# Create a new Excel workbook
$workbook = Spreadsheet::WriteExcel->new('../perl.xls');

# Add a worksheet
$worksheet = $workbook->add_worksheet();
$worksheet->set_column(0, 0, 90);
$worksheet->set_column(1, 0, 30);


# Add and define a format
$format = $workbook->add_format(); # Add a format
$format->set_bold();
$format->set_color('red');
$format->set_align('center');
# my $date_format = $workbook->add_format({num_format => 'yyyy-mm-ddThh:mm:ss.sss'});
$date_format = $workbook->add_format(
bold => 1,
align => 'center',
num_format => 'yyyy-mm-dd hh:mm'
);


# Write a formatted and unformatted string, row and column notation.
$col = $row = 0;
$worksheet->write($row, $col, "$first_name $last_name", $format);
# $worksheet->write(1, $col, 'Hi Excel!');

# Write a number and a formula using A1 notation
$worksheet->write("${coln}3", "$tt");
$date = sprintf "%sT03:00:00.000Z", $yyyymmdd;
$worksheet->write_date_time(2, $dcol, $date, $date_format);

$worksheet->write("${coln}4", "https://www.rjmprogramming.com.au/ITblog/?p=$iid" . "#$emoji");
$date = sprintf "%sT03:01:00.000Z", $yyyymmdd;
$worksheet->write_date_time(3, $dcol, $date, $date_format);

$worksheet->write("${coln}5", "$cuttothechase" . "#$cutei");
$date = sprintf "%sT03:02:00.000Z", $yyyymmdd;
$worksheet->write_date_time(4, $dcol, $date, $date_format);

$worksheet->write("${coln}6", "$imageurl" . "#$imgei");
$date = sprintf "%sT03:03:00.000Z", $yyyymmdd;
$worksheet->write_date_time(5, $dcol, $date, $date_format);

$alinkis = "<a download=perl.xls href='//www.rjmprogramming.com.au/perl.xls' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details id=myd><summary style=background-color:#f0f0f0; id=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary>$cont</details>\n";
} else {
$trown += 4;
$date = sprintf "%sT03:00:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;

$worksheet->write("${coln}${rown}", "$tt");
$date = sprintf "%sT03:01:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;

$worksheet->write("${coln}${rown}", "https://www.rjmprogramming.com.au/ITblog/?p=$iid" . "#$emoji");
$date = sprintf "%sT03:02:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;

$worksheet->write("${coln}${rown}", "$cuttothechase" . "#$cutei");
$date = sprintf "%sT03:03:00.000Z", $yyyymmdd;
$worksheet->write_date_time($rown, $dcol, $date, $date_format);
$rown += 1;

$worksheet->write("${coln}${rown}", "$imageurl" . "#$imgei");
$alinkis = "<a download=perl.xls href='//www.rjmprogramming.com.au/perl.xls' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details class=myd><summary style=background-color:#f0f0f0; class=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary>$cont</details>\n";
}
# print "@row\n";
}
# }
}

print "</h4><br><br><iframe id=myif src='/hello_get.html' style='width:100%; height:1500px;'></iframe></body>";
print "</html>";

1;

… in the changed Perl hello_get.cgi code supervised by (and working with) the changed HTML hello_get.html web application we hope you try for yourself.


Previous relevant Perl CGI Spreadsheet Module Tutorial is shown below.

Perl CGI Spreadsheet Module Tutorial

Perl CGI Spreadsheet Module Tutorial

Adding onto yesterday’s Perl CGI DBI Module Tutorial

  • use of Perl module DateTime …
  • use of Perl module DBI … Perl module exploration, and today, we dip our toes into …
  • use of Perl module Spreadsheet::WriteExcel … and to help with simulating PHP’s explode function …
  • use of Perl module Data::Dumper and its split function

… with modified Perl code as per …


#!/usr/bin/perl

use DateTime;
use DateTime::TimeZone;
use DBI;
use DBD::mysql;
use Spreadsheet::WriteExcel;
use Data::Dumper qw(Dumper);


local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

if ($ENV{'REQUEST_METHOD'} eq "GET") {
$buffer = $ENV{'QUERY_STRING'};
}

# Split information into name/value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}

$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
$blogp = $FORM{blogp};
$blogp =~ s/%2C/,/ig;
$oneletter = substr( $first_name, 0, 1 );

$dt = DateTime->now; # same as ( epoch => time )

$dttz = DateTime::TimeZone->new( name => 'local' )->name();

$dt->set_time_zone( $dttz );

$year = $dt->year;
$month = $dt->month; # 1-12

$day = $dt->day; # 1-31

$dow = $dt->day_of_week; # 1-7 (Monday is 1)

$hour = $dt->hour; # 0-23
$minute = $dt->minute; # 0-59

$second = $dt->second; # 0-61 (leap seconds!)

$doy = $dt->day_of_year; # 1-366 (leap years)

$doq = $dt->day_of_quarter; # 1..

$qtr = $dt->quarter; # 1-4

$dmy = $dt->dmy('/'); # 06/12/2002

$hms = $dt->hms; # 14:02:29

$tt = "";
$cont = "";
$oneletter = " ";

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "<script type=text/javascript>";
print " var ls='', ns='', qwr=''; ";
print " function zeroize(iinsf) { var insf=iinsf; var sep='/', i=0; while (insf.substring(i).substring(0,1) >= '0' && insf.substring(i).substring(0,1) <= '9') { i++; } sep=insf.substring(i).substring(0,1); ";
print " var arr=insf.split(sep); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(sep + arr[1] + sep, sep + '0' + arr[1] + sep); } ";
print " if (eval('' + arr[0].length) == 1) { insf='0' + insf; } ";
print " arr=insf.split(' ')[1].split(':'); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (insf.indexOf(' pm') != -1) { insf=insf.replace(' ' + arr[0].trim() + ':', ' ' + eval(12 + eval('' + arr[0].trim())) + ':').replace(' pm', ' '); arr=insf.split(' ')[1].split(':'); } ";
print " if (eval(-1 + eval('' + arr[1])) == eval('' + document.getElementById('mystime').innerHTML.split(':')[1])) { insf=insf.replace(':' + arr[1] + ':', ':' + document.getElementById('mystime').innerHTML.split(':')[1] + ':'); arr[1]='zz'; } ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(':' + arr[1] + ':', ':0' + arr[1] + ':'); } ";
print " if (eval('' + arr[0].trim().length) == 1) { insf=insf.replace(arr[0].trim() + ':', '0' + arr[0].trim() + ':'); } ";
print " } ";
print " } ";
print " return insf; ";
print " } ";
print " function loctime() { if (ls == '') { ";
print " qwr='' + Intl.DateTimeFormat().resolvedOptions().timeZone; ";
print " var d = new Date(); ";
print " d.toLocaleString('en-US', { timeZone: qwr }); ";
print " ns=document.getElementById('mystime').innerHTML.split(':')[2].split(' ')[0]; ";
print " ls=zeroize(('' + d.toLocaleString()).replace(',','')) + ' <a onclick=alert(qwr); style=cursor:pointer;text-decoration:underline;>GMT' + d.toString().split(' GMT')[1] + '</a>'; } if (!document.getElementById('mytime')) { setTimeout(loctime,1000); } else { ";
print " document.getElementById('mytime').innerHTML=ls.replace(':' + ls.split(':')[2].split(' ')[0] + ' ', ':' + ns + ' '); } ";
print " } ";
print "</script>";
print "</head>";
print "<body onload=setTimeout(loctime,1000);>";
print "<h2 style='font-family:Courier New;'>Hello $first_name $last_name <br>&nbsp;Local: <span id=mytime></span><br>Server: <span id=mystime>$dmy $hms</span> $dttz </h2><h4>";

if ($blogp == "") {
$blogp = $first_name;
$oneletter = substr( $blogp, 0, 1 );
}

if ($blogp != "") {
$oneletter = substr( $blogp, 0, 1 );

if ((ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) || ord($oneletter) == 40 ){
my ($oneurl) = split /,/, $blogp;

if ($oneurl == $blogp) {
$oneletter = substr( $blogp, 0, 1 );
} else {
if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")) {
$oneletter = "1";
$blogp = "( $blogp )";
} else {
$oneletter = "2";
}
}

}
}


if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")){
# /*** mysql hostname ***/
$hostname = 'dbhost';

# /*** mysql username ***/
$username = 'username';

# /*** mysql ***/
$password = 'password';

$dbname = 'dbname';

$tname = 'table_name';
$hostname = "DBI:mysql:$dbname:$hostname";

$dbh = DBI->connect($hostname, $username, $password);

my ($oneaurl) = split /,/, $blogp;
if (index($blogp, ',') <= 0) {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID=?");
} else {
if (ord($oneletter) != 40) {
$blogp = "($blogp)";
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
} else {
$sth = $dbh->prepare("SELECT post_title, post_content, ID FROM $tname WHERE ID in $blogp");
$blogp = "";
}
}

if ($blogp == "") {
$sth->execute();
} else {

$sth->execute( $blogp );
}

$exc = 0;
$coln = "A";
$rown = 6;
$alinkis = "";
my $workbook = 0; # Spreadsheet::WriteExcel->new('../perl.xls');


while (($tt, $cont, $iid) = $sth->fetchrow_array()) {
my ($junk, $imageu) = split / src="/, $cont;
my ($imageurl) = split /"/, $imageu;
my ($junk, $cutto) = split / href="/, $cont;
my ($cuttothechase) = split /"/, $cutto;
if ($exc == 0) {
$exc = 1;
# Create a new Excel workbook
$workbook = Spreadsheet::WriteExcel->new('../perl.xls');

# Add a worksheet
$worksheet = $workbook->add_worksheet();

# Add and define a format
$format = $workbook->add_format(); # Add a format
$format->set_bold();
$format->set_color('red');
$format->set_align('center');

# Write a formatted and unformatted string, row and column notation.
$col = $row = 0;
$worksheet->write($row, $col, "$first_name $last_name", $format);
# $worksheet->write(1, $col, 'Hi Excel!');

# Write a number and a formula using A1 notation
$worksheet->write("${coln}3", "$tt");
$worksheet->write("${coln}4", "https://www.rjmprogramming.com.au/ITblog/?p=$iid");
$worksheet->write("${coln}5", "$cuttothechase");
$worksheet->write("${coln}6", "$imageurl");
$alinkis = "<a download=perl.xls href='//www.rjmprogramming.com.au/perl.xls' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details id=myd><summary id=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary>$cont</details>\n";
} else {
$rown += 1;
$worksheet->write("${coln}${rown}", "$tt");
$rown += 1;
$worksheet->write("${coln}${rown}", "https://www.rjmprogramming.com.au/ITblog/?p=$iid");
$rown += 1;
$worksheet->write("${coln}${rown}", "$cuttothechase");
$rown += 1;
$worksheet->write("${coln}${rown}", "$imageurl");
$alinkis = "<a download=perl.xls href='//www.rjmprogramming.com.au/perl.xls' title='Download Excel spreadsheet'>&#128196;</a>&nbsp;&nbsp;<a target=_blank href=$cuttothechase title='Cut to the chase'>&#127939;</a>&nbsp;&nbsp;<a target=_blank href=$imageurl title='Image URL'>&#128444;</a>";
print "<details class=myd><summary class=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$iid'>$tt</a>&nbsp;&nbsp;$alinkis</h1></summary>$cont</details>\n";
}

# print "@row\n";
}
# }
}

print "</h4><br><br><iframe id=myif src='/hello_get.html' style='width:100%; height:1500px;'></iframe></body>";
print "</html>";

1;

… creating optionally downloadable Excel spreadsheet documents reflecting user selections, in the changed Perl hello_get.cgi code supervised by (and working with) the changed HTML hello_get.html web application, where, as of today, the dropdown for WordPress Blog Posting selection accepts multiple selections …

… with …

  • First and Last Name … in webpage and spreadsheet
  • Local and Server timestamps … in webpage
  • Blog Posting link(s) … in webpage and spreadsheet
  • Download Spreadsheet (total synopsis) download link(s) … in webpage
  • Cut to the Chase (ie. the action item of a blog posting) link(s) … in webpage and spreadsheet
  • Image URL (ie. the topmost image of a blog posting) link(s) … in webpage and spreadsheet

… data items featuring.


Previous relevant Perl CGI DBI Module Tutorial is shown below.

Perl CGI DBI Module Tutorial

Perl CGI DBI Module Tutorial

Onto yesterday’s Perl CGI DateTime Module Primer Tutorial‘s …

  • use of Perl module DateTime … today, we try out …
  • use of Perl module DBI

… to facilitate the connection and use of database functionalities, in our case MySql, as per our changed Perl code to read off our WordPress blog MySql database table fields …

  1. post_title
  2. post_content

… fields describing WordPress blog “Posting Title” and “Posting HTML Content” respectively, as per


#!/usr/bin/perl

use DateTime;
use DateTime::TimeZone;
use DBI;
use DBD::mysql;


local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

if ($ENV{'REQUEST_METHOD'} eq "GET") {
$buffer = $ENV{'QUERY_STRING'};
}

# Split information into name/value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}

$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
$blogp = $FORM{blogp};
$oneletter = substr( $first_name, 0, 1 );

$dt = DateTime->now; # same as ( epoch => time )

$dttz = DateTime::TimeZone->new( name => 'local' )->name();

$dt->set_time_zone( $dttz );


$year = $dt->year;
$month = $dt->month; # 1-12


$day = $dt->day; # 1-31


$dow = $dt->day_of_week; # 1-7 (Monday is 1)


$hour = $dt->hour; # 0-23
$minute = $dt->minute; # 0-59


$second = $dt->second; # 0-61 (leap seconds!)


$doy = $dt->day_of_year; # 1-366 (leap years)


$doq = $dt->day_of_quarter; # 1..


$qtr = $dt->quarter; # 1-4

$dmy = $dt->dmy('/'); # 06/12/2002


$hms = $dt->hms; # 14:02:29

$tt = "";
$cont = "";

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "<script type=text/javascript>";
print " var ls='', ns='', qwr=''; ";
print " function zeroize(iinsf) { var insf=iinsf; var sep='/', i=0; while (insf.substring(i).substring(0,1) >= '0' && insf.substring(i).substring(0,1) <= '9') { i++; } sep=insf.substring(i).substring(0,1); ";
print " var arr=insf.split(sep); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(sep + arr[1] + sep, sep + '0' + arr[1] + sep); } ";
print " if (eval('' + arr[0].length) == 1) { insf='0' + insf; } ";
print " arr=insf.split(' ')[1].split(':'); ";
print " if (eval('' + arr.length) >= 3) { ";
print " if (insf.indexOf(' pm') != -1) { insf=insf.replace(' ' + arr[0].trim() + ':', ' ' + eval(12 + eval('' + arr[0].trim())) + ':').replace(' pm', ' '); arr=insf.split(' ')[1].split(':'); } ";
print " if (eval(-1 + eval('' + arr[1])) == eval('' + document.getElementById('mystime').innerHTML.split(':')[1])) { insf=insf.replace(':' + arr[1] + ':', ':' + document.getElementById('mystime').innerHTML.split(':')[1] + ':'); arr[1]='zz'; } ";
print " if (eval('' + arr[1].length) == 1) { insf=insf.replace(':' + arr[1] + ':', ':0' + arr[1] + ':'); } ";
print " if (eval('' + arr[0].trim().length) == 1) { insf=insf.replace(arr[0].trim() + ':', '0' + arr[0].trim() + ':'); } ";
print " } ";
print " } ";
print " return insf; ";
print " } ";
print " function loctime() { if (ls == '') { ";
print " qwr='' + Intl.DateTimeFormat().resolvedOptions().timeZone; ";
print " var d = new Date(); ";
print " d.toLocaleString('en-US', { timeZone: qwr }); ";
print " ns=document.getElementById('mystime').innerHTML.split(':')[2].split(' ')[0]; ";
print " ls=zeroize(('' + d.toLocaleString()).replace(',','')) + ' <a onclick=alert(qwr); style=cursor:pointer;text-decoration:underline;>GMT' + d.toString().split(' GMT')[1] + '</a>'; } if (!document.getElementById('mytime')) { setTimeout(loctime,1000); } else { ";
print " document.getElementById('mytime').innerHTML=ls.replace(':' + ls.split(':')[2].split(' ')[0] + ' ', ':' + ns + ' '); } ";
print " } ";
print "</script>";
print "</head>";
print "<body onload=setTimeout(loctime,1000);>";
print "<h2 style='font-family:Courier New;'>Hello $first_name $last_name <br>&nbsp;Local: <span id=mytime></span><br>Server: <span id=mystime>$dmy $hms</span> $dttz </h2><h4>";

if ($blogp == "") { $blogp = $first_name; } else { $oneletter = substr( $blogp, 0, 1 ); }

if (ord($oneletter) >= ord("0") && ord($oneletter) <= ord("9")){
# /*** mysql hostname ***/
$hostname = 'dbhost';

# /*** mysql username ***/
$username = 'username';

# /*** mysql ***/
$password = 'password';

$dbname = 'dbname';

$tname = 'table_name';
$hostname = "DBI:mysql:$dbname:$hostname";

$dbh = DBI->connect($hostname, $username, $password);

$sth = $dbh->prepare("SELECT post_title, post_content FROM $tname WHERE ID=?");

$sth->execute( $blogp );

#while ( @row = $sth->fetchrow_array ) {
while (($tt, $cont) = $sth->fetchrow_array()) {
print "<details id=myd><summary id=mys><h1><a target=_blank href='//www.rjmprogramming.com.au/ITblog/?p=$blogp'>$tt</a></h1></summary>$cont</details>\n";
# print "@row\n";
}
# }
}


print "</h4><br><br><iframe id=myif src='/hello_get.html' style='width:100%; height:1500px;'></iframe></body>";
print "</html>";

1;

… in the changed Perl hello_get.cgi code supervised by (and working with) the changed HTML hello_get.html web application.


Previous relevant Perl CGI DateTime Module Primer Tutorial is shown below.

Perl CGI DateTime Module Primer Tutorial

Perl CGI DateTime Module Primer Tutorial

Do you remember with Perl CGI Modes of Use Primer Tutorial how we used the Perl programming language as an alternative server language player up at the RJM Programming website?

Well, in any case, today, we explore some Perl modules which can make that code be more useful to us. As for how we interface to it, we’ve written a very simple HTML hello_get.html interfacer we’d like to thank https://www.tutorialspoint.com/perl/perl_cgi.htm for …


<html>
<head>
<title>hello_get ... Thanks to https://www.tutorialspoint.com/perl/perl_cgi.htm and https://perlmaven.com/most-popular-perl-modules and https://www.freecodecamp.org/news/how-to-format-dates-in-javascript/</title>
</head>
<body>
<h1>hello_get.html HTML calls on hello_get.cgi Perl</h1>
<h3>RJM Programming - February, 2023</h3>
<h3>Thanks to https://www.tutorialspoint.com/perl/perl_cgi.htm and https://perlmaven.com/most-popular-perl-modules and https://www.freecodecamp.org/news/how-to-format-dates-in-javascript/</h3>
<br><br>
<FORM action = "/cgi-bin/hello_get.cgi" method = "GET">

First Name: <input type = "text" name = "first_name"> <br>

Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</FORM>

</body>
</html>

… where this webpage’s HTML form’s action points to some Perl hello_get.cgi (up at the Apache web server, in a cgi-bin folder and with the executable permission bit set) code using the DateTime module, and showing the user client local timezone current time compared to this RJM Programming’s server timezone current time …


#!/usr/bin/perl

use DateTime;
use DateTime::TimeZone;

local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

if ($ENV{'REQUEST_METHOD'} eq "GET") {
$buffer = $ENV{'QUERY_STRING'};
}

# Split information into name/value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}

$first_name = $FORM{first_name};
$last_name = $FORM{last_name};

$dt = DateTime->now; # same as ( epoch => time )

$dttz = DateTime::TimeZone->new( name => 'local' )->name();

$dt->set_time_zone( $dttz );

$year = $dt->year;
$month = $dt->month; # 1-12

$day = $dt->day; # 1-31

$dow = $dt->day_of_week; # 1-7 (Monday is 1)

$hour = $dt->hour; # 0-23
$minute = $dt->minute; # 0-59

$second = $dt->second; # 0-61 (leap seconds!)

$doy = $dt->day_of_year; # 1-366 (leap years)

$doq = $dt->day_of_quarter; # 1..

$qtr = $dt->quarter; # 1-4

$dmy = $dt->dmy('/'); # 06/12/2002

$hms = $dt->hms; # 14:02:29

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "<script type=text/javascript>";
print " function loctime() { ";
print " var qwr='' + Intl.DateTimeFormat().resolvedOptions().timeZone; ";
print " var d = new Date(); ";
print " d.toLocaleString('en-US', { timeZone: qwr }); ";
print " var ns=document.getElementById('mystime').innerHTML.split(':')[2].split(' ')[0]; ";
print " var ls=('' + d.toLocaleString()).replace(',','') + ' GMT' + d.toString().split(' GMT')[1]; ";
print " document.getElementById('mytime').innerHTML=ls.replace(':' + ls.split(':')[2].split(' ')[0] + ' ', ':' + ns + ' '); ";
print " } ";
print "</script>";
print "</head>";
print "<body onload=loctime();>";
print "<h2 style='font-family:Courier New;'>Hello $first_name $last_name <br>&nbsp;Local: <span id=mytime></span><br>Server: <span id=mystime>$dmy $hms</span> $dttz </h2>";
print "<br><br><iframe src='/hello_get.html' style='width:100%; height:1500px;'></iframe></body>";
print "</html>";

1;

The use of the HTML iframe in the Perl (writing HTML) code means that either …

… can be used to get the “Perl ball” rolling.


Previous relevant Perl CGI Modes of Use Primer Tutorial is shown below.

Perl CGI Modes of Use Primer Tutorial

Perl CGI Modes of Use Primer Tutorial

A little while back we revisited the “PHP Modes of Use” discussion last talked about with PHP Modes of Use File Traverse Tutorial as shown below. We’re revisiting today to show you that it doesn’t have to be only your principal server language of choice involved in this kind of thinking, but you can also talk in terms of your chosen CGI (Common Gateway Interface) language of choice, which happens to be Perl here at the www.rjmprogramming.com.au domain. The other common partner of PHP as its CGI partner is Python.

Do you recall the three modes of use we talk about? Here they are below …

  1. web browsing … via use of a GET arguments URL
  2. curl (from the command line … in our case Linux, but could be Windows too)
  3. command line (Perl) … use the $ARGV[] array variables

… all good? … okay, we keep those three, but with the curl option would also like to show that it can be subdivided into two submodes, namely …

  • GET mode (via URL)
  • POST mode (via simulated FORM (results))

… which is probably true of non-CGI scenarios as well, but is particularly pertinent to discussions of CGI because we generally think of the CGI language as the one POSTed to from an HTML form, but, here, hopefully, we extend your mode of thinking to the thought that curl can handle you sending in the GET mode (though that is awkward with more than one GET argument and using the & syntax) or via the use of various non-default switches such as -d “name1=value1 name2=value2 blah3=blahval3″ to simulate a (form) POST … pretty powerful, huh … enabling what you may have only initially thought of as a piece of code to process an HTML form, into the additional possibility of a standalone piece of code that curl can control independent of a web browser, as required. Please note, though, for those of us who want to “do their heads in” for “Onion of the 4th Dimension” possibilities, the PHP exec command, or something like it could be used with options 3 and/or 2a and/or 2b to create other possibilities.

Anyway, have a look (closely) at our tutorial picture and our web browser mode live run

… and have a look at the associated Perl CGI programming source code to read an *.htm* or *.txt file in readfile.cgi

Of great help for this tutorial was Perl and CGI for the World Wide Web by Elizabeth Castro page 195 (in particular) and What is the cURL command-line syntax to do a POST request? (for help regarding curl command line switches for POSTed data) … thanks.

Will leave you with a recall of the discussions regarding PHP (our primary non-CGI server language of choice at www.rjmprogramming.com.au) below …


Previous relevant PHP Modes of Use File Traverse Tutorial is shown below.

PHP Modes of Use File Traverse Tutorial

PHP Modes of Use File Traverse Tutorial

It’s been a while since we last visited the “PHP Modes of Use” discussion last talked about with C Supervised PHP Modes of Use Primer Tutorial as shown below. We’re revisiting today to show you a practical application of writing PHP for those three modes of use … namely …

  1. web browsing … use a form, then post, and then access the $_POST[] variables
  2. curl … note how only the one $_GET[] variable is available because of trouble using & on Linux command line (use of @ is a local idea … there would be many other ideas that will work)
  3. command line PHP … use the $argv array variables

… so have a look at the PHP programming source code to traverse a directory’s files in doviadir.php with the live “web browsing” live run.

Will leave you with a recall of the discussion below …

Recently, with our tutorial, PHP Modes of Use Primer Tutorial as shown below, we talked about three modes of use or access for the use of PHP and today we encase all that thinking in a Mac OS X command line C program supervision framework. You’d expect that this is possible in a command line or Intranet environment where Linux or unix (or, for that matter, Windows command line … though the code here won’t work for this one) where C can have such a close relationship to the Linux or unix kernel, that it would be able the “run the whole show” as well as the shell commands themselves can. Today’s C has been compiled using the Xcode IDE for use with a Mac OS X operating system.

So that’s the supervisor above. Read, again, about “the supervised”, below …

PHP is a very flexible programming language. It is probably best known as a server-side language called by a web browser using the http transport layer (ie. web browsing, or “surfing the net”). Let’s list three modes of use of PHP below:

  1. Via http transport layer (ie. web browsing, or “surfing the net”) in an Internet mode of use (eg: HTTP://localhost:8888/in_tra_ter_net.php?SERVER_NAME=localhost) in address bar of a web browser
  2. Via curl in an Internet mode of use (eg. curl HTTP://localhost:8888/in_tra_ter_net.php?SERVER_NAME=localhost) at Linux or unix or Windows command line to default output (and you can redirect as required via > outfile or >> outfile or 2> errfile or 2>> errfile)
  3. Via command line PHP in Linux or unix or Windows command line in a command or Intranet mode of use (eg. php in_tra_ter_net.php SERVER_NAME=localhost) at a Linux or unix or Windows command line (where the PHP code has been placed, in our example (ie. it is not a URL, but is a file specification of your (Intranet) server)) to default output (or you can redirect as required via > outfile or >> outfile or 2> errfile or 2>> errfile)

Does it matter how the PHP is accessed? Well, yes, it does … sometimes, but not if the code is restricted to a particular mode of usage (but part of what this tutorial is about is to get across how flexible and powerful PHP can be). With the last option above, lots of $_SERVER[] variables are undefined, for example.

  1. $_SERVER[‘HTTP_COOKIE’] is defined, unlike with curl usage (this seems to be a possibility as a way to detect curl usage). Most $_SERVER[] variables are defined, but $argv[] array is not.
  2. $_SERVER[‘HTTP_COOKIE’] is undefined, but a lot of the rest of $_SERVER[] variables are as above.
  3. Lots of $_SERVER[] variables are undefined, with the exception of $_SERVER[‘SCRIPT_FILENAME’] which may help you with Intranet application usage. You cannot enter $_GET[] arguments (on the command line (ie. you will get a syntax error if you try)) so these are undefined, but $argv[] array can be used in that awkward way shown, so that $argv[1] can be arranged to be a lot like $_SERVER[‘QUERY_STRING’] (ie. the bits after ? in a URL).

So, maybe you have the one mode of use in mind, but you need to think a bit to support all the modes of use, if they are all to have a role with the PHP you write, because, despite these differences it is good to use $_SERVER[] and $_GET[] and $_POST[] and $_SESSION[] and $argv[] and whatever else in terms of variable information PHP offers in terms of attempting to write generic code.

Hope you get something out of today’s discussion of our Mac OS X MAMP Apache local Web server environment example (hence the HTTP://localhost:8888/ you see in the URLs above), but please bear in mind that there would be other modes of use once you think of other client HTML element ways of accessing PHP (all a lot like the “web browsing” of above) or other possibilities within PHP code itself via PHP commands exec and file_get_contents the latter of which can be very useful during Intranet usage where there is no curl available, perhaps. Instead of curl you could use wget as another approach.

You may want to see a live run (web browsing) here at the rjmprogramming.com.au domain of the supervised PHP (alone), or you may want to download the supervised PHP programming source code you could call in_tra_ter_net.php or you may want to download the supervisory main.c as you require.

A “stop press” to do with code above is that since the “queueing up” of this blog post a new posting is relevant, the recent PHP Modes of Use Follow Up Tutorial, and that to incorporate this posting’s improvements over PHP Modes of Use Primer Tutorial, you’d want to substitute all mentions of in_tra_ter_net with more_in_tra_ter_net in the code of main.c as above. The relevant changed PHP source code is more_in_tra_ter_net.php


Previous relevant C Supervised PHP Modes of Use Primer Tutorial is shown below.

C Supervised PHP Modes of Use Primer Tutorial

C Supervised PHP Modes of Use Primer Tutorial

Recently, with our tutorial, PHP Modes of Use Primer Tutorial as shown below, we talked about three modes of use or access for the use of PHP and today we encase all that thinking in a Mac OS X command line C program supervision framework. You’d expect that this is possible in a command line or Intranet environment where Linux or unix (or, for that matter, Windows command line … though the code here won’t work for this one) where C can have such a close relationship to the Linux or unix kernel, that it would be able the “run the whole show” as well as the shell commands themselves can. Today’s C has been compiled using the Xcode IDE for use with a Mac OS X operating system.

So that’s the supervisor above. Read, again, about “the supervised”, below …

PHP is a very flexible programming language. It is probably best known as a server-side language called by a web browser using the http transport layer (ie. web browsing, or “surfing the net”). Let’s list three modes of use of PHP below:

  1. Via http transport layer (ie. web browsing, or “surfing the net”) in an Internet mode of use (eg: HTTP://localhost:8888/in_tra_ter_net.php?SERVER_NAME=localhost) in address bar of a web browser
  2. Via curl in an Internet mode of use (eg. curl HTTP://localhost:8888/in_tra_ter_net.php?SERVER_NAME=localhost) at Linux or unix or Windows command line to default output (and you can redirect as required via > outfile or >> outfile or 2> errfile or 2>> errfile)
  3. Via command line PHP in Linux or unix or Windows command line in a command or Intranet mode of use (eg. php in_tra_ter_net.php SERVER_NAME=localhost) at a Linux or unix or Windows command line (where the PHP code has been placed, in our example (ie. it is not a URL, but is a file specification of your (Intranet) server)) to default output (or you can redirect as required via > outfile or >> outfile or 2> errfile or 2>> errfile)

Does it matter how the PHP is accessed? Well, yes, it does … sometimes, but not if the code is restricted to a particular mode of usage (but part of what this tutorial is about is to get across how flexible and powerful PHP can be). With the last option above, lots of $_SERVER[] variables are undefined, for example.

  1. $_SERVER[‘HTTP_COOKIE’] is defined, unlike with curl usage (this seems to be a possibility as a way to detect curl usage). Most $_SERVER[] variables are defined, but $argv[] array is not.
  2. $_SERVER[‘HTTP_COOKIE’] is undefined, but a lot of the rest of $_SERVER[] variables are as above.
  3. Lots of $_SERVER[] variables are undefined, with the exception of $_SERVER[‘SCRIPT_FILENAME’] which may help you with Intranet application usage. You cannot enter $_GET[] arguments (on the command line (ie. you will get a syntax error if you try)) so these are undefined, but $argv[] array can be used in that awkward way shown, so that $argv[1] can be arranged to be a lot like $_SERVER[‘QUERY_STRING’] (ie. the bits after ? in a URL).

So, maybe you have the one mode of use in mind, but you need to think a bit to support all the modes of use, if they are all to have a role with the PHP you write, because, despite these differences it is good to use $_SERVER[] and $_GET[] and $_POST[] and $_SESSION[] and $argv[] and whatever else in terms of variable information PHP offers in terms of attempting to write generic code.

Hope you get something out of today’s discussion of our Mac OS X MAMP Apache local Web server environment example (hence the HTTP://localhost:8888/ you see in the URLs above), but please bear in mind that there would be other modes of use once you think of other client HTML element ways of accessing PHP (all a lot like the “web browsing” of above) or other possibilities within PHP code itself via PHP commands exec and file_get_contents the latter of which can be very useful during Intranet usage where there is no curl available, perhaps. Instead of curl you could use wget as another approach.

You may want to see a live run (web browsing) here at the rjmprogramming.com.au domain of the supervised PHP (alone), or you may want to download the supervised PHP programming source code you could call in_tra_ter_net.php or you may want to download the supervisory main.c as you require.

A “stop press” to do with code above is that since the “queueing up” of this blog post a new posting is relevant, the recent PHP Modes of Use Follow Up Tutorial, and that to incorporate this posting’s improvements over PHP Modes of Use Primer Tutorial, you’d want to substitute all mentions of in_tra_ter_net with more_in_tra_ter_net in the code of main.c as above. The relevant changed PHP source code is more_in_tra_ter_net.php


Previous relevant PHP Modes of Use Primer Tutorial is shown below.

PHP Modes of Use Primer Tutorial

PHP Modes of Use Primer Tutorial

PHP is a very flexible programming language. It is probably best known as a server-side language called by a web browser using the http transport layer (ie. web browsing, or “surfing the net”). Let’s list three modes of use of PHP below:

  1. Via http transport layer (ie. web browsing, or “surfing the net”) in an Internet mode of use (eg: HTTP://localhost:8888/in_tra_ter_net.php?SERVER_NAME=localhost) in address bar of a web browser
  2. Via curl in an Internet mode of use (eg. curl HTTP://localhost:8888/in_tra_ter_net.php?SERVER_NAME=localhost) at Linux or unix or Windows command line to default output (and you can redirect as required via > outfile or >> outfile or 2> errfile or 2>> errfile)
  3. Via command line PHP in Linux or unix or Windows command line in a command or Intranet mode of use (eg. php in_tra_ter_net.php SERVER_NAME=localhost) at a Linux or unix or Windows command line (where the PHP code has been placed, in our example (ie. it is not a URL, but is a file specification of your (Intranet) server)) to default output (or you can redirect as required via > outfile or >> outfile or 2> errfile or 2>> errfile)

Does it matter how the PHP is accessed? Well, yes, it does … sometimes, but not if the code is restricted to a particular mode of usage (but part of what this tutorial is about is to get across how flexible and powerful PHP can be). With the last option above, lots of $_SERVER[] variables are undefined, for example.

  1. $_SERVER[‘HTTP_COOKIE’] is defined, unlike with curl usage (this seems to be a possibility as a way to detect curl usage). Most $_SERVER[] variables are defined, but $argv[] array is not.
  2. $_SERVER[‘HTTP_COOKIE’] is undefined, but a lot of the rest of $_SERVER[] variables are as above.
  3. Lots of $_SERVER[] variables are undefined, with the exception of $_SERVER[‘SCRIPT_FILENAME’] which may help you with Intranet application usage. You cannot enter $_GET[] arguments (on the command line (ie. you will get a syntax error if you try)) so these are undefined, but $argv[] array can be used in that awkward way shown, so that $argv[1] can be arranged to be a lot like $_SERVER[‘QUERY_STRING’] (ie. the bits after ? in a URL).

So, maybe you have the one mode of use in mind, but you need to think a bit to support all the modes of use, if they are all to have a role with the PHP you write, because, despite these differences it is good to use $_SERVER[] and $_GET[] and $_POST[] and $_SESSION[] and $argv[] and whatever else in terms of variable information PHP offers in terms of attempting to write generic code.

Hope you get something out of today’s discussion of our Mac OS X MAMP Apache local Web server environment example (hence the HTTP://localhost:8888/ you see in the URLs above), but please bear in mind that there would be other modes of use once you think of other client HTML element ways of accessing PHP (all a lot like the “web browsing” of above) or other possibilities within PHP code itself via PHP commands exec and file_get_contents the latter of which can be very useful during Intranet usage where there is no curl available, perhaps. Instead of curl you could use wget as another approach.

You may want to see a live run (web browsing) here at the rjmprogramming.com.au domain or you may want to download the PHP programming source code you could call in_tra_ter_net.php as you require.

If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.

This entry was posted in eLearning, Operating System, Tutorials and tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>