Some useful Perl and PHP code snippets for the web.


CGI Sample Code.

Loading a file into the browser in Python. Works very well indeed!
Re-Written as of March 31 2006. Using PRE and XMP tags to print out
the text correctly. Tested in Apache 2.0. I have defined some
functions to print out a HTTP header as I do not know how to use the
python cgi module yet. Re-Written. 11 April 2005.

#!/usr/bin/python
from datetime import datetime
import os
def cgi1():
	print "Content-type: text\html\n"
	print "<HTML><HEAD><TITLE></TITLE>\n \
		</HEAD><BODY bgcolor='#FFFFFF\n' \
		text='#000000' link='#000099'>\n"
def cgi2():
	print "</BODY></HTML>\n"
def cgi3():
	print "<B>Viewing some undoubtedly cool file.</B><BR/>\n"
# main()
cgi1()
print "<H1>Python CGI page..</H1>\n"
i = datetime.now().strftime("%A, %d, %B, %Y - %H:%M:%S.")
print "<P>The date and time is....",i
print "</P>"
environ=os.environ
Browser = environ['HTTP_USER_AGENT']
myLine = ' '
FH=file("log.txt","r")
cgi3()
while not myLine == '':
	myLine=FH.readline()
	if myLine == '':
		print myLine,"<P>EOF.</P>"
	else:
		print myLine,"<BR />"
FH.close()
print "<I>This script written in Python. <A
HREF='http://www.python.org'>http://www.python.org</A><BR
/>"
print Browser
print "</I>"
cgi2()

PHP Random Image & Links script. Picks a random image from a list.

<html>
<head>
  <meta name="generator" content="HTML Tidy for Linux/x86 (vers 12 April 2005), see www.w3.org" />
  <title>Doom Screenshots.</title>
  <meta name="GENERATOR" content="Jedit. http://jedit.org." />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body style="color: white; background-color: rgb(8, 37, 46);" alink="lightGray" link="gray" vlink="darkGray">
<h1>My PHP page.</h1>
<form action="saruman.php" method="GET">
<select name="img" size="1">
<option value="0" selected>Image number: 1.</option>
<option value="1">Image number: 2.</option>
<option value="2">Image number: 3.</option>
<option value="3">Image number: 4.</option>
<option value="4">Image number: 5.</option>
<option value="5">Image number: 6.</option>
<option value="6">Image number: 7.</option>
</select>
<button type="submit">Submit</button>
</form>
<?php
	$time = strftime("%A %d %B %Y. %r - %Z");
	srand(time(NULL));
	$day = rand() % 6;
	$browser = getenv("HTTP_USER_AGENT");
	$string = sprintf("<P>You are using <I>%s</I> browser to visit @ <I>%s</I> time.</P>\n", $browser, $time);
	$links = array("BejArray" => array("0" => "http://www.quake4.com", "1" => "http://nami.mancubus.net",
			      "2" => "http://www.debian.org", "3" => "http://www.somethingaweful.com",
			      "4" => "http://www.slashdot.org", "5" => "http://castlevania.wrong.button.com/",
			      "6" => "http://doomdepot.doom2.net/index.html"
	));
	printf("<H3>Random Image Script.</H3>\n");
	if (!$img) {
		switch ($day) {
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
				printf("<IMG SRC='maps/00%s.png' width='320' height='200'>\n", $day);
				continue;
			}
		}
		else {
			printf("<IMG src='maps/00%s.png' width='320' height='200'>\n", $img);
		}
	echo $string;
	printf("<P>Random Link. %s</P>\n", $links["BejArray"][$day]);
	printf("<BR /><P>%s</P>\n", $val);
?>
<div align="left"  valign="top" style='position: absolute; left: 0px; top: 448px;'>
  <p><a href="http://www.jedit.org/">Made with Jedit.</a></p>
</div>
</body>
</html>

And the above program in C. A work in progress.

/* Emacs style mode select: -*- linux-c -*-
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
/********************************************************************
* Description: Random Link CGI Script.
* Author: Saruman <>
* Created at: Sun Sep 11 02:05:26 EST 2005
* Computer: Battlestar
* System: Linux 2.6.10 on i686
*
* Copyright (c) 2005 Saruman  All rights reserved.
*
********************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
const char *links[] = {
		"http://s2.enemy.org",
		"http://www.planetps2. com",
		"http://www.redhat.com",
		"http://www.atomicmpc.com.au",
		"http://www.somethingaweful.com",
		"http://www.debian.org"
};
void html()
{
	printf("Content-type: text/html\n\n");
	printf("<html>\n");
}
void html2()
{
	printf("</BODY></HTML>\n");
}
int main(void)
{
	int i;
	html();
	printf("<H1>C++ Random Link Program.</H1>");
	printf("<P>And now for a random image.</P>\n");
	srand(time(NULL));
	i = rand() % 6;
	printf("<P><I>\x6fRandom Link. %s</I></P>\n", links[i]);
	/* Selecting a random image. */
	switch (i) {
	case 0:
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
	case 6:
		printf("<IMG SRC='../maps/00%i.gif' width='320' height='200' />\n", i);
	}
	html2();
	return 0;
}

CGI Time/Date code. This code is useful for those CGI scripts that need to
show the current date and time in the browser.

@Days = ('Sunday','Monday','Tuesday',
	 'Wednesday','Thursday','Friday',
	 'Saturday');
@Mon1 = ('January','February','March',
	 'April','May','June',
	 'July','August','September',
	 'October','November','December');
($Sec,$Min,$Hour,$MDay,$Mon,$Year,$WkDay) = (localtime)[0,1,2,3,4,5,6];
$Year += 1900;
if($Sec < 10) {
	$Sec = "0$Sec"
};
if($Min < 10) {
	$Min = "0$Min"
};
if($Hour < 10) {
	$Hour = "0$Hour"
};
$date = sprintf("%s:%s:%s - %s %i %s %s", $Hour,$Min,$Sec, $Days[$WkDay], $MDay, $Mon1[$Mon], $Year);

The following code is a code sample that will read a directory and generate a
drop down menu listing of the contents. Just like my viewblog.cgi.
An incredibly useful code sample for sure. It even removes the . and .. from the
directory listings. You can use this to generate a listing of your Blog archives
just as I have done. I can think of many uses for this code. Now aren’t you
happy I wrote this instead of you having to suffer through the process yourself?
The things I do for my readers, just to make you happy.

This code requires CGI.pm. As mentioned before, very useful for Blog Archives
and/or general website archiving duties. I give this code sample a 10-10. In
case you were wondering, this code is from my viewblog.cgi script, which is a
good live example of this code by the way.

print $query->header(-type=>'text/html',
		     -expires=>'+3d',
		     -cookie=>$date,
		     -charset=>'utf-8');
print $query->start_html(-title=>'CGI Viewblog CGI Script.',
			 -meta=>{'keywords'=>'Blog Doom2 Level Editing Linux Doom',
				 'copyright'=>'Copyright 2004 John Cartwright.',
				 'definition'=>'General Viewblog Script.',
				 'Appeal'=>'Wide',
				 'description'=>'CGI Viewblog Script.'},
			 -BGCOLOR=>'#FFFFFF',
			 -TEXT=>'#000000',
			 -LINK=>'#888fff');
print $query->h3("CGI Viewblog Script.\n");
print "&lt;PRE&gt;&lt;XMP&gt;\n\n";
open(FILE,"$random_file");
@FILE = <FILE>;
close(FILE);
$phrases = join('',@FILE);
@phrases = split(/$delimiter/,$phrases);
srand(time ^ $$);
$phrase = rand(@phrases);
print $phrases[$phrase];
print "\n\n&lt;/XMP&gt;&lt;/PRE&gt;\n";
print "&lt;DIV style='position: absolute; left: 666px; top: 0px; width: 400px; height: 96px'&gt;";
print $query->start_form(
			 -action=>'viewblog.cgi',
			 -method=>'GET',
			 -comment=>'Hello. Welcome to the viewblog CGI.',
			 -enctype=>);
print $query->br;
print "<SELECT name=\"$select\" size=\"1\" ID='formstuff'>\n";
opendir(DNAME, "$folder") || die "I cannot open the requested directory $folder \n $!";
@dirfiles2 = readdir (DNAME);
@dirfiles2 = sort(@dirfiles2);
foreach $x2 (@dirfiles2) {
    if ($x2 eq ".") {
	$x2 = ' ';
    }
    if ($x2 eq "..") {
	$x2 = ' ';
    }
    if ($x2 =~ /REMOVED/) {
	$x2 = ' ';
    }
    if ($x2 eq ".cgiclean") { # What is this?
	$x2 = ' ' ;
    }
    if ($x2 eq ".htaccess") {
	$x2 = ' ';
    }
    if ($x2 eq "$archive") {
	print "<OPTION selected value=\"$folder\/$archive\" ID='formstuff'>$archive</OPTION>\n";
    } else {
# Simple hack to weed out those annoying zero length() strings...
	if (length $x2 > 3) {
	    print "<OPTION value=\"$folder\/$x2\" ID='formstuff'>$x2</OPTION>\n";
	}
    }
}
closedir(DNAME);
printf("</select>\n");
print $query->br;
print $query->submit('submit','Submit Selection.');
print $query->reset('reset','Reset Form.');
print $query->end_form();
print $query->p("The time & date is: $date");
print "&lt;/DIV&gt;\n";
print $query->br;
unless ($html_page) {
    print h1('My Blog.');
    print $query->hr;
    opendir(DNAME, "$folder") || die "I cannot open the requested directory $folder \n $!";
    @dirfiles = readdir (DNAME); # We feed the directory into the @dirfiles hash.
    @dirfiles = sort(@dirfiles); # Sorting the contents here with sort();.
    foreach $dirfile (@dirfiles) { # And for each of our files we take appropriate action.
	if ($dirfile eq ".") { $dirfile = ' '; }
	if ($dirfile eq "..") { $dirfile = ' '; }
	if ($dirfile =~ /REMOVED/) { $dirfile = ' '; }
	if ($dirfile eq ".cgiclean") { $dirfile = ' '; }
	if ($dirfile eq ".htaccess") { $dirfile = ' '; }
	$dirfile =~ s/_/&nbsp;-&nbsp;-&nbsp;-&nbsp;/g;
	if (length $dirfile > 3) {
	    print "&nbsp;$dirfile<BR/>\n";
	}
    }
    closedir(DNAME);

This small code sample shows how I have implemented the cool quote on my
viewblog.cgi. The quote goes in between the QUOTE tags and it will be printed as
it appears. The start and finishing QUOTE tags _must_ be flush against the left
margin or it _will_ break. You may also use PRE tags inside the quote code
especially if you are coding for the web. This will help format your output. As
you can see below, you can echo variables to the screen as well inside this
code, this is good for using my afforementioned time and date code to echo the
date and time to the browser along with your witty quotes.

#!/usr/bin/perl -W
print "Content-type: text/html\n\n";
$browser = "$ENV{'HTTP_USER_AGENT'}";
print <<QUOTE;
	#Quote goes here.
	#And now we echo the HTTP_USER_AGENT variable
	#to the screen.
	echo $browser;
QUOTE

For example: See below.

print <<QUOTE;
	<PRE>
	There shall become a time
	when the bands of Ocean
	shall be loosened,
	and the vast earth shall be laid open,
	Another Tiphys shall disclose new worlds,
	And lands shall be seen beyond Thule.
		-- Seneca, the tragedian, 1st Century, "The Medea".
	</PRE>
QUOTE

Or this way. Feeding it into a variable.

$quote = <<"(QUOTE_HTML)";
	Burn them all! Nod has enough problems with the GDI jackals
	digging through the ruins of Kane's temple, but now these new
	"Generals", more like fools, continue to bicker and vie for
	power. I cannot allow this infighting to continue. The inner
	circle is divided and I need to remind them that even though
	Kane is gone, his plans live on. I have not survived death time
	and after time and stood at kane's right hand this long to see
	everything crumble around us... Our lack of communication and
	innacurate information is a severe hindrance - without CABAL's
	presence, we are deaf and blind to the rest of the world. I cannot
	let anger distract me from my path.
	Kane's plan will become a reality - I will see to that. The steps
	have been taken and the machine has been set in motion. I will not
	let Nod degenerate into chaos as it did in the past. We are stronger
	than that - I am stronger than that, but first things first. Tomorrow
	is going to be a busy day...
		--Log Entry 635 - Slavic Anton - Commander
		Entry Date: 12-17-2030
		Entry Time: 19:30 hours
		Access Level: Gold-7-Epsilon-Gamma-62866.
		From Command & Conquer Firestorm manual.
(QUOTE_HTML)

The $quote variable is then available for any use you see fit. Especially if
you have dynamically generated content in the multi-line quote with script
generated variables. Another twist on the same thing.

$quote = <<"(QUOTE_HTML)";
	The poets and sages,
	Guardians of the Secret Faith,
	Hid their Lighted Torches
	in deserts, catacombs and caves.
		-- Valery Briusov.
(QUOTE_HTML)
print $quote;