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.