easy graphical dice generator in PHP

Just a simple little script which displays two die on screen. The faces are generated randomly, and are text-based, so no images required.

<html>

<head><title>Dice</title><head>

<body>

<?php

//Required code: This defines the dice array

$dice=array(

'<br>&nbsp;·&nbsp;<br>&nbsp;',

'·<br><br>&nbsp;&nbsp;·',

'·<br>&nbsp;·&nbsp;<br>&nbsp;&nbsp;·',

'·&nbsp;·<br><br>·&nbsp;·',

'·&nbsp;·<br>&nbsp;·<br>·&nbsp;·',

'···<br><br>···',

);

//End required code

?>

<!--FONT FOR CORRECT DISPLAYING-->

<font face='Lucida Console'>

<!--TABLE FOR MULTIPLE DICE-->

<table border='1'>

<tr>

<td><!--OUTPUT-->

<?php echo $dice[array_rand($dice)]; ?>

</td>

<td><!--OUTPUT-->

<?php echo $dice[array_rand($dice)]; ?>

<!--END EVERYTHING-->

</td>

</tr>

</table>

</font>

</body>

</html>

PHP script to spread text over multiple pages

Sometimes you’ll get a text file that is way too big to reasonably display all on one web page, this script is a simple paginator, which spreads the text over multiple pages cleanly. For the purposes of this demo, I have the data being read from a text file, however a more scalable approach would be to have the data being read from a database (I have commented this into the script).

<?php
function currPageName() {
	return substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], 
"/")+1);
}
$filename = "text.txt";
$this_page = currPageName();
if(isset($_REQUEST['step'])) $step = $_REQUEST['step'];
if(isset($_REQUEST['start'])) $start = $_REQUEST['start'];
if(isset($_REQUEST['file'])) $filename = $_REQUEST['file'];
// **************************************************
// or cut this out and allow the database script
// **************************************************
if(!strstr(".txt", $filename)) { $file = $filename; $filename .= ".txt"; }
else $file = substr($filename, 0, strlen($filename)-4);
$text = "";
if(file_exists($filename)) {
	$file_handle = fopen($filename, "rb");
	while (!feof($file_handle) ) {
		$text .= fgets($file_handle);
	}
	fclose($file_handle);
}
// **************************************************
// cut to here when allowing the database script
// **************************************************
/*
$file = $filename;
require("./db_connector.php"); // your database connection file
$sql = "SELECT * FROM your_table_name WHERE file={$filename} LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
mysql_close($conn); // assuming your connector is called $conn
$heading = $row['heading'];
$text = $row['data'];
*/
$text_limit = 600;
$text_array = explode(" ", $text);
$text_total_words = count($text_array);
if(!isset($step)) {
	$start = 0;
	$step = $text_limit;
}
$text_display = $text; 
if($text_total_words > $text_limit) { // if the page needs to be split up
	$text_display = ""; 
	for($x = $start; $x < $step; $x++) {
		$text_display .= $text_array[$x]." ";
	}
	$text_display = str_replace("\n\n", "\n</p>\n<p>\n", $text_display);
	if($start > 0) { // not page one
		$pstart = $start - $text_limit;
		if($pstart < 0) $pstart = 0;
		$pstep = $pstart + $text_limit;
		$text_display = "<a class=\"backforward\" href=\"{$this_page}?
file={$file}&start={$pstart}&step={$pstep}\"><&nbsp;Prev page</a></p>\n<br />
<br /><br />\n<p>{$text_display}";
	}
	if($text_total_words > $step) { // not the end of the text
		$nstart = $start + $text_limit;
		$nstep = $step + $text_limit;
		if($nstep > $text_total_words) $nstep = $text_total_words;
		$text_display = "{$text_display}</p>\n<br /><br /><br />\n<p>
<a class=\"backforward\" href=\"{$this_page}?file={$file}&start={$nstart}&
step={$nstep}\">Next page&nbsp;></a>";
	}
}
else { $text_display = str_replace("\n\n", "\n</p>\n<p>\n", $text_display); }
?>
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html lang="en" xml:lang="en">
<head>
	<title>page_stepper</title>
	<meta http-equiv="Content-Type" content="txt/html; charset=utf-8" />
	<style type="text/css">
* {
	margin: 0;
	padding: 0;
}
html {
	background: #ddd;
}
body {
	margin: 1em 10%;
	padding: 1em 3em;
	font: 80%/1.4 tahoma, arial, helvetica, lucida sans, sans-serif;
	border: 1px solid #999;
	background: #eee;
	position: relative;
}
a {
	color: #024378;
	font-weight: bold;
	text-decoration: none;
}
a:hover {
	color: #04569A;
	text-decoration: underline;
}
.backforward, .backforward:visited {
	background: #222 url(./site_images/overlay.png) repeat-x; 
	display: inline-block; 
	padding: 5px 10px 6px; 
	color: #fff; 
	text-decoration: none;
	-moz-border-radius: 6px; 
	-webkit-border-radius: 6px;
	-moz-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
	-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
	text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
	border: none;
	border-bottom: 1px solid rgba(0,0,0,0.25);
	position: relative;
	cursor: pointer;
	font-size: 13px; 
	font-weight: bold; 
	line-height: 1; 
	text-shadow: 0 -1px 1px rgba(0,0,0,0.25); 
	background-color: #e62727; 
}
.backforward:hover { background-color: #cf2525; }
</style>
    
</head>
<body>
<?php echo "<p>\n{$text_display}\n</p>"; ?>
</body>
</html>

I’ve hacked in a bit of CSS from the WampServer CSS to make it look pretty, but the buttons are mine. Basically the script pulls out the desired number of words from the text data, and prints it. If there are preceeding words, a “previous” button is prepended to the text; if there is more to come, a “next” button is appended.

function to format text file to HTML with PHP

This function takes in a text document, and reformats it for use on an HTML page.

function processText($text) {       
        $text = str_replace("&gt;", ">", $text);       
        $text = str_replace("&lt;", "<", $text);       
        $text = str_replace("\r\n\r\n", "\n", $text);       
        $text = str_replace("\r\n", "\n", $text);       
        $text = str_replace("\n\n", "\n", $text);       
        $text = str_replace("\n", " </p>\n<p> ", $text);       
        $text = "<p>".$text."</p>";       
        return $text;
}

Line by line, the process is:

Step 1

$text = str_replace("&gt;", ">", $text) and $text = str_replace("&lt;", "<", $text) – here each occurrence of “>” or “<” is replaced by it’s corresponding ASCII value (&gt; or &lt;).

Step 2

$text = str_replace("\r\n\r\n", "\n", $text) – here we replace “\r\n\r\n” double line breaks with a single “\n” line break (this is not HTML yet, but we will deal with this soon)

Step 3

$text = str_replace("\r\n", "\n", $text) – here we replace “\r\n” single line breaks with a single “\n” line break (again, this is not HTML yet, but we will deal with this)

Step 4

$text = str_replace("\n\n", "\n", $text) – here we replace “\n\n” double line breaks with a single “\n” line break (this is not HTML yet, but we are about to deal with this)

Step 5

$text = str_replace("\n", " </p>\n<p> ", $text) – here we replace “\n” single line breaks with a “</p>\n<p>” HTML paragraph break. As all other breaks have been converted to “\n” prior to this, they all become paragraphs

Step 6

$text = "<p>".$text."</p>" – this final line makes sure the text begins and ends with HTML paragraph tags.

automatically add soft hyphens to long words with PHP

Soft hyphens are optional hyphens that HTML will use when required to wrap a word to make sure it does not breach the space provided. This is a PHP function to add soft hyphens into words where required, and take the muscle word out of the equation.

function addSoftHyphen($word, $maxLen) {     
        if(strpos($word, "&shy;") === false) {         
                if(strlen($word) > $maxLen) {             
                        $word = substr($word, 0, $maxLen)."&shy;"
.substr($word, $maxLen);             
                        if(strlen(substr($word, strrpos($word, "&shy;")+5))
>$maxLen) {                 
                                $word = addSoftHyphen($word, $maxLen);             
                        }         
                }     
        }     
        else {         
                if(strlen(substr($word, strrpos($word, "&shy;")+5))>$maxLen) {             
                        $word = substr($word, 0, strrpos($word, "&shy;")+5
+$maxLen)."&shy;".substr($word, strrpos($word, "&shy;")+5+$maxLen);         
                }         
                if(strlen(substr($word, strrpos($word, "&shy;")+5))>$maxLen) {             
                        $word = addSoftHyphen($word, $maxLen);         
                }     
        }     
        return $word;
}

Just replace each occurrence of the excessively long word in question with a call to addSoftHyphen($word, $maxLen) and the word will be carefully broken and hyphenated as and when required without you needing to check each occurrence.

easy PHP email form

A very simple form for sending emails from any HTML page. This script gathers the input, performs form validation with PHP, and sends an email.

Step 1:

Make the form page mail.html

<html>
<head><title>Mail sender</title></head>
<body>
<form action="mail.php" method="POST">
<label for="email">Email</label>
<input type="text" name="email" size=40>
<label for="subject">Subject</label>
<input type="text" name="subject" size=40>
<label for="message">Message</label>
<textarea cols=40 rows=10 name="message"></textarea>
<input type="submit" value=" Send ">
</form>
</body>
</html> 

When the user fills in the form and hits the Send button, the mail.php file is called using POST. I have used the validate function to be found in my email validation tutorial.

<html>
<head><title>PHP Mail Sender</title></head>
<body>
<?php 
/* We should really check for each variable existing, but I’ll trust myself not to be bad
For a live site, variable testing should be used. */
$email = $HTTP_POST_VARS['email'];
$subject = $HTTP_POST_VARS['subject'];
$message = $HTTP_POST_VARS['message'];
// check for a valid email address using validate function (see link above for function)
// check there is a subject
if (!validate($email)) {
    echo "<h4>Invalid email address</h4>";
    echo "<a href='javascript:history.back(1);'>Back</a>";
} 
elseif ($subject == "") {
    echo "<h4>No subject</h4>";
    echo "<a href='javascript:history.back(1);'>Back</a>";
} 
elseif (mail($email,$subject,$message)) {
    echo "<h4>Thank you for sending email</h4>";
} 
else {
    echo "<h4>Can't send email to $email</h4>";
}
?>
</body>
</html> 

As you see, the script is simply one if … elseif … else statement. At first, it validates the required form fields. Note that PHP form validation is performed on the server, after sending all the data. Therefore, it would be a good idea to combine server-side form validation with PHP and client-side form validation with JavaScript in order to avoid unnecessary data sending.

If the email address is valid and subject isn’t empty, the script sends the mail and displays the corresponding message. Note how the variable $email is included into the output string.

You can also use this script to implement the safe "Contact Us" function on your website. Your visitors will be able to send you a message, but your email address won’t be displayed on the page and spam bots, that parse pages looking for potential email addresses, won’t get it.

Just remove the Email text field from the form and replace the first line of the script with something like…

$email = 'YourAddr@YourMail.com';

skipping in and out of PHP

When embedding PHP within HTML, you can close your PHP tag whenever you want to output HTML. This enables speedier processing of your PHP. For instance:

<?php if($option_01) { ?>   
    <div class='option_01'>     
    option_01 is chosen   
    </div>
<?php } elseif (option_02) { ?>   
    <div class='option_02'>    
    option_02 is chosen   
    </div>
<?php } else { ?>   
    <div class='option_03'>     
    option_03 is chosen by default   
    </div> 
<?php } ?>

Looks exciting and scary I know but, really, all this is doing is decreasing processor time and usage. PHP checks the options, and steps outside and deals with HTML only if needed. Small savings for the script above, but if this is consistently implemented in larger scripts the savings are worth it.

quick update: how to force vertical scrollbar with CSS

Still studying hard for exams over the next few weeks, but I took a quick lunch-break today and “relaxed” by doing a bit more web work. I came across the problem that some of my pages for a site were less than the height of the browser window, while others were longer. The result of this is that you get some “flickering” when navigating to different pages that don’t require a scrollbar as the layout shifts back and forth slightly if the browser doesn’t have a permanent scrollbar gutter..

The solution is to force a vertical scrollbar. This works well in all widely used browsers with only a few lines of code as the document height will always be at least one pixel longer. Just insert the following into your CSS:

html, body {
height: 100%;
margin: 0 0 1px;
padding: 0;
}

What the method above does is set your site’s height to 100 percent with a bottom margin of 1 pixel to force the vertical scrollbars to appear with at least one pixel to scroll. The advantage of this is that this works no matter what the visitor’s resolution is; and you don’t need to manually set the page height.

HTML special character reference table

You may not be able to enter certain symbols or characters into your web page using a single key or character. The following HTML 4 character reference table can be used to enter such special characters using the associated “numeric character reference” code or the “character entity reference” code. Note that not all characters are supported by every browser. Some browsers may support the numeric reference without supporting the character entity reference.

Numeric character reference (“ID” column in the table) is the numeric representation of a given character. To use the numeric character reference in your HTML code, use the following format:
&#Numeric character reference;
For example, to display the © symbol using the numeric character reference, enter:©

Character entity reference (“Code” column in the table) is the standard name of a given character. To use the character entity reference in your HTML code, use the following format instead:
&Character entity reference;
For example, to display the © symbol using the character entity reference:
&copy;

- ID Code - Description
Á 193 Aacute 1 latin capital letter A with acute
á 225 aacute 1 latin small letter a with acute
â 226 acirc 1 latin small letter a with circumflex
 194 Acirc 1 latin capital letter A with circumflex
´ 180 acute 1 acute accent
æ 230 aelig 1 latin small letter ae
Æ 198 AElig 1 latin capital letter AE
À 192 Agrave 1 latin capital letter A with grave
à 224 agrave 1 latin small letter a with grave
8501 alefsym L alef symbol
Α 913 Alpha G greek capital letter alpha
α 945 alpha G greek small letter alpha
& 38 amp C ampersand
8743 and M logical and
8736 ang M angle
å 229 aring 1 latin small letter a with ring above
Å 197 Aring 1 latin capital letter A with ring above
8776 asymp M almost equal to
à 195 Atilde 1 latin capital letter A with tilde
ã 227 atilde 1 latin small letter a with tilde
Ä 196 Auml 1 latin capital letter A with diaeresis
ä 228 auml 1 latin small letter a with diaeresis
8222 bdquo U double low-9 quotation mark
Β 914 Beta G greek capital letter beta
β 946 beta G greek small letter beta
¦ 166 brvbar 1 broken bar
8226 bull P bullet
8745 cap M intersection
Ç 199 Ccedil 1 latin capital letter C with cedilla
ç 231 ccedil 1 latin small letter c with cedilla
¸ 184 cedil 1 cedilla
¢ 162 cent 1 cent sign
χ 967 chi G greek small letter chi
Χ 935 Chi G greek capital letter chi
ˆ 710 circ D modifier letter circumflex accent
9827 clubs S black club suit
8773 cong M approximately equal to
© 169 copy 1 copyright sign
8629 crarr A downwards arrow with corner leftwards
8746 cup M union
¤ 164 curren 1 currency sign
8224 dagger U dagger
8225 Dagger U double dagger
8659 dArr A downwards double arrow
8595 darr A downwards arrow
° 176 deg 1 degree sign
Δ 916 Delta G greek capital letter delta
δ 948 delta G greek small letter delta
9830 diams S black diamond suit
÷ 247 divide 1 division sign
é 233 eacute 1 latin small letter e with acute
É 201 Eacute 1 latin capital letter E with acute
Ê 202 Ecirc 1 latin capital letter E with circumflex
ê 234 ecirc 1 latin small letter e with circumflex
è 232 egrave 1 latin small letter e with grave
È 200 Egrave 1 latin capital letter E with grave
8709 empty M empty set
8195 emsp U em space
8194 ensp U en space
ε 949 epsilon G greek small letter epsilon
Ε 917 Epsilon G greek capital letter epsilon
8801 equiv M identical to
Η 919 Eta G greek capital letter eta
η 951 eta G greek small letter eta
ð 240 eth 1 latin small letter eth
Ð 208 ETH 1 latin capital letter ETH
ë 235 euml 1 latin small letter e with diaeresis
Ë 203 Euml 1 latin capital letter E with diaeresis
8364 euro U euro sign
8707 exist M there exists
ƒ 402 fnof I latin small f with hook
8704 forall M for all
½ 189 frac12 1 vulgar fraction one half
¼ 188 frac14 1 vulgar fraction one quarter
¾ 190 frac34 1 vulgar fraction three quarters
8260 frasl P fraction slash
Γ 915 Gamma G greek capital letter gamma
γ 947 gamma G greek small letter gamma
8805 ge M greater-than or equal to
> 62 gt C greater-than sign
8660 hArr A left right double arrow
8596 harr A left right arrow
9829 hearts S black heart suit
8230 hellip P horizontal ellipsis
í 237 iacute 1 latin small letter i with acute
Í 205 Iacute 1 latin capital letter I with acute
î 238 icirc 1 latin small letter i with circumflex
Î 206 Icirc 1 latin capital letter I with circumflex
¡ 161 iexcl 1 inverted exclamation mark
Ì 204 Igrave 1 latin capital letter I with grave
ì 236 igrave 1 latin small letter i with grave
8465 image L blackletter capital I
8734 infin M infinity
8747 int M integral
Ι 921 Iota G greek capital letter iota
ι 953 iota G greek small letter iota
¿ 191 iquest 1 inverted question mark
8712 isin M element of
Ï 207 Iuml 1 latin capital letter I with diaeresis
ï 239 iuml 1 latin small letter i with diaeresis
Κ 922 Kappa G greek capital letter kappa
κ 954 kappa G greek small letter kappa
λ 955 lambda G greek small letter lambda
Λ 923 Lambda G greek capital letter lambda
9001 lang T left-pointing angle bracket
« 171 laquo 1 left-pointing double angle quotation mark
8592 larr A leftwards arrow
8656 lArr A leftwards double arrow
8968 lceil T left ceiling
8220 ldquo U left double quotation mark
8804 le M less-than or equal to
8970 lfloor T left floor
8727 lowast M asterisk operator
9674 loz E lozenge
8206 lrm U left-to-right mark
8249 lsaquo U single left-pointing angle quotation mark
8216 lsquo U left single quotation mark
< 60 lt C less-than sign
¯ 175 macr 1 macron
8212 mdash U em dash
µ 181 micro 1 micro sign
· 183 middot 1 middle dot
8722 minus M minus sign
Μ 924 Mu G greek capital letter mu
μ 956 mu G greek small letter mu
8711 nabla M nabla
160 nbsp 1 no-break space
8211 ndash U en dash
8800 ne M not equal to
8715 ni M contains as member
¬ 172 not 1 not sign
8713 notin M not an element of
8836 nsub M not a subset of
ñ 241 ntilde 1 latin small letter n with tilde
Ñ 209 Ntilde 1 latin capital letter N with tilde
Ν 925 Nu G greek capital letter nu
ν 957 nu G greek small letter nu
ó 243 oacute 1 latin small letter o with acute
Ó 211 Oacute 1 latin capital letter O with acute
Ô 212 Ocirc 1 latin capital letter O with circumflex
ô 244 ocirc 1 latin small letter o with circumflex
Œ 338 OElig O latin capital ligature OE
œ 339 oelig O latin small ligature oe
ò 242 ograve 1 latin small letter o with grave
Ò 210 Ograve 1 latin capital letter O with grave
8254 oline P overline
ω 969 omega G greek small letter omega
Ω 937 Omega G greek capital letter omega
Ο 927 Omicron G greek capital letter omicron
ο 959 omicron G greek small letter omicron
8853 oplus M circled plus
8744 or M logical or
ª 170 ordf 1 feminine ordinal indicator
º 186 ordm 1 masculine ordinal indicator
Ø 216 Oslash 1 latin capital letter O with stroke
ø 248 oslash 1 latin small letter o with stroke
Õ 213 Otilde 1 latin capital letter O with tilde
õ 245 otilde 1 latin small letter o with tilde
8855 otimes M circled times
Ö 214 Ouml 1 latin capital letter O with diaeresis
ö 246 ouml 1 latin small letter o with diaeresis
182 para 1 pilcrow sign
8706 part M partial differential
8240 permil U per mille sign
8869 perp M up tack
φ 966 phi G greek small letter phi
Φ 934 Phi G greek capital letter phi
Π 928 Pi G greek capital letter pi
π 960 pi G greek small letter pi
ϖ 982 piv G greek pi symbol
± 177 plusmn 1 plus-minus sign
£ 163 pound 1 pound sign
8243 Prime P double prime
8242 prime P prime
8719 prod M n-ary product
8733 prop M proportional to
ψ 968 psi G greek small letter psi
Ψ 936 Psi G greek capital letter psi
34 quot C quotation mark
8730 radic M square root
9002 rang T right-pointing angle bracket
» 187 raquo 1 right-pointing double angle quotation mark
8658 rArr A rightwards double arrow
8594 rarr A rightwards arrow
8969 rceil T right ceiling
8221 rdquo U right double quotation mark
8476 real L blackletter capital R
® 174 reg 1 registered sign
8971 rfloor T right floor
Ρ 929 Rho G greek capital letter rho
ρ 961 rho G greek small letter rho
8207 rlm U right-to-left mark
8250 rsaquo U single right-pointing angle quotation mark
8217 rsquo U right single quotation mark
8218 sbquo U single low-9 quotation mark
Š 352 Scaron O latin capital letter S with caron
š 353 scaron O latin small letter s with caron
8901 sdot M dot operator
§ 167 sect 1 section sign
­ 173 shy 1 soft hyphen
Σ 931 Sigma G greek capital letter sigma
σ 963 sigma G greek small letter sigma
ς 962 sigmaf G greek small letter final sigma
8764 sim M tilde operator
9824 spades S black spade suit
8834 sub M subset of
8838 sube M subset of or equal to
8721 sum M n-ary sumation
8835 sup M superset of
¹ 185 sup1 1 superscript one
² 178 sup2 1 superscript two
³ 179 sup3 1 superscript three
8839 supe M superset of or equal to
ß 223 szlig 1 latin small letter sharp s
Τ 932 Tau G greek capital letter tau
τ 964 tau G greek small letter tau
8756 there4 M therefore
Θ 920 Theta G greek capital letter theta
θ 952 theta G greek small letter theta
ϑ 977 thetasym G greek small letter theta symbol
8201 thinsp U thin space
Þ 222 THORN 1 latin capital letter THORN
þ 254 thorn 1 latin small letter thorn with
˜ 732 tilde D small tilde
× 215 times 1 multiplication sign
8482 trade L trade mark sign
ú 250 uacute 1 latin small letter u with acute
Ú 218 Uacute 1 latin capital letter U with acute
8657 uArr A upwards double arrow
8593 uarr A upwards arrow
û 251 ucirc 1 latin small letter u with circumflex
Û 219 Ucirc 1 latin capital letter U with circumflex
Ù 217 Ugrave 1 latin capital letter U with grave
ù 249 ugrave 1 latin small letter u with grave
¨ 168 uml 1 diaeresis
ϒ 978 upsih G greek upsilon with hook symbol
υ 965 upsilon G greek small letter upsilon
Υ 933 Upsilon G greek capital letter upsilon
ü 252 uuml 1 latin small letter u with diaeresis
Ü 220 Uuml 1 latin capital letter U with diaeresis
8472 weierp L script capital P
ξ 958 xi G greek small letter xi
Ξ 926 Xi G greek capital letter xi
ý 253 yacute 1 latin small letter y with acute
Ý 221 Yacute 1 latin capital letter Y with acute
¥ 165 yen 1 yen sign
ÿ 255 yuml 1 latin small letter y with diaeresis
Ÿ 376 Yuml O latin capital letter Y with diaeresis
Ζ 918 Zeta G greek capital letter zeta
ζ 950 zeta G greek small letter zeta
8205 zwj U zero width joiner
8204 zwnj U zero width non-joiner
LEGEND
Section Description
P General punctuation
A Arrows
1 General characters
C Controls and basic latin
S Miscellaneous symbols
D Spacing modified letters
T Miscellaneous technical characters
U General punctuation (special characters)
E Geometric shapes
G Greek symbols
I Latin extended B
L Letterlike symbols
M Mathematical operators
O Latin extended A

[sourced from International Organization for Standardization 1986 via chami.com]

a brief discussion of securing PHP input

A very brief tutorial/comment on securing inputs in your PHP script to prevent HTML, JavaScript, SQL or other injection type attacks. There is basically nothing to this, it is more a matter of using a bit of common sense and not leaving open doors which are extremely simple to close without effort.

A PHP input takes in variables from a user either from a form, or directly from the URL linking to the page. In either case, a malicious user can insert data which contains scripting elements and distorts your page or, much worse, alters or gives access to your database and/or site admin. General input error checking works, but only for data entered through your site (example form.php below).

<html>
<head>
....
</head>
<body>
<form action="action.php">
<input type="text" name="urlfield" maxlength="80" length="20">
<br />
<input type="text" name="inputfieldtext" maxlength="40" length="20">
<br />
<input type="password" name="inputfieldpass" maxlength="40" length="20">
<br />
<input type="submit" name="submit" value="submit">

</form>
</body>
</html>

A malicious user can point a URL to your site, which they then populate with data themselves from their end. For example they make a form on their own site, which points to your results page, thereby avoiding your data integrity check before submission. In order to “allow” for this, and prevent the malicious user’s efforts getting through and doing damage, sterilising should be performed on the input before using it (example action.php below).

<?php
$url= htmlspecialchars($_REQUEST['urlfield']);
$text = htmlspecialchars($_REQUEST['inputfieldtext']);
$pass= htmlspecialchars($_REQUEST['inputfieldpass']);
?>

or to apply it to a more “dangerous” scenario where a fuller spectrum of special characters are used:

<?php
$input= htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $input; // &lt;a href='test'&gt;Test&lt;/a&gt;
?>

What this does is take any input data and use PHP’s inbuilt htmlspecialchars($str[, ENT_QUOTES]) function to encode HTML’s special characters so that they are not interpreted by the browser. I use the ENT_QUOTES option in order to include single quotes in the encoding. For absolute encoding use PHP’s htmlentities($str[, ENT_QUOTES]) function. This encodes ALL HTML special characters, while htmlspecialchars($str[, ENT_QUOTES]) only encodes the basic HTML special characters, which is normally useful enough for most everyday web programming.

Dynamic JavaScript generation with PHP

Creating dynamic JavaScript on the fly can be useful when needing to target differing dynamically generated xml files for example. In my example below, I am creating the xml as I do here, and then using the dynamic JS to pass this new xml to a Flash template for display on the fly. The necessity for a dynamic JS script in this case is that the name of the xml changes dynamically, and also the JS script is named dynamically with a random value in order to prevent caching of the script.

To begin, the script is predominantly static, and is simply written to a JS file. Make sure every line is ended with the \r\n chararcters in order to be correctly written to the file. Essentially as below. I am using dynamic variables for the Flash height and the xml name:

<?php

$xyz = fopen("xml/".$jsname, "w");

fwrite($xyz, "<!--\r\n");
fwrite($xyz, "if (AC_FL_RunContent == 0 || DetectFlashVer == 0) {\r\n");
fwrite($xyz, " alert(\"This page requires AC_RunActiveContent.js.\");\r\n");
fwrite($xyz, "} else {\r\n");
fwrite($xyz, " var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);\r\n");
fwrite($xyz, " if(hasRightVersion) {\r\n");
fwrite($xyz, " AC_FL_RunContent(\r\n");
fwrite($xyz, " 'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',\r\n");
fwrite($xyz, " 'width', '870',\r\n");
fwrite($xyz, " 'height', '".$heightval."',\r\n");
fwrite($xyz, " 'scale', 'noscale',\r\n");
fwrite($xyz, " 'salign', 'TL',\r\n");
fwrite($xyz, " 'bgcolor', '#777788',\r\n");
fwrite($xyz, " 'wmode', 'transparent',\r\n");
fwrite($xyz, " 'movie', 'flash',\r\n");
fwrite($xyz, " 'src', 'flash',\r\n");
fwrite($xyz, " 'FlashVars', 'library_path=flash/librarypath&xml_source=xml/".$xmlname."',\r\n");
fwrite($xyz, " 'id', 'my_flash',\r\n");
fwrite($xyz, " 'name', 'my_flash',\r\n");
fwrite($xyz, " 'menu', 'true',\r\n");
fwrite($xyz, " 'allowFullScreen', 'true',\r\n");
fwrite($xyz, " 'allowScriptAccess','sameDomain',\r\n");
fwrite($xyz, " 'quality', 'high',\r\n");
fwrite($xyz, " 'align', 'middle',\r\n");
fwrite($xyz, " 'pluginspage', 'http://www.macromedia.com/go/getflashplayer',\r\n");
fwrite($xyz, " 'play', 'true',\r\n");
fwrite($xyz, " 'devicefont', 'false'\r\n");
fwrite($xyz, " );\r\n");
fwrite($xyz, " } else {\r\n");
fwrite($xyz, " var alternateContent = 'This content requires the Adobe Flash Player. '\r\n");
fwrite($xyz, " + '<a href="http://www.macromedia.com/go/getflash/">Get Flash</a>.';\r\n");
fwrite($xyz, " document.write(alternateContent);\r\n");
fwrite($xyz, " }\r\n");
fwrite($xyz, "}\r\n");
fwrite($xyz, "// -->\r\n");

fclose($xyz);

?>

As you can see, I pass in variables $jsname, $xmlname, and $heightval which are used to construct the script. This is then called by setting a dynamic call to the JS script within the webpage itself using PHP, as below:

<?php

$rndnum = rand(1234, 9876);
$jsname = "script_name_".$rndnum.".js";
// make the JavaScript here
echo '';

?>

This can be linked to a script to create XML dynamically, as here, and there you have a truly dynamic display.

Follow

Get every new post delivered to your Inbox.