Archive for October, 2008

simple PHP code | No Comments | October 22nd, 2008

n this tutorial I’ll discuss dates and time in PHP, which is useful for a
myriad of tasks. To kick things off, take a look at PHP’s time()
function, which displays the current time measured in the number of seconds
since the Unix Epoch (January 1 1970 00:00:00 GMT):

<?
print time();
?>

This is also called a UNIX timestamp, and as mentioned, displays the current
time in seconds passed since the Unix Epoch. A sample output may look like:

1069142586

Using date() to display the date and time

Now, we want to display not just the current time and date, but in a user
friendly format. To do that we should enlist PHP’s date() function.
This date function is used to convert from a UNIX timestamp to a human readable
date. The date() function looks like:

string date ( string format [, int timestamp])

You can see that the timestamp is surrounded by ‘[‘ and ‘]’, which means it’s
optional. If we put it then the function will use it and if we don’t put it then
the function will use the default timestamp. The default timestamp which is used
when we don’t put any timestamp is the current time.

Let’s start our work with the date function. We want to show the user what
date and time is now.

print date(“l, F jS Y – H:i:s”);
//Example output: Tuesday, November 18th 2003 – 03:20:14

As you can see on the example above, I use l, F jS Y – H:i:s as the variable
passed to the function. Here’s a description of each of the formatting
characters used above:

F

month, textual, long; e.g. “January”

H

hour, 24-hour format; i.e. “00” to “23”

i

minutes; i.e. “00” to “59”

j

day of the month without leading zeros; i.e. “1” to
“31”

l (lowercase ‘L’)

day of the week, textual, long; e.g. “Friday”

s

seconds; i.e. “00” to “59”

S

English ordinal suffix for the day of the month, 2
characters; i.e. “st”, “nd”, “rd” or “th”

Y

year, 4 digits; e.g. “1999”

But wait, PHP actually supports many other characters you can pass into the
date function to format the output. Here’s the complete list:

format
character

Description

Example returned values

a

Lowercase Ante meridiem and Post
meridiem

am or pm

A

Uppercase Ante meridiem and Post
meridiem

AM or PM

B

Swatch Internet time

000 through 999

d

Day of the month, 2 digits with leading
zeros

01 to 31

D

A textual representation of a day,
three letters

Mon through Sun

F

A full textual representation of a
month, such as January or March

January through December

g

12-hour format of an hour without
leading zeros

1 through 12

G

24-hour format of an hour without
leading zeros

0 through 23

h

12-hour format of an hour with leading
zeros

01 through 12

H

24-hour format of an hour with leading
zeros

00 through 23

i

Minutes with leading zeros

00 to 59

I (capital i)

Whether or not the date is in daylights
savings time

1 if Daylight Savings Time, 0
otherwise.

j

Day of the month without leading zeros

1 to 31

l (lowercase ‘L’)

A full textual representation of the
day of the week

Sunday through Saturday

L

Whether it’s a leap year

1 if it is a leap year, 0 otherwise.

m

Numeric representation of a month, with
leading zeros

01 through 12

M

A short textual representation of a
month, three letters

Jan through Dec

n

Numeric representation of a month,
without leading zeros

1 through 12

O

Difference to Greenwich time (GMT) in
hours

Example: +0200

r

RFC 822 formatted date

Example: Thu, 21 Dec 2000 16:01:07
+0200

s

Seconds, with leading zeros

00 through 59

S

English ordinal suffix for the day of
the month, 2 characters

st, nd, rd or th. Works well with j

t

Number of days in the given month

28 through 31

T

Timezone setting of this machine

Examples: EST, MDT …

U

Seconds since the Unix Epoch (January 1
1970 00:00:00 GMT)

See also

time()

w

Numeric representation of the day of
the week

0 (for Sunday) through 6 (for Saturday)

W

ISO-8601 week number of year, weeks
starting on Monday (added in PHP 4.1.0)

Example: 42 (the 42nd week in the year)

Y

A full numeric representation of a
year, 4 digits

Examples: 1999 or 2003

y

A two digit representation of a year

Examples: 99 or 03

z

The day of the year

0 through 366

Z

Timezone offset in seconds. The offset
for timezones west of UTC is always negative, and for those east of UTC
is always positive.

-43200 through 43200

Source:
http://www.php.net/manual/en/function.date.php

Using mktime() to manipulate past and future times

Another useful function in PHP is mktime(), which can help you
easily display and format a past or future time (ie: what day of the week is
your birthday on)? This function creates a timestamp from a given set of
variables that you pass to the function.

mktime(hour, minute, second, month, date, year);

Now, I want to know on what day of the week my birthday was on. My birth date
is July 21st 1974. I’ll use the mktime function like so:

$mybirthdate = mktime(0,0,0,7,21,1974);
print date(“l”, $mybirthdate);
//Output: Sunday

Wow, I finally found out that my birthday is on Sunday. :). Now the next case
I want to know is what day is 25 days from now. Let’s do it this way:

$next25day = mktime(0,0,0,date(“n”),date(“j”)+25,date(“Y”));
print date(“l”, $next25day);

Give attention to the variables that I passed to the mktime function. I’ve
passed date(“j”)+25. It means that I want to add 25 to the current date. You can
figure out what it will produce.

Using getdate() as an alternative to date()

This is another method to access the current date or the given timestamp. The
method, or you can call it function, is getdate(). This function
will produce an associative array containing the date information. The array
keys are:

seconds

seconds

minutes

minutes

hours

hours

mday

day of the month

wday

day of the week, numeric: from 0 as Sunday up to 6 as
Saturday

mon

month, numeric

year

year, numeric

weekday

day of the week, textual, full; i.e. “Friday”

month

month, textual, full; i.e. “January”

Example :

$today = getdate();
print $today[“month”] // it will print the month of current date
print $today[“weekday”] // it will print the day of current date

Displaying the date and time in your own local language

By this time I hope you can create your own date and time using the timestamp
of the current date or your own timestamp. I’m not using English as my primary
language, and neither are my website users. We are from Indonesia and I want to
display the date in Indonesian language. How can I do it? That’s a perfect
question and asked by most beginners.

Let’s create an associative array of date and month in our own language.

$days = Array (“Minggu”, “Senin”, “Selasa”, “Rabu”, “Kamis”, “Jum’at”, “Sabtu”);
$months = Array (1=>”Januari”, 2=>”Pebruari”, 3=>”Maret”, 4=>”April”,
5=>”Mei”, 6=>”Juni”, 7=>”Juli”, 8=>”Agustus”, 9=>”September”,
10=>”Oktober”, 11=>”Nopember”, 12=>”Desember”);

After we create our own language of date and months, now it’s time to display
it.

print $days[date(“w”)]; // display name of day with our own language
print $months[date(“n”)];

Ok guys, that’s it for today. We’ll see you again next time.

simple PHP code | No Comments | October 22nd, 2008

Creating a simple feedback form using PHP is very easy, thanks to PHP’s prebuilt mail() function. In this tutorial I’ll show you a complete, working example.

Firstly, lets create the HTML portion of the form:

<form action="sendmail.php" method="POST">
<b>Your name :</b> <input type="text" name="name"><br>
<b>Your e-mail :</b> <input type="text" name="email"><br>
<b>Message</b><br><textarea name="message"></textarea>
<input type="submit" value="Send"><input type="reset" value="Clear">
</form>

This is a basic form with two input fields and a textarea. Since we are using the POST method, we’ll
be eliciting PHP’s $_POST variables within our PHP script to retrieve what’s been entered. Inside
the PHP script called “sendmail.php” (as that’s what we’re specifying above in our form),
enter the following:

/*Here we are going to declare the variables*/
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//Save visitor name and entered message into one variable:
$formcontent="VISITOR NAME: $name\\n\\nFEEDBACK: $message";
$recipient = "you@yourdomain.com";
$subject = "Contact Form";

Obviously, you’ll need to change the recipient to your own email address. If you want to send it to more than one email address, just put a comma in between them. You can also change the subject. By using the $_POST array of PHP, which is an associative array, we can access all the elements of the form.
Looking back at the first input field in the form, you will see name=”name”.
This is how we got the variables $_POST['name'] and $_POST['email'] and $_POST['message'] above- they came from each form element’s given name. In other words, you use each form element’s name attribute as the key to accessing its value within array $_POST.

Continuing with our “sendmail.php” script, we now need to construct a mail header which mail() requires before it can send the form to
you:

$mailheader = "From: $email\\r\\n";
$mailheader .= "Reply-To: $email\\r\\n";
$mailheader .= "MIME-Version: 1.0\\r\\n";

These are simple mail headers. The first two tell the email program who it is from and who to reply to. The last one tells the
MIME-Version. All this information will be included in the email that’s sent to you. Finally, we’re now ready to invoke the mail() function to actually send the form:

mail($recipient, $subject, $formcontent, $mailheader) or die("Failure");
echo "Thank You!";

This executes the mail function with four parameters. It mails to the recipient with a subject, message, and headers. If it does not execute (die), it will print “Failure!”.

And now the complete “sendmail.php” script:

<?php
/*Here we are going to declare the variables*/
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//Save visitor name and entered message into one variable:
$formcontent="VISITOR NAME: $name\\n\\nFEEDBACK: $message";
$recipient = "you@yourdomain.com";
$subject = "Contact Form";
$mailheader = "From: $email\\r\\n";
$mailheader .= "Reply-To: $email\\r\\n";
$mailheader .= "MIME-Version: 1.0\\r\\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Failure!");
echo "Thank You!";
?>

That is it!

Mode rewrite | No Comments | October 22nd, 2008

See how to use .htaccess and mod_rewrite to easily transform ugly PHP URLs into search engine friendly ones.

The coming together of PHP and MySQL to create dynamic pages is a wonderful thing. Instead of having hundreds of separate webpages, your entire site can be stored inside a MySQL database, and then retrieved and displayed using a handful of “template” PHP pages. This makes updating the site extremely easy, though the draw back is often that the resulting URLs for the pages aren’t very search engine friendly. For example:

http://www.mysite.com/articles.php?id=3&page=0

The “?” and “&” characters within the URL will stump many search engines, even Google, from crawling the page. What we want instead is something like:

http://www.mysite.com/articles/3/0

which makes the URL appear just like any normal directory structure, with which all search engines have no qualms about. So how do we go about transforming the parameters portion of a dynamic URL into such a setup instead? Here are the simple steps:

Step 1: Rename your template PHP page, such as “articles.php”, as “articles” instead, without any extension. We want to use this page instead to act as our new templates page.

Step 2: Herein lies the key to creating search engine friendly URLs- configuring Apache to interpret a particular file without extension as a normal PHP page instead. In this case, we want Apache to treat “articles” as if it were a PHP page. In your .htaccess file, add the below code inside it:

ForceType application/x-httpd-php

Notice how the word “articles” appear within the tag. By adding the above code to your site’s .htaccess file, it informs Apache to interpret “articles” as a PHP page. You can add additional files for Apache to treat as PHP pages by duplicating the above multiple times.

Step 3: With “articles” now being synomonous to “articles.php”, all that’s left is writing code within “articles” to identify the parameters portion of our new URL format, and store them as variables for further processing. As a reminder, our new working URL looks like:

http://www.mysite.com/articles/3/0

What we want is to create code that detects the “3” and “0” portion of the URL, as they are the parameters. Within “articles”, you could do the following:

//split the URL into parts using "/" as the delimiter:
$urlarray=explode("/", $REQUEST_URI);
//Contains "3", or the ID of the article to display:
$articleID=$urlarray[2];
//Contains "0", or the page number of the article in question:
$pageNum=$urlarray[3];

We now have two variables that contain the two parameters embedded inside our search engine friendly URL, which we can then pass into a MySQL query to display the corresponding article and page number. For example:

$getarticle=mysql_query("SELECT thearticle FROM articletable
WHERE id=$articleID AND page=$pageNum");
echo mysql_result($getarticle, 0); //displays article

And there you have it. As mentioned, the key to creating search engine friendly URLs in PHP and MySQL is in fact via Apache’s .htaccess file.

simple PHP code | No Comments | October 20th, 2008

What is a Loop?

Looping is simply a way for you to reduce the amount of code and/or content you have to write out. The idea is that you have something you have to do, or some content you have to show, and instead of just “writing it all out,” you find a pattern to it – a common denominator – and let PHP execute the code or generate the content piece by piece using that pattern, based on a condition.

A condition is a way of letting PHP know how many times to run your loop, or when to stop running your loop. The ability to take a condition and execute a set of instructions over and over as long as that condition is true is one of the basic cornerstones of programming.

To demonstrate how loops work, we will use a “for” loop to solve the following example problem:

“Joe wants to be able to take a range of numbers and find out how many numbers are divisible by a certain number, within that range of numbers. “

The Code

Okay the first thing I am going to do is give you the complete script for the solution to this problem. That way, you have the goods right up front and can refer to it as a whole.

  1. <?php
  2. // variable to hold form
  3. $form = <<<SOMEFORM
  4. <form action = ‘{$_SERVER[‘PHP_SELF‘]}’ method = ‘post’>
  5. Range Start: <input type = ‘text’ name = ’start’ size = ‘3?><br />
  6. Range Finish: <input type = ‘text’ name = ‘finish’ size = ‘3?><br />
  7. Divided By: <input type = ‘text’ name = ‘num’ size = ‘3?><br />
  8. <input type = ’submit’ value = ‘Find Numbers’>
  9. </form>
  10. SOMEFORM;
  11. // if we have posted info…
  12. if ($_POST) {
  13. // assign post vars to reg vars for easier handling
  14. $start = (int) $_POST[‘start’];
  15. $finish = (int) $_POST[‘finish’];
  16. $num = (int) $_POST[‘num’];
  17. echo “The following numbers from $start to $finish are divisible by $num : <br />”;
  18. // loop from $start to $finish, 1 number at a time
  19. for ($x = $start; $x <= $finish; $x++) {
  20. // if the modulus of the current number and the divided by number
  21. // is zero, then it is evenly divisible by that number
  22. if (($x % $num) == 0) {
  23. // echo the number
  24. echo “$x ”;
  25. // end if
  26. // end for
  27. // end if
  28. // echo out the form
  29. echo $form;
  30. ?>

    What We Care About

    There may be a lot of things in that script you may be unfamiliar with. Basically there’s a form so we can get input from the user, and that’s about it. The only part of the script we are really going to focus on is this part:

    1. // loop from $start to $finish, 1 number at a time
    2. for ($x = $start; $x <= $finish; $x++) {
    3. // if the modulus of the current number and the divided by number
    4. // is zero, then it is evenly divisible by that number
    5. if (($x % $num) == 0) {
    6. // echo the number
    7. echo “$x ”;
    8. // end if
    9. // end for

      Let’s Get Loopy

      All loops are broken down into four basic pieces:

      – The initialization
      – The condition
      – The instruction
      – The iteration

      A basic “for” loop looks like this:


      for (initialization; condition; iteration) {
      instruction
      }

      We start out with telling PHP what kind of loop it is. Since it is a “for” loop, we start out by simply saying “for …” The initialization, condition, and iteration are put inside the ( )’s, separated by a semicolon. We use { } brackets to show where the start and end of our instruction is. Some people like to put the { on its own line like this:


      for (initialization; condition; iteration)
      {
      instruction
      }

      It’s really just a matter of style; PHP doesn’t care either way.

    10. Going Around In Circles

      The Initialization
      This is where the loop starts. We tell the “for” loop where to start by assigning the starting number to a variable $x. In this example, our starting number is represented by $start – what the user puts in from the form.

      In a “for” loop, the initialization must always be a number. It doesn’t have to be a whole number, or even positive, but it has to be a number, and it has to be initialized by assignment to a variable, so that PHP can keep track of counting each iteration of the loop. In other words, it has to have this basic format:

      $x = $start;

      The Condition
      This is where we control how many times we want the loop to repeat, or iterate. A “for” loop counts from one number to some other number. This is where we tell PHP what that other number is. Without the condition, the loop will never stop repeating, and we would have what’s called an infinite loop.

      The condition must always check the initializing variable against a number value. It doesn’t have to be a whole number, it can be positive or negative, but it has to be a number value. You can use any of the normal condition operators for the condition. Some basic formats (that are relevant to our example) for the condition are:
      $x < $finish;
      $x <= $finish;
      $x != $finish;

      …And Again And Again

      The Iteration
      This is where PHP increments the initialization variable. In our example, we do $x++. This is just a shorthand way of doing $x = $x + 1, which is equally valid. it is also equally valid to increment it by something other than 1. It doesn’t even have to be a whole number. It can even subtract a number so your loop can “count down.”

      How you want your loop to count (the increments per loop, counting up or down, etc..) is entirely up to you, and you will base that on what your goal for the instruction is. In this example, we could just as easily start with the ending number and count down to the starting number, subtracting 1 from $x during each iteration of the loop, like so:

      1. for ($x = $finish; $x >= $start; $x–) {
      2. if (($x % $num) == 0) {
      3. echo “$x ”;
      4. // end if
      5. // end for

      On that note, be careful to “phrase” your loop correctly, or you will not get your desired results, or worse, end up with an infinite loop. Consider this loop:

      1. $start = 100;
      2. $finish = 200;
      3. for ($x = $start; $x >= $finish; $x++) {
      4. echo “$x ”;
      5. // end for

      We are telling the loop to start at 100, and while $x is greater than 200, run the instruction. Well the problem is, right out the gate, the condition is false, because 100 is not greater than 200. Our loop will never execute. Or how about this example:

      1. $start = 100;
      2. $finish = 200;
      3. for ($x = $finish; $x >= $start; $x++) {
      4. echo “$x ”;
      5. // end for

      Whoops, we accidentally put the start and finish variables backward. Since we start at 200, our loop will keep iterating as long as it is greater than 100. Each iteration, we add 1 to 200, so the condition will always evaluate as true. The loop will never stop, thus creating an infinite loop.

      Show Me The Money!

      The Instruction
      The Instruction is what you want PHP to do each iteration of your loop. It can be something as simple as echoing out the current iteration, doing some math based on each iteration, or pulling out a new row of information from a database. This is the “pattern,” or “common denominator” to your large chunk of code/content. It’s the individual brick that your loop stacks over and over to make your wall.

      The most challenging part of making a loop is the Instruction part. Finding the pattern isn’t always so easy as our simple condition to test if a number divides evenly by another number. You can use virtually anything inside your loop to build your pattern, from regular assignments/outputs to conditions; you can even put another loop inside your loop! And there’s really no limit to how far you can “nest” things inside one another, except for how far you can wrap your head around the logic. Finding a pattern to make a loop out of deserves it’s own tutorial altogether. It is what makes looping an artform.

      Raspberry Red, Lemony Lemon, Orangey Orange!

      Tucan Sam isn’t the only dude offering different kinds of loops. PHP offers four different ways to reiterate pieces of code:

      – The while loop
      – The do…while loop
      – The for loop
      – The foreach loop

      In principle, each kind of loop has the same basic components and does the same basic thing, but their nuances make it possible to write your code more efficiently, depending on your circumstance. The nuances in the loops are being able to put the loop’s components in different orders, or even combining components of the loop.

      Changing the order of the components is important to know, because this can and will change the outcome of your loop. For example, some loops or orders will execute the instruction first, then check the condition, so you will always get at least one iteration of the loop.

      The While Loop

      The basic While loop syntax looks like this:


      initialization
      while (condition) {
      instruction
      iteration
      }

      A working example might look like this:

      1. $x = 0;
      2. while ($x < 10) {
      3. echo “$x ”;
      4. $x++;
      5. }

      In essence, this while loop is exactly like a for loop. It has a set initializer, a set condition, and a set iteration. You are, of course, free to switch the order of the instruction and the iteration. In this example, it would actually be better to write this as a for loop, because that’s what the for loop was made for.

      The power of a while loop is being able to combine the initializer and even sometimes the iteration with the condition. One scenario in which this comes in handy is if you have a list of information in a database and you want to grab that information and make a loop to display that data, but you aren’t sure how many iterations there will be, because you aren’t sure how many rows will be returned from the database.

      Example:

      1. $sql = “select name from table”;
      2. $result = mysql_query($sql);
      3. while ($name = mysql_fetch_assoc($result)) {
      4. echo “{$name[‘name’]} <br />”;
      5. }

      In this example, we run a query to select all the names in a table in your database. Inside the ( …), all 3 components (initialization, condition, iteration) are combined into a single expression.

      The initialization is easy enough to spot: $name = … is the initialization.

      mysql_fetch_assoc is a special function that grabs a name from the result source of the query and then internally increments the pointer of that result source to the next name in the results. This is the iteration, because when the loop finishes and goes back to the beginning, it will have a new name to fetch.

      The condition comes into play by the act of being able to initialize $name to the next name in the result source. If mysql_fetch_assoc gets to the end of the list of names, it will return false, so the next time the loop tries to assign a name to $name, it will fail, thus ending the loop.

      The Do…While Loop

      The do..while loop works pretty much exactly the same as the while loop, except that the instruction will always be executed first. The basic syntax looks like this:


      initialization
      do {
      instruction
      iteration
      } while (condition);

      As with the while loop, putting the components in those positions makes it a glorified for loop, and you should use a for loop. Just like the while loop, the power is being able to combine the components and/or make a loop with an undetermined amount of iterations.

      If we were to use a do…while loop with the previous database example :

      1. $sql = “select name from table”;
      2. $result = mysql_query($sql);
      3. do {
      4. echo “{$name[‘name’]} <br />”;
      5. while ($name = mysql_fetch_assoc($result));

      In this example, we’re going to run into some problems. Because the instruction comes first, $name[‘name’] does not exist until after the first iteration of the loop. In my experience, there aren’t very many circumstances where a do…while loop is preferred over a while loop. It’s really only good for wanting to make a loop where you want the instruction to be executed at least one time, no matter what.

      The For Loop

      We used the for loop in our example on how loops work, so you should already have a decent understanding about this loop. The only thing to really understand about the for loop, is that it is the “strictest” loop out of the bunch. It needs a set starting point, and a set ending point. It’s useful if you know exactly how many iterations you are dealing with, simple as counting from 1 to 10.

      As shown previously:


      for (initialization; condition; iteration) {
      instruction
      }

      The condition will always be evaluated before the instruction is complete, and the instruction will be executed before the value is iterated.

      initialization -> condition -> instruction -> iteration -> condition -> instruction -> iteration …

      The Foreach Loop

      A foreach loop is specially designed for working with array elements. A basic structure of a foreach loop looks like this:


      foreach ($array as $value) {
      instruction
      }

      In this loop, the $value is the initialization component. The condition and iteration comes from the $array. The $array represents an array. The loop starts an internal pointer at the beginning of the array, and assigns the value of that element to $value, and then executes the instructions. When the instructions are done, the pointer is moved to the next element of $array (the iteration). If there is no element (the end of the array), the condition evaluates false, and the loop ends.

      Consider this example:

      1. $letters = array(‘a’,‘b’,‘c’);
      2. foreach($letters as $letter) {
      3. echo “$letter <br />”;
      4. }

      The foreach loop points to the first element of the $letters array, executes the instructions, moves to the next element, etc… and when it runs out of elements, the loop is over. The output would be:

      a
      b
      c

      The foreach loop accommodates associative arrays, as well. An associative array is an array that assigns a “name” to the element, or key, of the array. Example:

      1. $account = array(‘name’ => ‘John’, ‘number’ => 123, ‘age’ =>30);
      2. foreach($account as $key => $val) {
      3. echo “$key : $val <br />”;
      4. }

      The output of this would be:

      name : John
      number : 123
      age : 30

      Continue and Break

      PHP offers two language constructs to break out of your loop: continue and break. “Continue” is used to skip the rest of the instructions in the current iteration of the loop. Let’s say you want to count from 1 to 100 but skip printing all the even numbers:

      1. for ($x = 0; $x <= 100; $x++) {
      2. if (($x % 2) == 0) {
      3. continue;
      4. }
      5. echo “$x <br />”;
      6. }

      Each iteration of the loop we have a condition to check if $x is evenly divisible by 2. If it is, we skip echoing out $x and move on to the next iteration. Now we could have just as easily done this:

      1. for ($x = 1; $x <= 100; $x = $x + 2) {
      2. echo “$x <br />”;
      3. }

      But that’s not the point! Besides, continue and break are useful for things much more complex than this. Break works the same way as continue, except that it breaks out of the whole loop, instead of the current iteration.

      Both break and continue can take an optional argument for you to specify what level loop to break or continue. This is useful for nested loops, where if you for example have a loop running inside another loop and if some condition is met, you want to exit out of the loop, even the main loop, you can do this:

      1. for ($x = 0; $x <= 10; $x++) {
      2. for ($y = $x; $y <= 10; $y++) {
      3. $z = $x * $y;
      4. echo “$x * $y = $z <br />”;
      5. if ($z == 50) {
      6. break(2);
      7. }
      8. }
      9. }

      In this nested loop, we are printing out everything from 1 * 1 to 10 * 10 but we have a condition inside the nested loop to break out of all of the loops if we find an answer that equals 50.

      That’s All Folks!

      Well, that’s about all there is to know about loops. The basic syntax of loops is pretty easy to figure out; it’s finding the patterns to loop that’s the tough part. I hope that this has helped some of you out there who are just getting started and want to know what’s the point of loops and why are there different kinds. Perhaps in a future tutorial I will attempt to tackle tips and tricks to finding patterns for loop instructions.

      Until then, happy coding!

Article | No Comments | October 17th, 2008

If you’re including files based on user input you must think carefully about the security implications of this. When I say user input, I mean any value coming from outside your PHP script that is used in the formation of a file path. This could be as simple as a user clicking a link containing URL-parameter whose value is a predefined path to a file you wish to include.

Let’s first examine some code that accepts the name of a file and includes the contents of that file in a PHP page. The file named in the URL-parameters “body” is specified as an include.

<html>
<head>
<title>Blah</title>
<table border=1>
<tr>
<td width=100>
<a href=index.php?body=news.html>Test</a>

<td><? include("$body");?>
</table>

Be aware this is a security risk. Suppose a mischievous user enters a link into their browser with something like this:

index.php?page=../../../etc/passwd

Allowing directory navigation symbols into input exposes your host system’s password file and allow anyone on the web to read it. Moreover, it can expose any document on your web site. In this article, we will look at various solutions for allowing material to be included while at the same time closing this loophole.

You might think that you could just hardcode a directory or folder name into the path like this:

<a href=index.php?body=news.html>Test</a>
<td><? include('folder/'.$body);?>

But this does not work because directory navigation symbols (“../” and “./” can always be included in the path to get out of this directory. A malicious user can navigate anywhere, even out of the web tree.

Validating Include Paths


The solution is, instead of just blindly including the file, we check for any directory navigation symbols in the submitted value before the file is included. I will show you how to create a function we can run the value through before executing the include.

The following script demonstrates how it works. You will need a text file to experiment with:

kumquat.txt

<h3>Kumquat</h3>

<p>Any of several trees or shrubs of the genus Fortunella bearing small orange-colored edible fruits
with thick sweet-flavored skin and sour pulp.
</p>

And this PHP page: safeinc.php:

<?php

print "<h2>Testing Safe Include</h2>";

function is_safe_file_path($path) {
	if ((!eregi("^..",$path)) && (!eregi("^.",$path)))
	{
		return true;
	} else {
		return false;
	}
}

$include_path = "kumquat.txt";

?>
Including: <?php print $include_path; ?>
<div class="note" style="background: #eeeeee; color: #333333; border: 1px dashed;
   padding: 4px; font: 12px Arial">
<?php

if(is_safe_file_path($include_path))
{
	include($include_path);
}

?>

</div>

Put both files in the same directory and run safeinc.php to see the result. You can try entering “../” or “./” or “../../” or “../kumquat.txt” etc. into the $include_path to see it reject those paths with unsafe path symbols.

Be sure to form your full path, such as “fruits/kumquat.txt” before running it through the function and including.

Of course, you can have paths that go deeper in the directory tree like the previous, but not “../fruits/kumquat.txt” because that is what we are trying to prevent: navigating out of the folder we are in.

For this example, I also left out encapsulating the include into a function to make it easier to understand (and code!). Here’s a version of safeinc.php that wraps the include into a function.

safeincfn.php:

<?php

print "<h2>Testing Safe Include</h2>";

function is_safe_file_path($path) {
	if ((!eregi("^..",$path)) && (!eregi("^.",$path)))
	{
		return true;
	} else {
		return false;
	}
}

function safe_include($path) {
	if(is_safe_file_path($path))
	{
		include($path);
		return true; // indicate success
	}
}

$include_path = "kumquat.txt";

?>
Including: <?php print $include_path; ?>
<div class="note" style="background: #eeeeee; color: #333333; border: 1px dashed; padding: 4px; font: 12px Arial">
<?php

safe_include($include_path);

?>
</div>

Or a more compact function that folds all the features into one:

function safe_include($path) {
if ((!eregi("^..",$path)) && (!eregi("^.",$path)))
	{
		include($path);
		return true; // indicate success
	} else {
		return false;
	}
}

Or with built-in warning and script halt. Silent on success, display message on fail.

function safe_include($path)   {
if ((!eregi("^..",$path)) && (!eregi("^.",$path)))
	{
		include($path);
	} else {
		print "Warning - you do not have permission to access this area.";
		exit;
	}
}

Article | No Comments | October 17th, 2008

Here is a quick way to create a configuration file from the web, used to initially setup an application or that can be expanded to allow users to modify the configuration later.

We will take advantage of the PHP’s ability to include code into an existing script. Instead of creating an initialization file that must be read and parsed, we let PHP do the parsing. The configuration file consists of a series of variable definitions. Our example script could be used to initially setup a database driven web application, such as a message board, etc. It may also be extended to allow updating of application settings at any time.

Our example will contain settings frequently used in PHP applications: values used for connecting with and querying a database and a filesystem path. Here is what the resulting configuration file might look like.

<?php
// Do not edit this file. Generated by admin script.
// Database settings
$db_user = 'me';
$db_pass = 'noneofyourbizness';
$db_host = 'localhost';
$db_name = 'mydb';
$db_table = 'mystuff';
// Paths
$base_path = 'home/users/me/mystuff';
?>

Our goal is to accept values from a web form and write changes to a configuration file.

For example, if you wanted to create a setup script for a database driven web application, users would go to a form page with the following inputs:

db_user     Database user name.
db_pass     Database password.
db_host     Database host name.
db_name     Database name.
db_table    Name of table application uses.
base_path   Path to folder containing files
            of interest to the application.

Writing the Configuration File


function write_config()

{

// For every setting, add a global variable

global $db_user,$db_pass,$db_host,$db_name,$db_table;

global $base_path;

// Prepare settings

// Using single quotes is easier because you don't have to escape them. For every setting, add a line.

$settings = "<?php\n";

$settings .= "// Do not edit this file. Generated by admin script.\n";

$settings .= "// Database settings\n";

$settings .= "\$db_user = '$db_user';\n";

$settings .= "\$db_pass = '$db_pass';\n";

$settings .= "\$db_host = '$db_host';\n";

$settings .= "\$db_name = '$db_name';\n";

$settings .= "\$db_table = '$db_table';\n";

$settings .= "// Paths\n";

$settings .= "\$base_path = '$base_path';\n";

$settings .= "?>\n";

// Write out new initialization file

$fd = fopen( '/somepath/config.php', "w" )

or die ("Cannot create configuration file.");

fwrite( $fd, $settings );

fclose( $fd );

}

Note Because I made this a function, we need to include any variables we are going to write into the configuration as global variables or function parameters. I chose to make all variables used by the configuration file globals. They will likely be global to the whole application anyway (unless you’re using classes).

Getting Input from the User


To use this all you need is a form with inputs matching the variable names. The values get submitted and then written out as variables in the configuration file. When the configuration file is loaded by the application, the submitted values are available.

I’ve designed a form for use with the setup script.

<form action="setup.php" method="POST">

<style>
td { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: x-small; color: #333333 }
  .formhed { background-color: #cccccc; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: x-small; color: #333333 }
  .intputhed { background-color: #eeeeee; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: x-small; color: #333333 }
</style>

<table cellspacing="2" cellpadding="5">
   <tr class=intputhed>
      <td colspan="2" class=formhed>Setup </td>
   </tr>

   <tr class=intputhed>
      <td>Database User Name</td>
      <td><input type="Text" name="db_user" size="24" value="<?php echo $db_user; ?>"></td>
   </tr>

   <tr class=intputhed>
      <td>Database Password</td>
      <td><input type="password" name="db_pass" size="24" value="<?php echo $db_pass; ?>"></td>
   </tr>

   <tr class=intputhed>
      <td>Database Host</td>
      <td><input type="Text" name="db_host" size="24" value="<?php echo $db_host; ?>"></td>
   </tr>

   <tr class=intputhed>
      <td>Database Name</td>
      <td><input type="text" maxlength=60 size="24" name="db_name" value="<?php echo $db_name; ?>"> </td>
   </tr>

   <tr class=intputhed>
	<td>Database Table</td>
	<td><input type="text" maxlength=60 size="24" name="db_table" value="<?php echo db_table; ?>"> </td>
   </tr>

   <tr class=intputhed>
	<td>Full Path</td>
	<td><input type="text" maxlength=60 size="24" name="base_path" value="<?php echo $base_path; ?>"> </td>
   </tr>

   <tr class=intputhed>
	<td colspan="2">
	   <input type="Hidden" name="action" value="update_config">
	   <input type="Submit" value="Next >>"> </td>
   </tr>

</table>

</form>

Security Concerns


Anytime you create or write an operating system file from a web based form and script combination, you must consider how secure it is. There is potential for abuse if users can write files all over the place.

First, you should be sure that the path to the configuration file is hardwired into the script. Never let the user define this path directly from the form input. If you do have a need for the user to select from a number of configuration files, select them from an array of allowed paths. The form should only allow the users to indicate which path they are selecting, for example, by an option number obtained from a drop down menu.

Second, you should be sure the configuration file is not writeable by anyone on the net. It should be writeable only by the owner and any script granted access to the filesystem.

If PHP is not running under your user id, then you will have to have the user manually make the file world writeable until the new file is written out, then have them manually change the permissions so it not world writeable.

Third, I suggest user input be run through a function that strips any HTML tags, SSI includes, Unix system characters or commands before writing the configuration out. You may need to allow some of these given the purpose of the input. For example, if the input is for a snippet of HTML (you still want to be careful, because submitting a bit of JavaScript could wreak havoc if displayed in your browser and a snippet of PHP code could also do harm).

Article | No Comments | October 17th, 2008

How to copy the contents of one table to another using SQL is not immediately obvious.

Create and Populate Table

create table mytablecopy select * from originaltable

Copying a Table into an Existing Table

insert into originaltable select * from mytablecopy

Sub-Selects

MySQL doesn’t yet support sub-selects. For example you cannot do this:

    select * from things where thing.userid not   in (select userid from
otherthings)