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.

Advertisements

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).