Fun with PHP

So you want to learn how to program in PHP? Well maybe not, but for those of you that do, you’re in the right place. PHP adds a whole new dimension to traditional website design. Some common uses are multi-part page compilation (header + content + footer), dynamic content, and database interaction. This article is best suited for someone who already knows HTML, and wants to learn how to write dynamic and interactive websites. If this sounds like you, then read on, and enjoy!

<?php

echo "test";

?>

To make the most of this quick lesson, you should get access to a PHP installation so that you can test out the code for yourself. PHP is available to download for all major operating systems at PHP. A text editor with syntax highlighting is also highly beneficial. For Windows, I prefer phpDesigner 2007. It has a great feature where it will allow you to instantly refresh PHP output if you have PHP locally installed. For Mac, I would recommend my new favorite, Coda – although this isn’t free. (Have a free Mac favorite? Let me know in the comments!) And, if you are cool enough to be using Linux, then you probably already have a favorite. But if you don’t, then try Gnome’s gedit. Now that you have all of this taken care of, you are ready to start programming!

Variables

The concept of variables is what allows a website to be dynamic. A variable is simply used to store a value, which can then be recalled and modified later in a program. PHP is a loosely typed language, which means that variables are easy to create. This also means that it is easy to get confused when there are a lot of variables in scope. You are not even required to declare variables in PHP, but it is good practice to do so and PHP will most likely issue a warning if you don’t. Below are some examples of declaring, using, and modifying variables.

<?php // your code will be considered HTML if you don't include this

// File: A Basic PHP Script (test.php)
// Date: Today
// Author: You!/code

// Initializing Variables
$str = 'Hi! This is a string!';
$num = 1;

// Printing to Browser / Screen
echo $str . '<br />'; // <br /> added for clarity
print $str . '<br />'; // print is equivalent to echo

// Adding Variables
$str = $str . ' And this is something added to the string!';
echo "$str<br />"; // double quotes evaluate variables unlike single quotes

$num += 1 + 5;
echo ($num - 2) . '<br /><br />'; // variables are always output as strings

?> <!-- Equally important closing tag -->

Hey... I'm just HTML, and I'm boring. :'(

Conditionals

Conditionals are used to control the flow of a program. Let’s say, for example, that you wanted to print out different text depending on the value of a number. Another use of conditionals might be to make sure that a form submission isn’t empty before saving it to a database. Make sure you’re trying this out on your own!

// Execute the following block of code if $num is 1 or 2 
if($num == 1 || $num == 2) { 
    // you can also use && to require multiple conditions 
    // '=' set a value, '==' tests a value 
    // (also '===' sees if something is identical, but this isn't used often) 
    echo "$num is $num<br />
"; // '\' is the escape character 
} 
elseif($num > 1) { 
    echo '$num is greater than two<br />'; 
} 
else echo '$num is less than one!<br />';

Loops

Loops are useful for executing code blocks multiple times and iterating through data sets. Below are some basic examples of loops. The arrays section that follows will provide an example of data set iteration.

// do something five times 
for($i = 0; $i < 5; $i++) { 
    echo "the number is $i<br />
"; 
} // i will be 0, 1, 2, 3, and finally 4 (not 5!) 

// loop until the given condition is satisfied 
$str = 'hello there!'; 
$reverse = ''; 
while(strlen($str) > 0) { 
    $reverse = $str{0} . $reverse; 
    $str = substr($str, 1); 
} 
echo "$reverse<br />
"; // output: !ereht olleh

Arrays

Arrays are simply a bunch of variables squished together under a common name. The different variables stored inside of an array are usually related to each other in some way. For example, the array variables might be of the same type, like a collection of form variables, or a list of user accounts.

// Declaring arrays and the items inside 
$arr = array(); //empty 
$arr = array('hello', 'key' => 'value', 'empty array' => $arr); 
$arr[1880] = 'Best year ever!'; 
$arr[] = $array[1880]; 

// Iterating through an array 
for($i = 0; $i < count($arr); $i++) { 
    echo "item $i, "; 
} 

foreach($arr as $key => $value) { 
    echo "key: $key value: $value "; 
} 

// Implode / Explode 
$zuanich = explode('|', '1|2|3|4|5|6'); // we now have an array! 
echo implode(', ', $zuanich); // output: 1, 2, 3, 4, 5, 6

Functions

These little beauties are great for simplifying common tasks. This first example simply returns the current time in milliseconds since the Unix Epoch (the year 1970). I’ll show you why I’ve written this in the next example.

// Used to calculate time. 
function getmicrotime() { 
   list($usec, $sec) = explode(' ', microtime()); 
   return 1000000*((float)$usec + (float)$sec); 
}

Now, we’ll find the nth number of the Fibonacci sequence using two different methods. For some additional fun, I’ve timed both of the functions using the previous function. If all goes well, the first method should yield a shorter execution time. (There is a precise reason for this, and a constant relationship between the two times, but I won’t go into that.)

// Find fibonacci to a given number 
function fibonacci1($number) { 
    $new_number = 0; 

    for($i = $number; $i > 0; $i--) { 
        $new_number += $i; 
    } 
     
    return $new_number; 
} 

echo '<br />Fibonacci Test 1:<br />'; 
$start = getmicrotime(); 
echo fibonacci1(100); 
echo '<br />(this took ' . round((getmicrotime() - $start), 5) . ' microseconds)'; 

// calculating fibonacci using recursion 
function fibonacci2($n) { 
    if($n > 1) return $n+fibonacci2($n-1); 
    else return 1; 
} 

echo '<br /><br />Fibonacci Test 2:<br />'; 
$start = getmicrotime(); 
echo '' . fibonacci2(100); 
echo '<br />(this took ' . round((getmicrotime() - $start), 5) . ' microseconds)';

Practical Applications

We’re almost done! And now you’ll actually have some useful snippets too! One of the biggest pains about writing a multi-page HTML-only website, is updating the navigation in each page whenever you change something. Enter PHP, to the rescue, with a quick and easy fix. The easiest solution is to store your header, footer, and/or navigation HTML in separate files and have PHP include them before sending out each of the individual pages. This allows you to make a change in the includes files and have it affect each page of your website.

<?php 
// Include common navigation file 
include(getenv('DOCUMENT_ROOT') . '/navigation.php'); // standard include 

/* other include functions: 
include_once() - prevents accidental inclusions of the same file more than once 
require() - error out if the page cannot be included 
require_once() - obvious, this is what i generally use 
*/ 
?> 
the rest of your HTML document

The last example demonstrates one of the greatest uses of PHP: form submission. Forms allow users to interact with your website. Most forms all have the same structure of 1 part HTML and 1 part PHP. The following example collects data from a form and emails it to a given address.

<?php 
// Process form submission 
if(isset($_POST['name'])) { // $_POST is an automatically created global variable 
    $subject = 'Contact Form Submission'; 
    $to = 'webmaster@yoursite.com'; 
    $from = 'Yoursite <form@yoursite.com>'; 

    $body = 'Name: ' . $_POST['name'] . "
"; 
    $body .= 'Email: ' . $_POST['email'] . "
"; 
    $body .= 'Message: ' . $_POST['message']; 
     
    // Send Email 
    if(mail($to, $subject, $body, "From: $from")) 
        echo("<p>Message successfully sent!</p>"); 
    else echo("<p>Message delivery failed...</p>"); 
} 
?> 
<html> 
<head> 
<title>Contact Form</title> 
</head> 

<body> 

<form action="?" method="post"> 
    Name: <input type="text" name="name" /><br /> 
    Email: <input type="text" name="email" /><br /> 
    Message: <textarea name="message"></textarea><br /><br /> 
    <input type="submit" value="Send!" /> 
</form> 

</body> 
</html>

Well, that’s all I’ve got for you! What did you think of programming in PHP? Easy enough, huh? If you have a desire to learn more, Google and PHP.net are always excellent resources. I might even post a more advanced PHP article in the future!

Leave me a comment, and let me know what you thought of the article. Thanks for reading my blog!

Leave a Reply

Your email address will not be published. Required fields are marked *