Math For Kids

I just created a couple of PHP scripts for my nephew to help him with his math. Actually, any kid or adult can use it. The program performs some basic mathematics such as addition, subtraction, multiplication and division. The numbers and result are totally random. You will get a different set of numbers and result each time. You can play with it as long as you want, and as often as you like.

The result of each equation is hidden when the page is initially loaded. You can click the “Display Answer” link to reveal the answer. Clicking the “New Question” link will generate a different set of random numbers. Navigation is located at the top. You can select: Addition, Subtraction, Multiplication and Division. Give it a try.

Just a couple of other things that I wanted to mention. I’m using Javascript to hide the answers when the documents are initially loaded. The math result is contained inside a hidden div. The div is toggled on or off or displayed or hidden, by simply clicking on a link. The Javascript that I use can be viewed and copied if you look at the source.

In addition, I’m using simple a rand() function to generate a set of numbers. I use basic PHP math operations to perform the math operations. I do a couple of checks in subtraction and division scripts to avoid the following: subtraction which results in negative number, division by zero, and a divisible number, meaning no remainders when performing divisions. The scripts can be easily modified.

Examples

Addition

$a = rand(0, 20);  // This generates a random number between 0 and 20.
$b = rand(0, 20);  // This generates a random number between 0 and 20.
$c = $a + $b; // Performs addition

Subtraction

$a = rand(0, 20);  // This generates a random number between 0 and 20.
$b = rand(0, 20);  // This generates a random number between 0 and 20.
if ($a>$b) {$c=$a-$b;} else {$c=$b-$a;}  // No negative results

Division

$a = rand(2, 100);  // This generates a random number between 2 and 100.
$b = rand(2, 100);  // This generates a random number between 2 and 100.
do {
$c = $a / $b;
} while ($a % $b != 0) // Checks if result is divisible

It was a fun little project.

Replace eregi with preg_match

A couple of weeks ago, I wrote a small PHP code to validate if the url being passed is in fact valid. I used a regular expression and PHP’s eregi function to find a pattern match. Looking back, the problem is, the eregi function is deprecated in PHP 5.3.0.

For compatibility going forward, we need to replace eregi with the preg_match function which is better suited for regular expression matches. We will use the same example as last time. As you recall, the function was:

Code With eregi

$urlregex = "^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$";
 
if (eregi($urlregex, $_POST['url'])) {
//  url is valid. shorten long url
} else {
// reject. url is invalid
}

Code with preg_match

$urlregex = "^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$";
 
if(!preg_match($urlregex, $_POST['url']))
// reject. url is invalid //
} else {
url is valid. shorten long url
}

Here, we’ve sucessfully replaced the eregi function with preg_match.

Form Validation Callbacks Within CodeIgniter

There are many ways to add form validation within CodeIgniter. One way is by extending the form validation library with your own. Another way is by using callbacks. CodeIgniter support callbacks to form validation. I would like to show how callbacks can be added to the existing form validation set of rules.

Validation Rules

Here’s a typical form validation rule where the ‘url’ field is required.

$this->form_validation->set_rules(‘url’, ‘URL’,'required’ );

Validation Rules with Callbacks

This is how you add callbacks. Notice the ‘callback’ prefix.

$this->form_validation->set_rules(‘username’, ‘Username’, ‘callback_url_check’);

The Callback Function

The callback function. The ‘callback’ prefix is omitted.

function url_check() { 
  $regex = “your reg ex code here”;
  if(!preg_match($regex, $str)) {
    $this->form_validation->
    set_message(‘valid_url’, ‘Please enter a valid URL.);   return FALSE;
  } else {
    return TRUE;
  }
}

In the example above, you will need to supply your own regular expression to perform a url match. This is how you implement the callback function. It’s ideal for adding quick functions without extending the current CodeIgniter library.

Make Your Copyright Notice Dynamic

Most website and blog owners place some kind of copyright information on their websites and in their blogs. Copyright notices mean that the copyright holder, reserves all the rights provided by copyright law, such as distribution, performance, and creation of derivative works.

Copyrights are usually found in the footer of most designs, themes or templates. My copyright information is found in the footer. It says, “Copyright © 2003-2011. All rights reserved.” The copyright notice will need to be updated yearly to reflect the current year.

Some owners place a range of years, such as 2000-2010, just like mine, to reflect that the website or blog has been around for a number of years. Often times, the owner forgets to update the copyright information. It’s a simple text change, but there are ways to make it dynamic.

By making your copyright notice dynamic means you never have to edit the copyright notice ever again. At every New Year’s eve, while you are out celebrating, your website magically updates the copyright notice to the latest year. How? It uses a PHP function called date().

To get the current year, use the PHP date function:

<? echo date(“Y”); ?>

If you want a range of years, you can use:

2001-<? echo date(“Y”); ?>

There you have it, a dynamic copyright notice! And one more thing, to display the copyright symbol properly, use the HTML special symbol:

&copy; or &#169; which are the same as the symbol ©

Going Back To CodeIgniter

It’s has been months since I played around with CodeIgniter. I say, it’s time to head back into it. Or should I say, jump back head first. I just realized how much easier it is to whip out an application or two, by just piecing together a few lines of code.

The resulting code is light, fast and fairly efficient. I tried other PHP frameworks, like CakePHP, but for some reason I can’t really explain, I just couldn’t latch on to it. It’s a weak try on my part, but I just feel much more comfortable with CodeIgniter. Maybe, it’s the simplicity.

In any case, both CakePHP and CodeIgniter requires some heat, starting a fire, and some baking. But, first off, I need to get reacquainted with CodeIgniter.

I’m back reading The User Guide.

PHP Time of Day Script

One very cool way of taking advantage of PHP’s powerful language is to make a determination as to what time of the day it is, and making a decision based on that information. For example, we want to detect the server’s current time and display a message that says either good morning, good afternoon or good evening.

There’s a handy PHP function called date that we can use. We can assign a variable called $current_time, to the server’s current time.

$current_time = date(G);

Next, let’s display the logic.

if ($current_time >= 0 && $current_time < 12) { echo 'Good Morning';}
if ($current_time >= 12 && $current_time < 18) { echo 'Good Afternoon';}
if ($current_time >= 18 && $current_time < 24) { echo 'Good Evening';}

You can also display images based on time of day.

if ($current_time >= 18 && $current_time < 24) { echo<img src=”sample.jpg” />;}

Display Your WAN IP Address

Have you ever wondered how dozens of websites can display your WAN IP address? The script is quite simple. You can probably host it if you have access to a web server. All you need to do is create a PHP file. Place the code below. Save. Upload the file to a web server and run the script. That’s it.

<?php
$ip = getenv(REMOTE_ADDR);
echo “Your IP address is:. $ip;
?>

HTTP Referrer

This short article will teach you how to return your program to the referring URL if you are running a PHP script or a function. At the top of the script you will need to capture the referring URL by including the following:

$ref = getenv("HTTP_REFERER");

You can then place your function next anyway you want it.

function {
 your function ...
}

When you are done, you can return the user to the referring URL by sending a header function.

header('Location: '. $ref );

Caveat: you will get a “header already sent error” if you are printing to the screen before the header function.

That’s it.

Generating PHP Random Keys

There are many ways of generating random keys in PHP. Random keys are essential in applications where you need unique identifiers that are not necessarily in sequential order. A prime example of where to use this script would be is when you need to create unique key for a URL shortener script.

For example: a user supplies a long URL. The script generates a random key based a predetermined length and returns a short URL based on the random key. So, here are  a couple of PHP random scripts that you might find useful. They both generate 6 random characters each time they are called.

Example 1

We create a function called rand_str(). We set the characters and generate a random key with a length of 6 characters. We make sure the same two characters don’t appear next to each other.

function rand_str($length = 6, $chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890?) {
  $chars_length = (strlen($chars)1); // Length of character list
  $string = $chars{rand(0, $chars_length)}; // Start our string
  for ($i = 1; $i < $length; $i = strlen($string)) { // Generate random string
    $r = $chars{rand(0, $chars_length)}; // Grab a random character from our list
    if ($r != $string{$i1}) { 
      $string .=  $r; // Make sure the same two characters don’t appear next to each other
    } 
    echo $string; // Return the string
  }
}

Example 2

This is example is essentially the same as above, but a bit more succinct. It generates a 6 character random string, but it doesn’t have a consecutive character feature like above.

for ($s =, $i = 0, $z = strlen($a = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’)-1; $i != 6; $x = rand(0,$z), $s .= $a{$x}, $i++);
$key = $s;
echo $key;

There you have it. Two scripts for generating random strings based on a predetermined length. It’s perfect for applications that need to generate unique and random keys.

There’s a good possibility a “swear” word could be generated by random chance. To avoid such words, simply take out the vowels from your character list.

Run Multiple Applications in CodeIgniter

You’ve installed CodeIgniter and you’ve written a couple of applications. Now, you want to run two of your applications under one install of CodeIgniter. The following article discusses how to run several applications within a single install of CodeIgniter. The approach is accomplished using Apache’s Virtual Host.

Install Apache Virtual Host

1. To add a virtual host, edit /etc/apache2/sites-available/default. We will use “vhostname” as the virtual hostname in this example. Edit the default file and add the following:

<Virtualhost *:80>
ServerName vhostname
DocumentRoot /var/www2
</VirtualHost>

2. Run the a2ensite script which enables your virtualhost within the apache2 configuration. It creates symlinks within /etc/apache2/sites-enabled.

# sudo a2ensite vhostname

3. Restart Apache

# sudo /etc/init.d/apache2 restart

4. Check your virtualhost if it’s working by pointing your browser to http://vhostname.

CodeIgniter Setup

One way of setting up CodeIgniter to support multiple applications, is to have separate folders for each application. You can set up your CodeIgniter directories like the following:

system/
 application/
  app1/
   config/
  app2/
   config/

1. Under the “app1/config” directory, edit the config.php file. Point your application to be hosted at vhostname by changing the following line:

$config['base_url'] = "http://vhostname/";

2. Copy the “index.php” file under the main CodeIgniter directory to the http://vhostname web root directory.

3. The “.htaccess” file recommended by CodeIgniter also needs to placed to the web root of http://vhostname.

4. Open your browser and check if your application is working by placing http://vhostname in the address bar of the browser.

5. Repeat steps 1-4 to add additional virtual hosts. That’s it.

If you have questions or suggestions, please leave a comment.