Projects Are About Humans. Deal With That!

Archive for the 'php' Category

PHP Conditional Structures

As you've read in a previous article, a statement to PHP is like a sentence in English. A statement can be an assignment, a function call, a loop, a conditional statement of even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well.

One of the most important statement in many languages, PHP included, is the "if" structure. It allows the execution of code, based on different conditions. The syntax is simple:

if (expression)

statement

While the expression should be boolean, this is not a must, because, as you've read before, PHP automatically evaluates expressions according to the context in which they're used. So if "expression" evaluates to "TRUE", then PHP will execute the statement.

if ($num1 > $num2) //is "$num1" bigger than "$num2"?

print "The first number is bigger than the second number"; //if it is, do this

There are times when you want more then one statement to be executed. You don't have to insert 10 if structure for 10 statements, you just have to group all 10 statements in a statement group using curly braces:

if ($num1 > $num2)

{

print "The first number is bigger than the second number";

$bigger = $num1; //assigning the value of "$num1" to "$bigger"

}

Sometimes you may want to execute a statement if a condition is met, and another statement if the condition is not met. In order to do this, you can use "else" after the first statement, which will execute another statement if the condition resolves to "FALSE".

if ($num1 > $num2) //is "$num1" bigger than "$num2"?

{

print "The first number is bigger than the second number"; //if it is, do this

$bigger = $num1; //assigning the value of $num1 to $bigger

}

else

{

print "The second number is bigger than the first number";//if it's not, do this

$bigger = $num2; //assigning the value of $num1 to $bigger

}

Another way to extend an if statement is using "elseif". Similar to "if", "elseif" requires an expression to evaluate. On the other hand, unlike "else", "elseif" will execute a statement if the "if" expression evaluates to FALSE, and only if the "elseif" expression evaluates to TRUE.

if ($num1 > $num2) //is "$num1" bigger than "$num2"?

{

print "The first number is bigger than the second number"; //if it is, do this

$bigger = $num1; //assigning the value of $num1 to $bigger

}

elseif ($num1 == $num2) //the first expression is FALSE, so try this one

{

print "Both numbers are equal"; //got it!

}

else //if the previous if/elseif expressions are FALSE, do this…

{

print "The second number is bigger than the first number"; //the only option left

$bigger = $num2; //assigning the value of $num1 to $bigger

}

You can use several "elseif" structures in the same if statement, but remember that an "elseif" statement will only be executed if the previous expressions were all evaluated to "FALSE", and the current "elseif" expression evaluates to "TRUE". In other words, once the "if" structure evaluates an expression to "TRUE", it executes the corresponding statement, then it exits the structure.

When you want to compare the same variable or expression with many different values, and execute a different piece of code depending on which value it equals to, the "if" statement might prove to be repetitive. This is where "switch" comes in. The "switch" statement is similar to a series of if statements on the same expression.

if ($number == 1)

{ print "the number is 1"; }

if ($number == 2)

{ print "the number is 2"; }

if ($number == 3)

{ print "the number is 3"; }

So you can use a switch structure to write this:

switch ($number)

{

case 1:

print "the number is 1″;

break;

case 2:

print "the number is 2″;

break;

case 3:

print "the number is 3″;

break;

}

While it may look easy at first, the "switch" statement is more complex than you think. "switch" parses each statement and executes it. While at first, no code is executed, when a "case" statement is found with a value that matches the value of the "switch" expression, then PHP begins to execute the statements. It continues to execute statements until the end of the "switch" block, or the first time it finds a "break" statement. If you don't write a "break" statement at the end of a statement group, PHP will go on executing the statements of the following case. For example:

switch ($number)

{

case 1:

print "the number is 1″;

case 2:

print "the number is 2″;

case 3:

print "the number is 3″;

}

If "$number" holds the value "1", this piece of code will output all three messages. If "$number" is "2", it will output only the last two messages; if "$number" is "3", then it will only output the last message. Therefore, it's important to add "break" statements in order for your code to perform as intended. On the other hand, you can use this if you have different values that should output the same result – just leave the values with no corresponding statement.

The "switch" structure has his own "else", but it's called "default". "switch" will try to match all the given values, but if it doesn't find any, it can be provided a default statement, which will be executed. This should be the last statement in the "switch" structure:

switch ($number)

{

case 1:

print "the number is 1″;

break;

case 2:

print "the number is 2″;

break;

case 3:

print "the number is 3″;

break;

default: //if no other values are matched, do the following statement

print "the number is not equal to 1, 2 or 3";

}

1 comment

PHP operators And Expressions

In any language, human and computer, the way we put words together it's very important. Like the way people use conjunctions in spoken language to properly say what they mean, the same way PHP uses operators to perform an action. An operator is a symbol or series of symbols that, when used along with some values, performs an action and usually produces a new value. The values used with the operator are called operands. When you say "two plus three", in PHP you write it this way: "2 + 3" – the numbers "2" and "3" are the operands, and the addition symbol "+" is the operator. The combination of operands with an operator to manufacture a result is called an expression. Therefore, you can say that an expression is any combination of functions, values, and operators that resolve to a value. The numbers "2" and "3" are also expressions; so to speak, if you can use it as if it were a value, then it is an expression.

One of the most used operators in PHP is the assignment operator "=". You can use this to initialize a variable; the operator evaluates the right-hand operand and assigns it to its left-hand operand. While most operators use their operands to come up with a result, and don't change their values in any way, assignment operators break this rule. Because you can include nest expressions, you can perform multiple things at the same time. So not only you can assign the word "John" to the variable "$name", but you can output the variable at (almost) the same time. For example:

print ($name = "John"); //assigns "John" to

"$name", then outputs "$name"

Arithmetic operators are also very used in any programming language. You know for sure what each of them can do, so we'll just stick to pointing them out: addition "+", subtraction "-", division "/", multiplication "*", and modulus "%". Appending additional characters to a str ing is performed using the concatenation operator, which is a single dot ".". Treating both operands as str types, it appends the right-hand operand to the left, the result being, of course, a str ing.

$first_name = "John";

$last_name = "Davis";

print $first_name . $last_name; //outputs "John Davis"

Although there is one assignment operator, there are a lot of combination operators used with the assignment operator and the arithmetic operators. A combined assignment operator consists of a standard operator symbol followed by an equals sign. Combination assignment operators save you the trouble of using two operators yourself. For example:

$x = 5;

$x = $x + 5; //$x now equals 10

The second statement can be wrapped up into a much smaller statement:

$x = 5;

$x += 5; //$x now equals 10

You can do the same with other arithmetic operators. While "+=" adds the value of the right operand to the left operand, "-=" subtracts it, "*=" multiplies it, "/=" divides it, "%=" uses the modulus function, and finally ".=" is used to concatenate two str types, appending the right operand to the left one. Another two important combined operators are "++" and "–". They're mostly used in conjunction with variables, and increment or decrement the value by one. The operand can either be located at the left side (pre-increment or pre-decrement operator) or the right side of the operator (post-increment or post-decrement operator).

$x = 5;

$x++; //$x now equals 6

++$x; //$x is now 7

$x–; //$x is down to 6

Comparison operators perform tests on their operands. They return the boolean value "TRUE" if the test is successful, or "FALSE" otherwise. This type of expression is useful in control structures, such as "if" and "while" statements. Besides the basic "<" and ">", "<=", ">=", there are some other operators you should know about. "==" means equivalence, "!=" means non-equivalence, "===" means left is equivalent to right and is the same type. These operators are mostly used with integers or doubles, although you can use the equivalence operator to compare str ings.

You can use a conditional operator in conjunction with the increment or decrement operator. Pay attention to the location of the assignment operator. If you're using pre-increment or pre-decrement (the operand is at the right side of the operator), then PHP increments or decrements the variable, then performs the test. On the other hand, if you use post-increment or post-decrement operators, PHP will perform the test, and after that it will increment or decrement the variable, regardless of the result of the test.

$x = 1;

$bool_var = $x++ < 2; //TRUE, because PHP first performs the test, then increments $x

$y = 9;

$bool_var = –$y > 8; //FALSE, because PHP decrements $y to 8, then performs the test

Logical operators allow the comparison between booleans. The "or" operator "||" returns "TRUE" if either the left or the right operand is true. The "and" operator "&&" returns "TRUE" if both left and right operands are true. They are mostly use to test two or more expressions that resolve to a boolean. The "not" operator "!" returns true if the expression is false, so in a matter of speaking, it reverses the value of the boolean expression. If the operands consist of two or more expressions, you should use parenthesis to separate them:

($x > 5) && (!($X < 20))

The following conditional operator can seem very odd at first, but it is very useful.

$first ? $second : $third

If the value of the first expression is TRUE, then the second expression is evaluated, and that is the result of the conditional expression. Otherwise, the third expression is evaluated, and that is the value.

No comments

Programming PHP Arrays

The most inconvenient thing about a variable in software programming is that you can only store one value at a time. Arrays are special types that allow variables to overcome this limitation, so you can store as many values as you want in the same variable. For example, instead of having two variables "$number1" and "$number2", you could have an array "$numbers" that will hold both values. Imagine the same thing with ten numbers. What about a hundred? Because of the flexibility of the array, it can store two values or two hundred values, without having to define other variables. The PHP server-side scripting language indexes all the values within an array using a number or a string, so you will know which of the values you're using.

Programming with arrays is easy. You can process each item one after another, or you could just take one at random. Each item in an array is commonly referred to as an element. These elements can be accessed directly via their index, which can be either a number or a string. By default, PHP starts indexing elements numerically, from zero, and increments the element's index with each new addition, so keep in mind that the index of the last elements in a numerically indexed array is always the total number of elements minus one. Indexing arrays by string can be useful in cases where you need to store both names and values.

There are two ways you can create an array: with the "array()" function or directly using the array identifier "[]". You can use the "array()" function when you want to assign multiple elements to an array at a time. Don't think that an array can only contain elements of a certain type (for example, only numbers). You can have numbers, strings and booleans in the same array, PHP won't mind at all.

$names = array("John", 279, "Betty",TRUE);

This creates an array called "$names" which holds the specified elements. You can access an array element by placing its index between square brackets, right after the array name. Not only you can retrieve a value this way, but you can also assign a value to that element.

print $names[2]; //outputs "Betty"

$names[3] = "Harrison"; //replaces TRUE with "Harrison"

Remember that PHP starts indexing from zero, therefore "$names[0]" is "John", and so on - the index of any element always is one less than the element's place in the list. Another way to define an array is using the array identifier "[]" in conjunction with the array name. You can also use this to add new elements in you have already created an array – either using the "array()" function or the array identifier.

$names[] = "John";

$names[] = "Mary";

$names[] = "Betty";

$names = array("Harry", "Samantha","Danny");

There is no need to place any numbers between the square brackets, PHP takes care of the index number, so you don't have to figure out which is the next available slot. This doesn't mean that you cannot add numbers, but pay attention not to skip any of them, because PHP will initialize only the elements with the index number you specify.

Arrays indexed by strings, and not numbers, can prove to be useful when you need to access elements in array by name, and not by number. For example, if you have an address book, it would be much better to have a field called "name" or "address", instead of a numeric field called "1" or "2". You can define an associative array pretty much the same way you define a numerically indexed array.

$sysinfo = array(computer_name => "My computer",

cpu_mhz => 2800,

memory_size => 512,

multimedia => TRUE);

Or you can use the array identifier:

$sysinfo[computer_name] = "My computer";

$sysinfo[cpu_mhz] = 2800;

$sysinfo[memory_size] = 512;

$sysinfo[multimedia] = TRUE;

It's good to know that an array element can itself be an array, so this enabled you to create sophisticated data structures called multidimensional arrays. Let's say you have an address book, and you use an array to hold the information on the people you know (John, Mary, Betty, Harry). But on the other hand, each element must be a collection of a person's details (first name, last name, telephone number). This is how you define it:

$address_book = array(

array(first_name => "John", last_name => "Davis", phone_number => "1234567"),

array(first_name => "Mary", last_name => "Stewart", phone_number => "1234568"),

array(first_name => "Betty", last_name => "Willis", phone_number => "1234569"),

array(first_name => "Harry", last_name => "Miller", phone_number => "1234560"));

You can access the data using two indices, the first one for "$address_book" – which is a numeric index, and the second one for the person's details – which is a string index. The following text outputs the text "Mary":

print $address_book[1][first_name];

There are a lot of functions to use with arrays. You can merge, slice, shift and sort arrays, by using the functions with the same name: "array_merge()", "array_slice()", "array_shift()", and "sort()". Sorting is definitely one of the most used functions. The "sort()" function can sort both alphabetically or numerically, depending on the array elements. Read the PHP documentation to learn how to use these functions.

4 comments

PHP Variables and Constants

A variable is a holder for a type of data. So, based on its type, a variable can hold numbers, strings, booleans, objects, resources or it can be NULL. The variable name consists of letters, numbers and/or the underscore character (“_”), preceded by a dollar (“$”) sign. It cannot include spaces or non-alphanumeric characters. Here are some possible variable names: “$i”, “$a_very_long_variable_name”, “$6723”, “$TotalRESULT”. You should keep your variable names short and descriptive. A variable named “$f” is unlikely to mean much to you when you return to your code after a month or so. On the other hand, a variable named “$filename”, should make more sense.

The contents of a variable can be changed at any time, and so can its type. To declare a variable, you must include it in your script. You can declare a variable and assign it a value in the same statement. For example:

$number1 = 8; //assigns the value “8” to a variable called “$number1”

print $number1; //outputs the value that the variable “$number1” holds

This statement declares a variable using the assignment operator (“=”). The variable is called “$number1”, and it holds the value “8”. After the assignment, you can treat the variables as if they were values, so “print $number1” is equivalent to “print 8”, that is, if “$number” holds the value “8”. Remember that sometimes it is important to know the type of data a variable holds, so make sure that a variable contains an integer or a float before using it in a mathematical calculation, for example.

An interesting feature in PHP is dynamic variables. This means that a variable name can be stored into variable itself. Let's consider the following:

$product = “computer”; //defines a variable called “$product”

$$product = “IBM”; //defines another variable called “$computer”

After parsing these two lines, PHP will a variable called “$computer” and assign it the value “IBM”. This little script is equivalent to:

$product = “computer”;

$computer = “IBM”;

This means that “$$product” is equivalent to “$computer”, because the variable “$product” holds the value “computer”.

Another nice feature is variable referencing. By default, variables are assigned by value. In other words, if you were to assign “$varA” to “$varB”, a copy of the value held in “$varA” would be then assigned to “$varB”. So if you change the value of “$varA”, it has absolutely no effect on “$varB”:

$varA = “one”; //assigns “one” to “$varA”

$varB = $varA; //assigns the value that “$varA” holds to “$varB”

$varA = “two”; //assigns “two” to “$varA”

print $varB; //outputs the value that “$varB” holds

This script outputs “one”, so the value of “$varB” is not changed in any way. On the other hand, you can assign a variable a reference to another variable by adding an ampersand (&) in front of the “$varA” when assign the value to “$varB”:

$varA = “one”; //assigns “one” to “$varA”

$varB = &$varA; //assigns a reference of “$varA” to “$varB”

$varA = “two”; //assigns “two” to “$varA”

print $varB; //outputs the value that “$varB” holds

This outputs “two”. Why, you ask? Because $varB holds a reference to $varA's value, rather than a copy of its contents. So all changes made to $varA are seen when accessing $varB. In other words, both $varA and $varB now point to the same value.

While variables offer a flexible way of storing data, and you can freely change their values and the type of data they store at any time, you may sometimes want to work with a value that you don't want to alter. This is where constants come in. You can use the PHP function define() to create a constant. After you've done this, its value cannot be changed. That value can only be a number or a string. You should know that by convention, the name of the constant should be in capitals. Unlike variables, constants don't require a dollar symbol before their name:

define(“MAXIMUM_MARK”, 10); //defines a constant called “MAXIMUM_MARK”

define(“NAME”, “John Smith”); //defines a constant called “NAME”

print “Welcome ” . NAME; //outputs the value that the constant “NAME” holds

This outputs “Welcome John Smith”. Notice the concatenation operator (“.”), which appends the string “Welcome” and adds our constant.

PHP also provides a number of built-in constants for you. “__FILE__”, for example, returns the name of the file currently being read by the interpreter. “__LINE__” returns the line number of the file. These constants are useful for generating error messages. You can also find out which version of PHP is interpreting the script using the “PHP_VERSION” constant.

No comments

Types In PHP

PHP uses different types of data in its many functions. For example, if you have a script that adds up two numbers, you need to provide two numbers. If a script searches a text within another text, you need to provide two series of characters. These are two simple types of data.

Different types of data take up different amounts of memory and may be treated differently when they are manipulated in a script – for example, a number between 0 and 255 uses only one byte of memory; the series of characters "Johnny" uses 6 bytes of memory - therefore some programming languages demand that the programmer declares in advance which type of data a variable will contain, so they will know how much memory to allocate. PHP doesn't require you to declare the type of data a variable will use, and just interprets the data according to the context in which that data is used. For example, if you provide a function with a number instead of some characters, the function will treat the number as a set of characters. It will do this, but without changing the type of the data; instead, it will use its own interpretation of that data.

Some of the most common types in PHP are: boolean, integer, floating-point number and string. A boolean type expresses a truth value, so it can be either "TRUE" or "FALSE". An integer is a whole or real number, meaning a number without a decimal point. On the other hand, a floating-point number (also called float, double, or real number) is a number that includes a decimal point. A string is a collection of characters; when you work with strings in your scripts, they should always be surrounded by double (") or single (') quotation marks. Arrays and objects are also important data types in PHP, but we'll talk about those later.

You can use PHP's built-in function gettype() to test the type of any data, and settype() to change the type of that data. You can also change the type by casting, which means that you place the type in brackets in front of the data, thus instructing PHP to create a copy of that data's value converted to the type you specified. The main difference between settype() and a cast is the fact that casting produces a copy, leaving the original data untouched.

Another important type of data in PHP is "NULL". If a data has no assigned value, or its value has been unset using the unset() function, then that data is null. NULL is the only possible value of type NULL.

Special functions require you to use special types of data called resources. These data hold references to an external application, for example handlers to opened files, database connections, images, so you cannot convert any value to a resource; it can only be manipulated by a limited number of functions.

No comments

Structure Of PHP Script

Let's get back to the script we used before:

<?php
print "Hello Web!";
?>

In this simple script you can see some of the most used components of a PHP script. First off, PHP tags are used to separate the actual PHP content from the rest of the file. You can inform the interpreter that you want it to execute your commands by adding a pair of these: standard tags "<?php ?>"; short tags "<? ?>"; ASP tags "<% %>"; script tags "<SCRIPT LANGUAGE="php"> </SCRIPT>". The standard and the script tags are guaranteed to work under any configuration, the other two need to be enabled in your "php.ini"

Now that you know how to define a block of PHP code, take a closer look at the code above. The "print" function is used to output data, so anything output by "print()" ends up in the HTML file. Therefore, you can say that a function is a command that performs an action. Usually, you send some data to the function, and the function uses that data to come up with a result. There are a lot functions in PHP, and almost each one performs a different action. Data sent to a function is almost always placed in parentheses after the function name; there are some exceptions where parentheses are optional, and the "print()" function is one of them.

After that first line of code, you can see a semicolon. This semicolon informs the interpreter that you have completed a statement - a statement is to PHP what a sentence is to the English language. It represents an instruction to the interpreter, and some additional data. If PHP doesn't find a semicolon at the end of your statement, then it will continue parsing the file until it finds one, ignoring any white-spaces or empty lines. So, your one statement doesn't necessarily have to use only one line of code. There can be two or more statements on a single line, but, on the other hand, a statement could use two or more lines. PHP also ignores white spaces, so you can have as many blanks as you want between the statements, and between the statements' parameters. You should know that you don't have to use a semicolon with the last statement in your script (just before the closing tag). So the following scripts are equivalent:

<?php
print "This is a test" ;
?>

<?php print "This is a test" ?>

Commenting you PHP code can be very helpful. If some code seems to be very clear at the time of writing, the same code can look like a black hole a few weeks later, when you want to modify it. So adding comments to your code can save you time later on, and make it easier for other people to work with your code. But, wait, what is a comment? A comment is a text in a script that is ignored by the interpreter. So you can write anything you want in it, from copyright notices to detailed information about your code. PHP recognizes a comment by checking out if it contains two forward slashes ("//") or a single hash sign ("#"). The text beginning from either of these marks until the end of the line is ignored. You can also use multi-line comments. They begin with a forward slash followed by an asterisk ("/*") and end with an asterisk followed by a forward slash ("*/"):

<?php
/*
This is a demo script.
All it does is output Hello Web! in your browser.
*/

print "Hello Web!"; //outputs a message

//copyright (C) SoftwareProjects.org 2004
?>

1 comment

Your First PHP Script

Writing PHP code is very easy. You don't need specialized software to do this, all the tools should be found in a new installation of your operating system. Let's start off with a little script and analyze its contents. PHP files are made up of plain text, just like a HTML document. So open your favorite text editor, and type the following:

<?php

print "Hello Web!";
?>

Always remember to save PHP's files with the extension ".php" - this is very important, because it tells the server to how to treat these files, and run the appropriate interpreter to "understand" their contents. So just go ahead and give it an easy-to-remember name like "hello.php". If you run the web-server on your own computer, copy the file to the root location of your web-server ? you can find this in your web-server's documentation. If you're not running the server on your computer, then you must upload the file to your server. You can do this using a FTP client. After you've put your script where it should belong, you must open it via your web-browser, so point your web-browser to the path of the script according to your server's address - for example, if you're running a server on your own computer, then just load into your web-browser the file http://localhost/hello.php

If everything goes ok, then you will see "Hello Web!" (without the quotation marks) in your web-browser's output window. If PHP is not installed or the server didn't recognize the file's extension, you will see the source code of the script (the script itself).

While the above script is pure PHP, you can incorporate it into a HTML document. So go ahead create a file named "hello2.php" under your web-server root directory with the following content:


<html>
<head>
<title>PHP Test 2</title>
</head>

<body>
<?php print "<b>Hello Web!</b>"; ?>
</body>
</html>

You can easily see now that PHP only parses the text between the PHP tags ("<?php (…) ?>"), and replaces this text with the output of the script. The rest of the script is left alone, and is forwarded as-is to the web-browser. This way you will be able to combine both HTML and PHP in the same page. This is how the file will look like after being parsed by PHP:

<html>
<head>

<title>PHP Test 2</title>
</head>
<body>
<b>Hello Web!</b>
</body>

</html>

As you can see, incorporating HTML into a PHP document is simply a matter of typing in the code. The output of this last script will be pretty much the same as the first one, except that the new document will also have a title: "PHP Test 2″, and the welcome message will be written using bold characters.

You can include as many blocks of PHP code as you need in a single document, combining them with HTML as required. Although you can have multiple blocks of code in a single document, they combine to form a single script. Anything defined in the first block (variables, functions, or classes, for example) usually will be available to subsequent blocks.

No comments

PHP Configuration

After installing PHP, the next step would be configuring its many options. In order to do this, you must edit the configuration file, which should be called "php.ini". PHP reads this file when it starts, so you shouldn't expect your changes to apply as soon as you've modified the file, you have to restart the web-server after you've changed PHP's configuration file!

The configuration file is not provided with PHP; instead, there are two templates which should help you decide on PHP settings: a development purposes template "php.ini-dist" - and a production site template "php.ini-recommended". If no configuration file is used, then PHP will use the factory settings.

If you intend to use PHP for learning and development, you should definitely use the first template. If you will use PHP for production purposes, you should go with the second template. This second one makes PHP more efficient and more secure. Unfortunately, this way of improving PHP's performance may make it incompatible with some applications, and may prove to be difficult to develop with. So go ahead and choose the one it suits you best, and then copy it under the name "php.ini" in its intended location - you can find out where PHP looks for its configuration file if you read the documentation. The locations of the configuration file may differ for each platform, so, for example, on UNIX-systems you should place it in "/usr/local/lib/"; on a Windows system, the default location is the Windows directory. A "php.ini" file in the current working directory will override one in the default location, so it's easy to change the behavior of PHP on a per-directory basis.

The configuration file is fully commented, so you can go over each one setting and see the effect on your application, and then decide weather to modify it or not. Changing the values is actually very easy, you just have to open the configuration file in your favorite text file editor, and simply modify the settings according to your needs. Again, remember to restart the web-server after you've altered the configuration file.

The settings in the php.ini file take the form of a setting name and a value separated by an equals sign. White spaces between these two are ignored; a semicolon instructs PHP not to take into consideration the text that follows the semicolon, until the end of the line. Most settings' names are suggestive to their behavior, and you will find some useful descriptions before each setting.

1 comment

PHP Installation

Before you start programming with PHP, you must first acquire, install, and configure the PHP interpreter. PHP is available for a lot of platforms, and works in conjunction with many web-servers. Along with PHP itself and a web-server you also need a web-browser, so you can view the outcome of your work.

The latest version of PHP can be downloaded from www.php.net; after the download is complete, don't forget to unpack the archive. There are two available downloads: the source code, which you can use to compile PHP, and the binary version of PHP, which means that it's already compiled. If you're new in the business, you should go with the binary version, for it will save you from a lot of headaches. If you don't have already installed a web-server, you should go ahead install one for your operating system (for example Apache on Linux, and IIS or Apache on Windows); a web browser is also required, but this should be the least of your concern, you most probably have it already installed. If you don't want to run the web-server on your own, you can find a hosting company that will host your web-site. This way, you can skip the installation, start writing scripts. There are a lot of hosting companies that offer free hosting services, just search it on the Internet and you'll find a lot of offers to choose from.

PHP and your web-server

There are two ways of attaching PHP to your web-server. The first and most common way is with using PHP's direct module interface - also called SAPI - for the most common web-servers: Apache, Microsoft IIS, Netscape and iPlanet. The second way to use PHP is as a CGI processor, which means that you must set up the server to use the command line executable of PHP, so it can process the PHP file requests on the server. This method mostly applies to the web-servers that PHP doesn't have a direct module interface for.

PHP has installation instructions for both ways. Before installing, you should always make sure that you are logged into the system as the root user (administrator). If you're not allowed to access the system's root account, you should ask your system administrator to install PHP for you.

SAPI installation

The first way of installing PHP and the easiest way to get PHP up and running is by using a direct module interface. This will require some configuring in your web-server; for example, Apache requires you to edit its configuration file and add a few new entries. In order to find out exactly what you need to do in order to properly install PHP on Apache, or any other web-server, you should read PHP's documentation.

The second way of installing PHP is not always recommended by the web-server's developer. Apache calls this method ?suicidal?, because, if not configured properly, could allow a user with not-so-good intentions to access some of the web-server's files which are not intended to be public. So if you're a beginner, you should stay away from this method of installing PHP. Even advanced users sometimes fail to cover all the security issues.

After you've completed the installation, you should remember to take PHP for a test drive, before you start programming. You wouldn't want to ask people around why your script isn't working, when the installation wasn't performed correctly.

1 comment

What Is PHP?

The endless possibilities of the PHP scripting language and a great community of users has made it one of the most popular open-source languages. For all you people living outside the UNIX world, Open Source means it doesn't cost anything. You can use it as much as you want and where you want, and nobody will ever charge you thousands of dollars for licenses and support. Even though it was originally conceived as a set of macros to help coders maintain personal home pages, its name grew a lot more from its purpose. Since then, PHP's capabilities have been extended, taking it beyond a set of utilities to a full-featured programming language, capable of managing huge database-driven online environments.

Links of interest
Free Project Management Education

PHP scripting

PHP is now officially known as "PHP: HyperText Preprocessor". It is a server-side scripting language usually written in an HTML context. Unlike an ordinary HTML page, a PHP script is not sent directly to a client by the server; instead, it is parsed by the PHP binary or module, which is server-side installed. HTML elements in the script are left alone, but PHP code is interpreted and executed. PHP code in a script can query databases, create images, read and write files, talk to remote servers - the possibilities are endless. The output from PHP code is combined with the HTML in the script and the result sent to the user?s web-browser, therefore it can never tell the user whether the web-server uses PHP or not, because all the browser sees is HTML.

PHP's support for Apache and MySQL further increases its popularity. Apache is now the most-used web-server in the world, and PHP can be compiled as an Apache module. MySQL is a powerful free SQL database, and PHP provides a comprehensive set of functions for working with it. The combination of Apache, MySQL and PHP is all but unbeatable.

That doesn?t mean that PHP cannot work in other environments or with other tools. In fact, PHP supports an extensive list of databases and web-servers. The rise in popularity of PHP has coincided with a change of approach in web-publishing. While in the mid-1990s it was ok to build sites, even relatively large sites, with hundreds of individual hard-coded HTML pages, today?s webmasters are making the most of the power of databases to manage their content more effectively and to personalize their sites according to individual user preferences.

Reasons for using PHP

There are some indisputable great reasons to work with PHP. As an open source product, PHP is well supported by a talented production team and a committed user community. Furthermore, PHP can be run on all the major operating systems with most servers.

The speed of development is also important. Because PHP allows you to separate HTML code from scripted elements, you will notice a significant decrease in development time on many projects. In many instances, you will be able to separate the coding stage of a project from the design and build stages. Not only can this make life easier for you as a programmer, but it also can remove obstacles that stand in the way of effective and flexible design.

Well-maintained open source projects offer users additional benefits. You benefit from an accessible and committed community who offer a wealth of experience in the subject, as fast and as cheap as possible. Chances are that any problem you encounter in your coding can be answered swiftly and easily with a little research. If that fails, a question sent to a mailing list or forum can have an intelligent, authoritative response. You also can be sure that bugs will be addressed as they are found, and that new features will be made available as the need is defined. You will not have to wait for the next commercial release before taking advantage of improvements, and there is no hidden interest in a particular server product or operating system. You are free to make choices that suit your needs or those of your clients and incorporate whatever components you want.

20 comments

« Previous Page