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.
No comments:
Post a Comment