<!-- SophiaKnows -->

PHP BASICS
Rev 3: Jan 2005

 

1. What Is PHP?

PHP is a server-side scripting language that can be used to add customized features and database driven dynamic content to web pages and internet based applications.

The syntax of PHP is intentionally very similar to popular programming languages such as C and Perl. If you have any previous experience with these languages, you should be able to pick up the basics of PHP quite quickly.

This note provides a quick overview of PHP syntax and features (particularly as compared to other languages).

However, PHP is feature rich. It is a language maintained by developers for developers, and no single tutorial can cover the hundreds of functions and solutions built into PHP.

Fortunately, excellent online documentation is among PHP's strengths.

2. How To Include PHP Code

PHP is activated by naming a file with the extension .php

example.php

PHP is embedded within a page by enclosing commands within the start tag <?php and the end tag ?>

<?php
echo ("Written by PHP");
?>

Normal HTML and plaintext cannot be included within blocks of PHP code. You can output HTML from within a PHP block to the browser by using the echo command as shown above, or by ending the PHP block, resuming normal HTML, and later starting a new PHP block.

Listing 1.1 PHP Goes Here

<?php
// PHP Can Proceed HTML
?>

<html>

<title>PHP Page</title>

<head>

<link href="global.css" type="text/css" rel="stylesheet" />

<?php
// PHP Can Go In the Head
?>

</head>

<body>



<?php
// PHP Can Go In the Body
?>



</body>

</html>

You can include as many separated blocks of PHP code in your file as you need, and any variables you set will be available to the block it was set in, and any block below that.

3. PHP Variables

PHP variables are assigned in a typical manner. Normal variables are preceded with a dollar sign ($), and assigned to with an equal sign (=).

$variable-name = "";
$user = "Bob";

Number values are assigned to variables as bare numbers. Character data is assigned to variables as quoted string literals (using either single or double quotes):

$val = 5;
$title = "The Title";
$title = 'The Title';

Variables may, of course, be assigned to other variables. They may also be included in quoted values assigned to another variable:

$title = "The Title";
$chapter_title = "$title Chapter 1";

Quotation marks and special characters (e.g. $) are escaped using the backslash operator ("\"):

$message = "\"Fresh\" Fruit: \$1.00";

4. PHP Arrays

Unlike some languages, any variable can be used an array by including a key in square brackets after the variable.

For a regular (index based) array, a number is used as the key. For an associative array, a quotes enclosed string (or another variable) is used:

<?php
// Indexed array
$fruits[0] = "apple";
$fruits[1] = "grape";

// Associative array
$mother['kitten'] = "cat";
$mother['puppy'] = "dog";
?>

In additon, the function array can be used to create either indexed or associative arrays:

<?php
// Indexed array
$fruits = array('apple','grape','orange');

// Associative array
$mother = array('kitten' => 'cat', 'puppy' => 'dog');
?>

5. PHP Operators

5.1 PHP Comparison Operators

PHP uses the common set of comparison operators, provided unlike Perl, PHP uses the same operators for both strings and numbers:

$x == $y  // equal to

$x != $y  // not equal to

$x > $y  // greater than

$x >= $y  // greater than or equal to

$x < $y  // less than

$x <= $y  // less than or equal to

5.2 PHP Arithmetic Operators

Arithmetic operators in PHP are virtually identical to those in Perl and C as illustrated by the examples below:

$add = $var + 3;  // Addition

$sub = 18 - 6;  // Subtraction

$mult = $var1 * 3; // Multiplication

$div = 15 / $var;  // Division

$mod = $var % 2; // Modulus

6. PHP Control Structures

PHP provides same basic control structures seen in other languages, among them the looping constructs for, foreach and while, and the standard if/else constructs. Examples of each are given below:

6.1 For Loop

for ($i = 0; $i < 20; i++) { 
    print "Current Iteration: $i\n";
    }

6.2 Foreach Loop

foreach ($fruits as $i => $fruit) { 
    print "Current Iteration: $i. $fruit\n";
    }

6.3 While Loop

$i = 0;
while ($i < 20) {
    print "Current Iteration: $i\n";
    $i++;
    }

6.4 If Elseif Else

if ($i > 20) {
  echo "$i is greater than 20.\n";
  } elseif ($i > 10) {
    echo "$i is greater than 10.\n";
    } else {
      echo "$i is less than 10.\n";
      }

7. Access To Form Variables

One of the nicest features of PHP is its easy access to form variables. For instance, consider the following short form:

<form method=post action="handler.php">
  <input type=text name="restrictions">
  <input type=submit>
</form>

On submitting the form, the value of the variable "restrictions" will be available to the handler.php script simply as $restrictions with no further work required. This is true whether the data was submitted via POST or GET form method.

8. PHP File Access

PHP also allows you full ability to read and write to remote and server based files. Files can be accessed in one of several ways: read only, read/write and write only.

8.1 PHP File Access: Read Only

The full contents of a file can be read into a local variable using one of two methods readfile or file. Here is the syntax for readfile:

$file = readfile("filename");

Where $file is the variable you'll use to refer to the contents of the file, filename is the name of the file to be opened.

$lines = file("filename");

file is like readfile except that the contents of the target file are returned in the form of an array in which each new line is a member.

Both file and readfile can read files via http if permitted by your server configuration.

Both file and readfile can return showstopping errors if PHP is unable to open a stream at "filename". This behavior can turned off by using the at sign (@) proceeding the commands:

$file = @readfile("filename");
$line = @file("filename");

8.2 PHP File Access: Read/Write

Local files can be opened in read/write mode using the fopen command, which is given in the form:

$file = fopen("filename","mode");

where $file is the variable you'll use to refer to the open file, "filename" is the name of the file to be opened, and, "mode" determines level of access to the file using one of the following values:

r  (read only)
r+ (read and write)
w  (write only)
w+ (read and write, truncate file to 0 bytes)
a  (write only, start at end of file -- append)
a+ (read and write, starting at file end)

Once the file is opened, there are two commands to read in data. fgetc retrieves a single character, while fgets retrieves a number of bytes you specify. They are used in the following manner:

$one = fgetc($file);

$ten = fgets($file,10);

If you need to write to the file, the function used is fputs:

fputs($file,"This is written to the file");

But note that the results of fputs depends on how the file was opened:

$file = fopen("filename",w+); // read write
fputs($file,"This is written to the file"); // Text replaces contents

$file = fopen("filename",a); // write only
fputs($file,"This is written to the file"); // Text appended to contents

After you are done working with the file, you can close your it using the fclose command:

fclose($file);

9. Conclusion

That's the overview and enough to get started with a basic PHP program. There is much more to PHP all which can be found in the excellent documentation at: php.net

Finally, here is list of the methods used in this overview linked to their listings in the PHP functions manual:

array
readfile
file
fopen
fgetc
fgets
fputs
fclose

 

 

< CODEBASE | TOP^ | MAINPAGE >

Text & Design By Tony Pisarra
© SophiaKnows 1998-2004