The Right Environment

PHP is typically used in combination with a Web server like Apache. Requests for PHP scripts are received by the Web server, and are handled by the PHP interpreter. The results obtained after execution are returned to the Web server, which takes care of transmitting them to the client browser. Within the PHP script itself, the sky's the limit - your script can perform calculations, process user input, interact with a database, read and write files... Basically, anything you can do with a regular programming language, you can do inside your PHP scripts.

From the above, it is clear that in order to begin using PHP, you need to have a proper development environment set up. This series will focus on using PHP with the Apache Web server on Linux, but you can just as easily use PHP with Apache on Windows, UNIX and Mac OS.

There's one essential concept that you need to get your mind around before we proceed further. Unlike CGI scripts, which require you to write code to output HTML, PHP lets you embed PHP code in regular HTML pages, and execute the embedded PHP code when the page is requested.

These embedded PHP commands are enclosed within special start and end tags, like this:

<<?php
... PHP code ...
?>

Here's a simple example that demonstrates how PHP and HTML can be combined:

<html>
<head></head>
<body>

Agent: So who do you think you are, anyhow?
<br />

<?php
// print output
echo 'Neo: I am Neo, but my people call me The One.';
?>

</body>
</html>

Not quite your traditional "Hello, World" program... but then again, I always thought tradition was over-rated.

Save the above script to a location under your Web server document root, with a .php extension, and browse to it.

What just happened? When you requested the script above, Apache intercepted your request and handed it off to PHP. PHP then parsed the script, executing the code between the marks and replacing it with the output of the code run. The result was then handed back to the server and transmitted to the client. Since the output contained valid HTML, the browser was able to render it for display to the user.

What just happened? When you requested the script above, Apache intercepted your request and handed it off to PHP. PHP then parsed the script, executing the code between the marks and replacing it with the output of the code run. The result was then handed back to the server and transmitted to the client. Since the output contained valid HTML, the browser was able to render it for display to the user.

A close look at the script will reveal the basic syntactical rules of PHP. Every PHP statement ends in a semi-colon. This convention is identical to that used in Perl, and omitting the semi-colon is one of the most common mistakes newbies make. That said, it is interesting to note that a semi-colon is not needed to terminate the last line of a PHP block. The PHP closing tag includes a semi-colon, therefore the following is perfectly valid PHP code:

<?php

// print output
echo 'Neo: I am Neo, but my people call me The One.'

?>

It's also possible to add comments to your PHP code, as I've done in the example above. PHP supports both single-line and multi-line comment blocks.

Blank lines within the PHP tags are ignored by the parser. Everything outside the tags is also ignored by the parser, and returned as-is. Only the code between the tags is read and executed.

A Case of Identity

Variables are the bread and butter of every programming language... and PHP has them too. A variable can be thought of as a programming construct used to store both numeric and non-numeric data; the contents of a variable can be altered during program execution. Finally, variables can be compared with each other, and you - the programmer - can write code that performs specific actions on the basis of this comparison.

PHP supports a number of different variable types: integers, floating point numbers, strings and arrays. In many languages, it's essential to specify the variable type before using it: for example, a variable may need to be specified as type integer or type array. Give PHP credit for a little intelligence, though: it automagically determines variable type by the context in which it is being used!

Every variable has a name. In PHP, a variable name is preceded by a dollar ($) symbol and must begin with a letter or underscore, optionally followed by more letters, numbers and/or underscores. For example, $popeye, $one and $INCOME are all valid PHP variable names, while $123 and $48hrs are invalid.

Note that variable names in PHP are case sensitive, so $me is different from $Me or $ME.

Here, the variables $name, $rank and $serialNumber are first defined with string and numeric values, and then substituted in the echo() function call. The echo() function, along with the print() function, is commonly used to print data to the standard output device (here, the browser). Notice that I've included HTML tags within the call to echo(), and those have been rendered by the browser in its output. You can do this too. Really.

An Equal Music

To assign a value to a variable, you use the assignment operator: the = symbol. This is used to assign a value (the right side of the equation) to a variable (the left side). The value being assigned need not always be fixed; it could also be another variable, an expression, or even an expression involving other variables, as below:

<?php

$age = $dob + 15;

?>

Interestingly, you can also perform more than one assignment at a time. Consider the following example, which assigns three variables the same value simultaneously:

<?php

$angle1 = $angle2 = $angle3 = 60;

?>

Not My Type

Every language has different types of variable - and PHP is no exception. The language supports a wide variety of data types, including simple numeric, character, string and Boolean types, and more complex arrays and objects. Here's a quick list of the basic ones, with examples:

# Boolean: The simplest variable type in PHP, a Boolean variable, simply specifies a true or false value.

<?php

$auth = true;

?>

Integer: An integer is a plain-vanilla whole number like 75, -95, 2000 or 1.

# Floating-point: A floating-point number is typically a fractional number such as 12.5 or 3.141592653589. Floating point numbers may be specified using either decimal or scientific notation.

<?php

$temperature = 56.89;

?>

# String: A string is a sequence of characters, like "hello" or "abracadabra". String values may be enclosed in either double quotes ("") or single quotes(''). (Quotation marks within the string itself can be "escaped" with a backslash (\) character.) String values enclosed in double quotes are automatically parsed for special characters and variable names; if these are found, they are replaced with the appropriate value. Here's an example:

<?php

$identity = 'James Bond';
$car = 'BMW';

// this would contain the string "James Bond drives a BMW"
$sentence = "$identity drives a $car";
echo $sentence;

?>

Market Value

If variables are the building blocks of a programming language, operators are the glue that let you build something useful with them. You've already seen one example of an operator - the assignment operator -, which lets you assign a value to a variable. Since PHP believes in spoiling you, it also comes with operators for arithmetic, string, comparison and logical operations.

A good way to get familiar with operators is to use them to perform arithmetic operations on variables.

PHP also allows you to add strings with the string concatenation operator, represented by a period (.). you can concatenate and assign simultaneously.

That's about it for this tutorial. You now know all about the basic building blocks and glue of PHP - its variables and operators.

Now that you know the basics, it's time to focus in on one of PHP's nicer features - its ability to automatically receive user input from a Web form and convert it into PHP variables. If you're used to writing Perl code to retrieve form values in your CGI scripts, PHP's simpler approach is going to make you weep with joy. So get that handkerchief out.

Forms have always been one of quickest and easiest ways to add interactivity to your Web site. A form allows you to ask customers if they like your products, casual visitors for comments on your site, and pretty girls for their phone numbers. And PHP can simplify the task of processing the data generated from a Web-based form substantially.

As you probably already know, the "action" attribute of the <form> tag specifies the name of the server-side script that will process the information entered into the form. The "method" attribute specifies how the information will be passed.

whenever a form is submitted to a PHP script, all variable-value pairs within that form automatically become available for use within the script, through a special PHP container variable: $_POST. You can then access the value of the form variable by using its "name" inside the $_POST container.

Obviously, PHP also supports the GET method of form submission. All you need to do is change the "method" attribute to "get", and retrieve values from $_GET instead of $_POST. The $_GET and $_POST variables are actually a special type of PHP animal called an array.

Operating With Extreme Caution

Thus far, the scripts we've discussed have been pretty dumb. All they've done is add numbers and strings, and read back to you the data you typed in yourself - not exactly overwhelming. In order to add some intelligence to your scripts, you need to know how to construct what geeks call a "conditional statement" - a statement which lets your script perform one of a series of possible actions based on the result of a comparison test. And since the basis of a conditional statement is comparison, you first need to know how to compare two variables and determine whether they're identical or different.

You've already seen some of PHP's arithmetic and string operators. However, the language also comes with operators designed specifically to compare two values: the so-called "comparison operators".

PHP 4.0 also introduced a new comparison operator, which allows you to test both for equality and type: the === operator. The following example demonstrates it:

<?php

/* define two variables */
$str = '10';
$int = 10;

/* returns true, since both variables contain the same value */
$result = ($str == $int);
print "result is $result
";

/* returns false, since the variables are not of the same type even though they have the same value */
$result = ($str === $int);
print "result is $result
";

/* returns true, since the variables are the same type and value */
$anotherInt = 10;
$result = ($anotherInt === $int);
print "result is $result";

?>

A Question of Logic

In addition to the comparison operators I used so liberally above, PHP also provides four logical operators, which are designed to group conditional expressions together. These four operators - logical AND, logical OR, logical XOR and logical NOT.

/* logical NOT returns true if the condition is false and vice-versa */
// returns false
$result = !($status == 1);
print "result is $result
";

/* logical XOR returns true if either of two conditions are true, or returns false if both conditions are true */
// returns false
$result = (($status == 1) xor ($auth == 1));
print "result is $result
";

Logical operators play an important role in building conditional statements, as they can be used to link together related conditions simply and elegantly.

Now that you've learnt all about comparison and logical operators, I can teach you about conditional statements. As noted earlier, a conditional statement allows you to test whether a specific condition is true or false, and perform different actions on the basis of the result. In PHP, the simplest form of conditional statement is the if() statement.

if (condition) {
do this!
}

The argument to if()is a conditional expression, which evaluates to either true or false. If the statement evaluates to true, all PHP code within the curly braces is executed; if it does not, the code within the curly braces is skipped and the lines following the if() construct are executed.

If Not This, Then What?

In addition to the if() statement, PHP also offers the if-else construct, used to define a block of code that gets executed when the conditional expression in the if() statement evaluates as false.

The if-else construct looks like this:


if (condition) {
do this!
}
else {
do this!
}

If the thought of confusing people who read your code makes you feel warm and tingly, you're going to love the ternary operator, represented by a question mark (?). This operator, which lets you make your conditional statements almost unintelligible, provides shortcut syntax for creating a single-statement if-else block. So, while you could do this:

$msg = $numTries > 10 ? 'Blocking your account...' : 'Welcome!';

PHP also lets you "nest" conditional statements inside each other.

PHP also provides you with a way of handling multiple possibilities: the if-elseif-else construct. A typical if-elseif-else statement block would look like this:


if (first condition is true) {
do this!
}
elseif (second condition is true) {
do this!
}
elseif (third condition is true) {
do this!
}
... and so on ...
else {
do this!
}

In this case, I've used the if-elseif-else control structure to assign a different menu special to each combination of days. Note that as soon as one of the if() branches within the block is found to be true, PHP will execute the corresponding code, skip the remaining if() statements in the block, and jump immediately to the lines following the entire if-elseif-else block.

The Only Acronym You'll Ever Need

If you're new to Web development, you could be forgiven for thinking that it consists of no more than a mass of acronyms, each one more indecipherable than the last. ASP, CGI, SOAP, XML, HTTP - the list seems never-ending, and the sheer volume of information on each of these can discourage the most avid programmer. But before you put on your running shoes and flee, there's a little secret you should know. To put together a cutting-edge Web site, chock full of all the latest bells and whistles, there's only one acronym you really need to know:

PHP

Now, while you have almost certainly heard of PHP, you may not be aware of just how powerful the language is, and how much it can do for you. Today, PHP has the enviable position of being the only open-source server-side scripting language that's both fun and easy to learn. This is not just advertising: recent surveys show that more than 16,000,000 Web sites use PHP as a server side scripting language, and the language also tops the list of most popular Apache modules.

Why, you ask? The short answer: it's powerful, it's easy to use, and it's free. Extremely robust and scalable, PHP can be used for the most demanding of applications, and delivers excellent performance even at high loads. Built-in database support means that you can begin creating data-driven applications immediately, XML support makes it suitable for the new generation of XML-enabled applications, and the extensible architecture makes it easy for developers to use it as a framework to build their own custom modules. Toss in a great manual, a knowledgeable developer community and a really low price (can you spell f-r-e-e?) and you've got the makings of a winner!

Setup a PHP Development Environment

1. Install 7-Zip

2. Install Apache

Apache is the web server that will server the PHP files. After installation, in your browser, go to http://localhost and you will see a page saying that your Apache installation was successful.

3. Install PHP

We will now download and install PHP 5 and then make changes to both the Apache and PHP configuration files so that Apache can serve PHP files. Unzip the file you downloaded. In the directory where the PHP files were unzipped, select all files with CTRL-A and then press CTRL-X . Then create a directory called c:\php and type CTRL-V to move all the files there. Now move (don't just copy) the file c:\php\php5ts.dll to c:\windows\php5ts.dll. Create a directory called c:\webs. Rename the file c:\php\php.ini-dist to c:\php\php.ini.

In the file that you just renamed ( c:\php\php.ini ), make the following changes to the values doc_root and extension_dir, note that you should use backward slashes.

doc_root = "c:\webs"

extension_dir = "c:\php\ext"


Now open Apache's httpd.conf file at C:\Program Files\Apache Group\Apache2\conf\httpd.conf and change the DocumentRoot entry to: DocumentRoot "C:/webs" , note that you should use forward slashes.

DocumentRoot "C:/webs"

In the same httpd.conf file, change the Directory entry to: "C:/webs" , note that you should use forward slashes.

<Directory "C:/webs">

Again in the same httpd.conf file, search for the phrase "media types" and add the following text after the two AddType lines:.

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php .php5
Action application/x-httpd-php "/php/php-cgi.exe"
SetEnv PHPRC "C:/php"

And lastly in the httpd.conf file, change the DirectoryIndex entry to: index.htm index.html index.php.

We now need to restart Apache so the above changes take effect, so in your taskbar, double-click on your Apache icon.

Test your Apache/PHP installation by creating a file called C:\webs\test\index.php with the following content, and then in your browser go to http://localhost/test.

4. Install MySQL - database

after installation of mysql, In the file c:\php\php.ini remove the preceding semi-colons from php_mysql.dll, php_mysqli.dll and php_pdo_mysql.dll, and php_mbstring.dll

Restart Apache by double-clicking on your Apache icon.

Test your Apache/PHP/MySQL installation by creating a file called C:\webs\test\testMysql.php with the following content, and then in your browser go to http://localhost/test/testMysql.php. If you see no errors and a list of categories is displayed in your browser, then your Apache/PHP/MySQL installation was successful.

<?php
$connection = mysql_connect("localhost", "root", "admin");
$database = mysql_select_db("mysql");
$result = mysql_query("SELECT name FROM help_category");

while($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $row[0] . '
';
}
mysql_close();
?>

5. Install phpMyAdmin

Unzip the file that you downloaded. Press CTRL-A to select all the files that you unzipped, and then press CTRL-X to indicate that you want to move them. Create a directory called c:\webs\phpmyadmin and press CTRL-V to move all the phpMyAdmin files to this directory.

Create a file called C:\webs\phpmyadmin\config.inc.php with the following content.

<?php
/* Servers configuration */
$i = 0;
/* Server localhost (config:root) [1] */
$i++;
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['extension'] = 'mysql';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'admin';
?>

In your browser, goto http://localhost/phpmyadmin and you will see the phpmyadmin start screen.

6. Install Java

To run Eclipse we first need Java so we will download and install it now. Goto developers.sun.com/downloads. Click on the Java SE (JDK) 6 link. Click on the Download button for JDK 6u1. Click Accept. Click on Windows Offline Installation, Multi-language. Click OK to save it to disk. Double click on file that was downloaded. Accept agreement. Click Next and it will install for about 8 minutes. Unclick the Show the readme file checkbox and click Finish .

7. Install Eclipse

Eclipse is a professional editor normally used for Java. We will install it in this step and then install the PHPEclipse plugin so we can use it with PHP.

Goto www.eclipse.org/downloads and click Eclipse Classic. Click "Save to Disk" and click on OK . Unzip the Eclipse file that you downloaded. Type in c:\ and click OK (this will create a directory called c:\eclipse and unpack everything there. Double-click on the file c:\eclipse\eclipse.exe. Set the workspace to C:\webs , click the checkbox, then click OK . Click on the workbench icon. Close Eclipse by clicking on the X. Click the checkbox and OK .

8. Install PHPEclipse

We will now install an add-on to Eclipse which allows you to develop in PHP. Goto sourceforge.net/projects/phpeclipse and click on the Download PHPEclipse button. Click on the download link for the latest release. Click on the first link to download the PHPEclipse zip file. Unzip the downloaded PHPEclipse zip file. Copy the sub-directory under features to c:\eclipse\features. Copy all the sub-directories under plugins to c:\eclipse\plugins. Click the eclipse.exe file again to start it. Change from Java to PHP perspective by clicking on the perspective icon and then on Other.... Choose PHP and then click OK .

9. Install Subversion

Subversion allows you keep a tightly controlled repository of your files of all your changes, a good idea if you work by yourself and necessary if you work in a team.

Goto downloads.open.collab.net/collabnet-subversion.html and click on the Server and Client for Windows Server 2003 link. Double-click on the .exe file you downloaded. Check the svnserve box and click next. We will be accessing our repository via the file system so we don't need the Apache module. Check the Windows Service checkbox and click Next . Click Install . Wait about 20 seconds for it to install.

10. Install TortoiseSVN

TortoiseSVN is a tool which enables you to check files in and out of the Subversion repository with the Windows Explorer.


Goto www.tortoisesvn.net/downloads and click on the .msi link. Double-click on the .msi file you downloaded. Click the I Accept... button and then click Next . Click on Next . Click Install . Unclick Show Changelog and click Finish . Click Yes to restart your system.

11. Install Tortoise Plug-in

The tortoise plug-in allows you to use Tortoise from inside Eclipse.

Goto www.tabaquismo.freehosting.net/ignacio/eclipse/tortoise-svn/subversion.html and click on the Version 1.0.9 link.

Unzip the .zip file that you downloaded. Move the directory that you just unzipped to C:\eclipse\plugins.



9. Install Subversion











10. Install TortoiseSVN











11. Install Tortoise Plug-in




Robert Johnson Legend

Robert Leroy Johnson was born on May 8, 1911 to Aug 16, 1938. Robert Johnson a famous blues musician, and also an indutee of the Rock and Roll Hall of Fame. His best hit is Love in Vain