Free PHP Tutorial with PHP Tips - Beginner to Advanced PHP
ASP-style tags. PHP BasicsIn this lesson of the PHP tutorial, you will learn...
How PHP WorksWhen a user navigates in her browser to a page that ends with a .php extension, the request is sent to a web server, which directs the request to the PHP interpreter.As shown in the diagram above, the PHP interpreter processes the page, communicating with file systems, databases, and email servers as necessary, and then delivers a web page to the web server to return to the browser. The php.ini FileBefore we look at PHP syntax, we should briefly mention the php.ini file. This is a plain text file that is used to configure PHP. When the PHP interpreter is started, it reads the php.ini file to determine what settings to use. We will mention this file from time to time throughout the course, but for now, it is enough that you are aware of its existence.Basic PHP SyntaxPHP TagsPHP code must be contained in special tags so that the PHP interpreter can identify it. Depending on the PHP configuration, these tags can take several forms:
In this manual, we will use the first form shown as it is the most common and the most portable. |
PHP Statements and Whitespace
PHP statements must be inside of PHP tags to be processed by the PHP interpreter. Each PHP statement must end with a semi-colon, which tells the PHP interpreter that the statement is complete. If a semi-colon does not appear at the end of a line, the interpreter will assume that the statement continues onto the next line.The PHP interpreter condenses all sequential whitespace in PHP scripts to a single whitespace. This convenient feature allows PHP developers to structure their code in a readable format without being concerned about the effects of line breaks and tabs.
Comments
PHP has two forms of comments:- Single-line comments begin with a double slash (//).
- Multi-line comments begin with "/*" and end with "*/".
Syntax
// This is a single-line comment
/*
This is
a multi-line
comment.
*/
PHP Functions
There are literally hundreds of built-in PHP functions that do everything from returning the current date and time on the server to pulling data out of a database. A function might take zero arguments (e.g, phpinfo(), which returns information on the PHP environment) or it might take several arguments (e.g, mail(), which takes three required and two optional arguments). The syntax for calling a function is straightforward:Syntax
function_name(arguments);
Code Sample: PhpBasics/Demos/PhpInfo.php
<html> <head> <title>PHPINFO</title> </head> <body> <?php //Output information on the PHP environment phpinfo(); ?> </body> </html>
Introduction to php.net
Hello World!
It is an unwritten rule that every programming course must contain a "Hello World!" script. Here it is:Code Sample: PhpBasics/Demos/HelloWorld.php
<html> <head> <title>Hello World!</title> </head> <body> <?php //Write out Hello World! echo 'Hello World!'; ?> </body> </html>
Code Explanation
Notice the following about the above code:This code isn't very exciting. In fact, PHP doesn't buy us anything here as we could have just as easily output the result using straight HTML. There is nothing dynamic about this script. After learning about variables, we'll take a look at some more interesting examples.
- Code between <?php and ?> is processed by the PHP interpreter.
- The echo command is used to print text back to the browser.
Variables
PHP variables begin with a dollar sign ($) as shown below.Syntax
$var_name = "Value";
Variable Types
Variable Type | Explanation |
---|---|
Integer | whole number |
Double | real number |
String | string of characters |
Boolean | true or false |
Array | list of items |
Object | instance of a class |
Variable Names (Identifiers )
- consist of letters, digits, underscores and dollar signs
- cannot begin with a digit
- are case sensitive
Type Strength
PHP is weakly typed, meaning that variables do not need to be assigned a type (e.g, Integer) at the time they are declared. Rather, the type of a PHP variable is determined by the value the variable holds and the way in which it is used.Hello Variables!
Here is the "Hello World!" script again, but this time we use a variable.Code Sample: PhpBasics/Demos/HelloVariables.php
<?php $Greeting = 'Hello World!'; ?> <html> <head> <title><?php echo $Greeting; ?></title> </head> <body> <?php echo $Greeting; ?> </body> </html>
Code Explanation
This time the string "Hello World!" is stored in the $Greeting variable, which is output in the title and body of the page with an echo command.
Exercise: First PHP Script
Duration: 5 to 10 minutes.
In this exercise, you will write a simple PHP script from scratch. The script will declare a variable called $Today that stores the day of the week.- Open a new document and save it as Today.php in the PhpBasics/Exercises folder.
- Declare a variable called $Today that holds the current day of the week as literal text.
- Output $Today in the title and body of the page.
- Test your solution in a browser. The resulting HTML page should look like this:
Instead of assigning a literal string (e.g, "Monday") to $Today, use the built-in date() function so that the script won't have to be manually updated every day to stay current.
Variable Scope
A variable's scope determines the locations from which the variable can be accessed. PHP variables are either superglobal, global, or local.Variable Scope | Explanation |
---|---|
superglobal | Superglobal variables are predefined arrays, including $_POST and $_GET. They are accessible from anywhere on the page. |
global | Global variables are visible throughout the script in which they are declared. However, they are not visible within functions in the script unless they are re-declared within the function as global variables. |
function | Variables in the function scope are called local variables. Local variables are local to the function in which they are declared. |
Superglobals
Again, superglobal variables are predefined arrays, including $_POST and $_GET and are accessible from anywhere on the page. The complete list of superglobals is shown below.- $_GET - variables passed into a page on the query string.
- $_POST - variables passed into a page through a form using the post method.
- $_SERVER - server environment variables (e.g, $_SERVER['HTTP_REFERER'] returns the URL of the referring page).
- $_COOKIE - cookie variables.
- $_FILES - variables containing information about uploaded files.
- $_ENV - PHP environment variables (e.g, $_ENV['HTTP_HOST'] returns the name of the host server.
- $_REQUEST - variables passed into a page through forms, the query string and cookies.
- $_SESSION - session variables.
Style | Syntax (using $_GET) | Notes |
---|---|---|
Short | $varname |
|
Medium | $_GET['varname'] |
|
Long | $HTTP_GET_VARS['varname'] |
|
Constants
Constants are like variables except that, once assigned a value, they cannot be changed. Constants are created using the define() function and by convention (but not by rule) are in all uppercase letters. Constants can be accessed from anywhere on the page.Syntax
define('CONST_NAME',VALUE);
Variable-Testing and Manipulation Functions
PHP provides built-in functions for checking if a variable exists, checking if a variable holds a value, and removing a variable.Function | Explanation | Example |
---|---|---|
isset() | Checks to see if a variable exists. Returns true or false. | isset($a) |
unset() | Removes a variable from memory. | unset($a) |
empty() | Checks to see if a variable contains a non-empty, non-false value. | empty($a) |
PHP Operators
Operators in PHP are similar to those found in many modern C-like programming languages.Operator | Name | Example |
---|---|---|
+ | Addition | $a + $b |
- | Subtraction | $a - $b |
* | Multiplication | $a * $b |
/ | Division | $a / $b |
% | Modulus | $a % $b |
Operator | Name | Example |
---|---|---|
. | Concatenation | $a . $b
'Hello' . ' world!' |
Operator | Name | Example |
---|---|---|
= | Assignment | $a = 1;
$c = 'Hello' . ' world!'; |
+=
-=
*=
/=
%=
.= | Combination Assignment | $a += 1;
$a -= 1;
$a *= 2;
$a /= 2;
$a %= 2;
$a .= ' world!';
|
++ | Increment By One | $a++;
++$a; |
-- | Decrement By One | $a--;
--$a; |
Operator | Name | Example |
---|---|---|
?: | Ternary | $foo = ($age >= 18) ? 'adult' : 'child'; |
@ | Error Suppression | $a = @(1/0); |
Creating Dynamic Pages
Single Quotes vs. Double Quotes
In PHP, for simple strings you can use single quotes and double quotes interchangeably. However, there is one important difference of which you need to be aware. Text within single quotes will not be parsed for variables and escape sequencesCompare the examples below.Code Sample: PhpBasics/Demos/SingleQuotes.php
<html> <head> <title>Single Quotes</title> </head> <body> <?php $person = 'George'; echo '\tHello\n$person!!'; ?> </body> </html>
Code Sample: PhpBasics/Demos/DoubleQuotes.php
<html> <head> <title>Single Quotes</title> </head> <body> <?php $person = "George"; echo "\tHello\n$person!!"; ?> </body> </html>
To see the effect of the special characters (\n and \t), you will have to view the source of the resulting page.
Passing Variables on the URL
A common way to pass values from the browser to the server is by appending them to the URL as follows:Syntax
http://www.webucator.com/hello.php?greet=Hello&who=World
The HTML page below shows an example of how these name-value pairs might be passed.
Code Sample: PhpBasics/Demos/HelloHi.html
<html>
<head>
<title>Preferred Greeting</title>
</head>
<body>
Do you prefer a formal greeting or an informal greeting?
<ul>
<li><a href="HelloHi.php?greet=Hello">Formal</a></li>
<li><a href="HelloHi.php?greet=Hi">Informal</a></li>
<li><a href="HelloHi.php?greet=Howdy">Friendly</a></li>
</ul>
</body>
</html>
Code Sample: PhpBasics/Demos/HelloHi.php
<?php //Assign the passed variable to a variable with //a more convenient name. $greeting = $_GET['greet']; ?> <html> <head> <title><?= $greeting ?> World!</title> </head> <body> <?php echo "$greeting World!"; ?> </body> </html>
Code Explanation
Notice the following about the code above.
- Variable names begin with a dollar sign ($).
- Values passed in the query string are part of the $_GET array and can be accessed using the following syntax: $_GET['fieldname'].
- A shortcut for echo 'text to print'; is <?= 'text to print' ?>.
Leave a Comment