word-wrapping with PHP

A simple function to wrap text to a defined length using PHP. It takes a string as input, and returns a string with <br /> inserted to wrap the text on the page.

function word_wrap($text) {
    // Define the characters to display per row
    $chars = "10";
    $text = wordwrap($text, $chars, "<br />", 1);
    return $text;
}

Pretty self-explanatory really,  having defined the number of characters within your function, the input text is passed to the in-built PHP function along with the number of characters; then the wrapped text is passed back to you.

password protect a page with PHP

Password protection for a single page. Visitors are required to enter a password and username into a login form to view the page content. By default the password entry form is displayed, unless the both the password and username match; in that case the “protected content” is displayed. As this is served from server side, the protected content is secure at your end and will not display using “View Source”.

<?php
// Define your username and password
$username = "someuser";
$password = "somepassword";

if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) { 
?> 

<h1>Login</h1> 
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="txtUsername">Username:</label>
<input type="text" title="Enter your Username" name="txtUsername" />
<label for="txtpassword">Password:</label>
<input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" /> 
</form>

<?php 
}
else { 
?> 

<p>This is the protected page. Your private content goes here.</p>
 
<?php 
} 
?> 

This is a simplistic demonstration of the concept so, to maintain security on a live site, it would be best to store the username and password details in a config.inc file (or equivalent).

display page visitor information with PHP

It’s easy to retrieve and display information about page visitors with PHP using predefined variables. eg to show IP address, referrer and browser type:

<?php
// Display users IP address
echo "

IP Address: " . $_SERVER['REMOTE_ADDR'] . "

"; // Display users port number echo "

Port Number: " . $_SERVER['REMOTE_PORT'] . "

"; // Display users host name // see note below for using this echo "

Host Name: " . $_SERVER['REMOTE_HOST'] . "

"; // Display the URI used to access this page (entire request path, including query string) echo "

Request URI: " . $_SERVER['REQUEST_URI'] . "

"; // Display the URL used to access this page (request path without query string) echo "

Request URL: " . $_SERVER['REQUEST_URL'] . "

"; // Display the referrer echo "

Referrer: " . $_SERVER['HTTP_REFERER'] . "

"; // Display users browser type echo "

Browser: " . $_SERVER['HTTP_USER_AGENT'] . "

"; ?>
Note: To use $_SERVER['REMOTE_HOST'], your web server must be configured to create this variable. For example in Apache you’ll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

You can utilise this in many ways, whether it in order to display different information to visitors based on their browser or operating system; or to record this information yourself for building a better site which meets the needs of users better.

Check the php.net listing of $_SERVER variables for more predefined variables you can utilise.

easy display of last modified time for files using PHP

Not so much use for any websites I’ve built so far, but this will be useful for download pages to enable them to display the date of the current build or builds etc.

This script outputs the date and time that a file was last modified. You can format it any way you want.

<?php
$last_modified = filemtime("MY_FILE.txt"); // Insert your file name here
echo "Last modified " . date("l, dS F, Y @ h:ia", $last_modified); 
// eg. Last modified Tuesday, 30th March, 2010 @ 04:23pm
?> 

By using this with any file download, you can have your pages automatically update when you replace the downloadable files with alternate versions. Just make sure the file name is still the same.

display page load time with PHP

A quick smidgen of code, which outputs the time in seconds that it takes for a PHP page to load. This provides a neat way of having a listing at the bottom of your page advertisin ghow quickly it loads.

At the very top of your page insert the following code :

<?php
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$start = $time; 
?>

And at the very end of your page the following:

<?php
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$finish = $time;
$totaltime = ($finish - $start);
echo “This page took {$totaltime} seconds to load.";
?> 

And there you have it, nothing dramatic or earth-shattering, but it works.

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';

emulate an iPhone with Firefox

Firefox has the ability to spoof the header fields and enable you to be a different browser or operating system. For example, pretending to be an iPhone so you can access iPhone only sites.

Step 1:

Go to Mozilla.org and install the Firefox plugin.

Step 2:

In your browser, go to Tools > Default User Agent > User Agent Switcher > Options. Select New > New User Agent .

Step 3:

In the ‘Description’ field give it a name (ie iPhone 3.0) and in the User Agent Field enter the following:

Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A102 Safari/419 (United States)

If you want to use a different mobile phone user agent you can get a list of them here (via Wikipedia).

page view counter in php

Creating a visible page counter is not as hard as it may sound. Like most sites, I have a database to monitor traffic, however it seems like major overkill to make DB requests and updates just to display a visitor count on a page. It is much simpler to have a hard file which maintains this count for you.

I am using a count.dat file, but if you want to track this for multiple pages, it is best to name multiple files such as hp_count.dat, contact_count.dat etc (bear in mind that if you have too many pages all doing this, you will end up with a plethora of dat files to be referenced, so tidy them into their own folder). The code below inserted into a page counts the visitors and display the results dynamically.

<?php
if(file_exists("count.dat")) {
    $exist_file = fopen("count.dat", "r");
    $new_count = fgets($exist_file, 255);
    $new_count++;
    fclose($exist_file);
    // to be invisible counter comment out next line;
    print("$new_count people have visited this page");
    $exist_count = fopen("count.dat", "w");
    fputs($exist_count, $new_count);
    fclose($exist_count);
}
else {
    $new_file = fopen("dat_folder/count.dat", "w");
    fputs($new_file, "1");
    fclose($new_file);print("you are visitor number 1"); 
}
?> 

To insert the code to a page where you want the counter displayed you would use the following code:

<?php require("count.dat"); ?> 

This is a very basic script which just counts the hits to a single page but, as I said above, you can reuse it easily to track multiple pages.

Counting only bookmark and type-in traffic

Using the $HTTP_REFERER variable we can determine in most cases where a visitor has come from. The reason we can’t guarantee this all the time is because of anonomizer programs which spoof or block this environment variable from recording accurate information. For this example I am being simplistic, so I have ignored the potential problems associated with this. When a surfer bookmarks your page or types your page URL into the browser window the $HTTP_REFERER variable will usually be blank.

So if I only wanted to count bookmarkers to a page I would add the following lines of code before the counting routine to the code above:

if($HTTP_REFERER != "") {
    //add one to the count and update the count.dat file
} 

If you add the code above you’ll see it will only increment the counter if you type the URL into your browser or come from a bookmark. You can also hit refresh after you have typed in or come from a bookmark to increment the counter.

However, if you come from any hyperlink your visitors page count will not be incremented. Remember that the != means not equal to; and when you say != "" it means that as long as there is something there, they must have come from other means than bookmark or type-in. I sometimes notice the words "bookmark" you could also add the regular expression to ignore case and look for the work bookmark by adding a second loop inside the above one:

if(eregi("bookmark", $HTTP_REFERER) {
    // I found the word "bookmark" so don't count this visitor
} 

So there you have it, a quick and simple visitor counter in PHP, along with some directions for adding a lot more functionality to it.

Apple store outage

The Apple Store has been down for quite a few hours today/tonight. Twitter reports are just that it is down, with no actual reasons yet. All Apple is saying is what is on the site, which is just a “We’ll be back soon” logo. Apparently they’re updating the store, but it wouldn’t normally be expected to be done at such a peak usage time.

Being one week before the iPad release, we can only conjecture that they are reformatting the store for iPad apps and content. I’m not going to bother guessing, because we’ll all be able to see what is what very soon I’m sure.

roadtrip weekend

I’ve been on a roadtrip for the last three days. Headed down to Napier on Friday, before spending all of Saturday enjoying the privilege of being at my good friends Hamish and Julie’s wedding and celebration, and then driving back to Auckland today.

I need to acknowledge how good looking Hamish is, and I think the best way to express this is with a photo:

Hamish_is_sexy

Yabba Dabba Doo!! Julie is one lucky lady!

The weather was perfect yesterday, with brilliant sunshine before, during and after the wedding; then for the pre-reception drinks in an olive grove, before dinner in the vineyard restaurant. Fabulous time was had by all. I’ll post and link some more photos of the actual day, once my internets is working properly.