As mentioned in the Hello PHP! post, the first questions regarding a coding language should be about syntax. As we saw, in the Hello World! program (see below), PHP delimits instructions with the semicolon (;), PHP delimiters are required in PHP files, and single quotation marks are accepted delimiters for string literals.
<?php
echo 'Hello World!';
?>
Contents
Objectives
- To understand what PHP is and how a PHP script functions with a Web Server to handle Web Browser requests.
- To learn what software and components you need to get started with PHP.
- To create and run a simple PHP script.
- To learn how to store and access data in PHP variables.
- To understand how to create and manipulate numeric and string data/variables.
- To review how to create HTML input forms.
- To learn how to receive HTML form data with your PHP scripts.
HTML
- HTML is used to provide web browser output.
- PHP scripts may output any information format; we will output HTML to produce websites that work with web browsers.
How PHP Scripts are Accessed and Interpreted
Exploring the Basic PHP Development Process
The basic steps you can use to develop and publish PHP are:
- if you are publishing online:
- Create a PHP script file and save it to a local disk.
- Use FTP to copy the file to the server.
- Access your file using a browser, through server address yourserver/path/filename.
OR,
- if you are testing on your local server (e.g., XAMPP):
- Create a PHP script file and save it to the local server path.
- Ensure that your server is up and running.
- Access your file using a browser, through server address 127.0.0.1/path/filename or localhost/path/filename.
Given a script on a local server at
c:\XAMPP\htdocs\app-one\start.php
where c:\XAMPP is the installation path for XAMPP, htdocs is the server web root, the correct URL for this script would be
http://localhost/app-one/start.php
Online, htdocs is one of the usual web server root names… start here.
Creating a PHP Script File and Saving It to a Local Disk
You can use a number of different editors to create your PHP script files, e.g., Notepad, Notepad++, TextPad, Sublime Text.
- The PHP script starts with a <?php tag and ends with ?>.
- Between these tags is a single PHP print statement.
<?php
print("Hello, World!");
?>
The script must be placed in a folder that is under the server web root folder.
Accessing Your File Using a Browser
Given that your script is in a folder within the server document root, you must access it with the domain name of the server plus the correct path of the script relative to the server document root, e.g., given a script at
c:\XAMPP\htdocs\app-one\start.php
where htdocs is the server document root, and the server is local, the correct URL for this script would be
http://localhost/app-one/start.php
Proper Syntax
- PHP syntax is very similar to that of Java.
- Delimiters come in pairs.
- Parentheses (“(” and “)”) are used to enclose parameter lists.
- Quotation marks:
- Straight double quotation marks (“) are used to enclose strings such that PHP may substitute variables by their values.
- Straight single quotation marks (‘) are used to enclose a string literal.
- All quotation marks are straight (not slanted).
- Accolades (“{” and “}”) enclose method, class and namespace definitions, scopes,…
- Semicolons (;) end all executing instructions.
- The print statement syntax:
print ( “Your message to print” );- Enclose message in quotation marks
- End in a semi-colon
Use of Improper Syntax
Suppose you use the wrong syntax:
<html><head><title>something</title></head>
<body>
<?php
print ( “Hello, World! );
?>
</body>
</html>
The output will always tell you the origin of the error. Running this file, you should see a “Parse error: parse error in /… on line 4”. Since there is no compilation process, all errors, even syntax errors occur when you run the program. This is your debugging output.
Embedding HTML in a PHP Script
One way to use PHP is to embed HTML within PHP files. For example:
<html> <head> <title>HTML With PHP Embedded</title> </head> <body> <?php print ("<br> Using PHP is not hard<br>"); ?> and you can learn to use it quickly! </body> </html>
Note that to work properly, this must be a .php file, so that Apache sends the php script to the php interpreter.
Using Backslash (\) to Escape Characters within Strings
Sometimes you want to output an HTML tag that also requires double quotation marks. Use the backslash (“\”) character to signal that the double quotation marks themselves should be output:
print (“<font color=\”blue\”>”);
The above statement would output: <font color=”blue”>
Of course, it would be wiser to use single straight quotation marks to avoid having to escape the double straight quotation marks…
print (‘<font color=”blue”>’);
Using Comments with PHP Scripts
Comments enable you to include descriptive text along with the PHP script. Comment lines are ignored when the script runs; they do not slow down the run-time. Comments have two common uses:
- Describe the overall script purpose.
- Describe particularly tricky script lines.
<?php // This is a comment ?>
Can place on Same line as a statement:
<?php print ("Hello, World!"); //Output a line ?>
Another example:
<html>
<head><title> Generating HTML From PHP</title></head>
<body> <h1> Generating HTML From PHP</h1>
<?php
// Example script to output HTML tags
print ("Using PHP has <i>some advantages:</i>");
print ("<ul><li>Speed</li>");
print ("<li>Ease of use</li>");
print ("<li>Functionality</li></ul>"); //Output bullet list
?>
</body>
</html>
PHP allows a couple of additional ways to create comments:
<?php phpinfo(); # This is a built-in function ?>
Multiple line comments.
<?php
/* phpinfo() is a php function that is part of the base php language.
It displays information on the PHP version being used and all configured extentions. */
phpinfo(); ?>
Using PHP Variables
Variables are used to store and access data in computer memory. A variable name is a label used within a script to refer to the data.
In PHP, for example:
$cost = 4.25; $months = 12;
Assigning New Values to Variables
You can assign new values to variables:
$days = 3;
$newdays = 100;
$days = $newdays;
At the end of these three lines, $days and $newdays both have values of 100.
The Names of Variables
You can select just about any set of characters for a variable name in PHP, but they must:
- Use a dollar sign ($) as the first character
- Use a letter or an underscore character (_) as the second character. Other characters should be alphanumeric.
- Select variable names that make your code self-explanatory, e.g., $counter is more descriptive than $c or $ctr.
Combining Variables and the print Statement
To output the value of $x, write the following PHP statement:
print ("$x");
The following code will output “I would like to buy 6 apples.”
$num=6;
print ("I would like to buy $num apples.");
The following code will output “I would like to buy $num apples.”
$num=6; print ('I would like to buy $num apples.');
Full Example:
<html> <head><title>Variable Example</title></head> <body> <?php $first_num = 12; $second_num = 356; $temp = $first_num; //typical swap operation $first_num = $second_num; $second_num = $temp; print("first_num=$first_num<br>second_num=$second_num"); ?> </body> </html>
Arithmetic Operators
You can use operators such as a plus sign (+) for addition and a minus sign (–) for subtraction to build mathematical expressions, e.g.,
<?php
$apples = 12;
$oranges = 14;
$total_fruit = $apples + $oranges;
print ("The total number of fruit is $total_fruit.");
?>
These PHP statements would output “The total number of fruit is 26.”
Operator | Effect | Example | Result |
+ | Addition | $x = 2 + 2; | $x is assigned 4. |
– | Subtraction |
$y = 3; $y = $y – 1; | $y is assigned 3, and then 2. |
/ | Division | $y = 14 / 2; | $y is assigned 7. |
* | Multiplication |
$z = 4; $y = $z * 4; | $y is assigned 16. |
% | Remainder | $y = 14 % 3; | $y is assigned 2. |
A Full Example
<html>
<head><title>Variable Example</title></head>
<body>
<?php
$columns = 20;
$rows = 12;
$total_seats = $rows * $columns;
$ticket_cost = 3.75;
$total_revenue = $total_seats * $ticket_cost;
$building_cost = 300;
$profit = $total_revenue - $building_cost;
print ("Total Seats are $total_seats <br />");
print ("Total Revenue is $total_revenue <br />");
print ("Total Profit is $profit");
?>
</body>
</html>
WARNING: Using Variables with Undefined Values
If you accidentally use a variable that has not been initialized (never was assigned a value), then it will have no value (called a null value). When a variable with a null value is used in an expression PHP, PHP may not generate an error and may complete the expression evaluation. For example, the following PHP script will output “x= y=4”:
<?php
$y = 3;
$y = $y+$x+1; // $x has a null value
print ("x=$x y=$y");
?>
Writing Complex Expressions
Operator precedence rules define the order in which the operators get executed. For example,
$x = 5 + 2 * 6;
The value of $x
is either 42 or 17 depending on order of evaluation. Multiplication and division operations get executed before addition and subtraction. Therefore, the expression must be evaluated to 17.
PHP’s operator precedence rules are as follows, in order:
- operators within parentheses,
- multiplication and division operators,
- addition and subtraction operators.
E.g.,
$x = 100 - 10 * 2; //$ x = 80
$y = 100 - (10 * 2); //$ y = 80
$z = (100 - 10) * 2; //$z = 180
Full Example:
<html>
<head><title>Expression Example</title></head>
<body>
<?php
$grade1 = 50;
$grade2 = 100;
$grade3 = 75; //learning arrays will be very beneficial!
$average = ($grade1 + $grade2 + $grade3) / 3;
print ("The average is $average.");
?>
</body>
</html>
Working with PHP String Variables
Strings are used in scripts to hold data such as customer names, addresses, product names, and descriptions. Consider the following example, where $name is assigned “Christopher” and the variable $preference is assigned “Milk Shake”:
$name="Christopher";
$preference="Milk Shake";
WARNING: Be Careful Not to Mix Variable Types
Be careful not to mix string and numeric variable types, unless this is your intent. For example, you might expect the following statements to generate an error message, but they will not. Instead, they will output “y=1”:
<?php
$x = "banana";
$sum = 1 + $x;
print ("y=$sum");
?>
Using the Concatenate Operator
The concatenate operator (.) combines two separate string variables into one, e.g.,
$fullname=$firstname.$lastname;
$fullname will receive the string values of $firstname and $lastname connected together.
E.g.,
$firstname="John";
$lastname="Smith";
$fullname=$firstname.$lastname;
print("Fullname=$fullname");
This will output “JohnSmith”
You can also use double quotation marks to concatenate directly, e.g.,
$firstname="John";
$lastname="Smith";
$Fullname = "$firstname $lastname"; //AND
$Fullname2 = $firstname . " " . $lastname; //Have the same effect
Practical Functions for Strings
Function | Description |
strlen() | Return the length of the string, e.g., $len = strlen($name); |
trim() |
Removes blank characters from the beginning and end of a string, e.g., $in_name = ” Joe Jackson “; $name = trim($in_name); |
strtolower() and strtoupper() | Return the input string in all uppercase or all lowercase letters, respectively, e.g., $inquote = “Now Is The Time”; $lower = strtolower($inquote); $upper = strtoupper($inquote); |
substr() | Return a part of the string, as specified, e.g., $part = substr( $name, 0, 5); //return first 5 chars $part = substr( $name, 2); //return all chars from 3rd |
Example with substr()
<?php
$date = "12/13/2017";
$month = substr($date, 0, 2);
$day = substr($date, 3, 2);
$year = substr($date, 6);
print ("Year=$year, Month=$month, Day=$day");
?>
Getting input data from forms
For a primer on how to create HTML forms, see my post on Creating HTML Input Forms.
To receive data from a form with method=”POST” you use a special variable called $_POST, which is accessed with a string-type index, e.g.,
$firstName = $_POST["FirstName"];
will receive the input field with name=”FirstName” in the form submitted through POST and place it in a variable: $firstName.
To receive data from a form with method=”GET” we use a special variable called $_GET, which is accessed with a string-type index, e.g.,
$lastName = $_GET["LastName"];
will receive the input field with name=”LastName” in the form submitted through GET and place it in a variable: $lastName.
Full Example:
Suppose your HTML form uses the following:
Enter email address:<form action="" method="POST"> <br><input type="text" size="16" maxlength="20" name="email">…</form>
Then can receive input as follows:
<html>
<head><title>Receiving Input</title></head>
<body>
<font size=5>Thank You: Got Your Input.</font>
<?php
$email = $_POST["email"];
print ("<br>Your email address is $email");
?>
Summary
- PHP supports both numeric and string variables. String variables use different methods for value manipulation (for example, concatenation) than numeric variables do.
- You can use HTML forms to pass data to PHP scripts. HTML form elements include text boxes, text areas, password boxes, check boxes, radio buttons, and selection lists.
- PHP scripts can receive form element input values by using a PHP variable name that matches the one specified in the form element’s name argument.