PHP: Hypertext Preprocessor
Assoc. Prof. Mohammad Faidzul Nasrudin
Learn by
Doing://
What is PHP
• PHP originally stood for Personal Home Page, but it now stands for
the Hypertext Preprocessor. It is:
– created by Danish-Canadian programmer Rasmus Lerdorf in 1994.
– used together with HTML to create dynamic web applications.
– free to download and use and runs on various platforms.
• By default, PHP files have ".php“ extension
• The standard PHP interpreter, powered by the Zend Engine
– a compiler and runtime environment for the PHP scripting language
that compiles and executes the PHP code.
• W3Techs reports that, as of January 2022, PHP is used by 78.1%
of all the websites.
PHP installation
Example
• We will get PHP by installing XAMPP/WAMP/LAMP 1. DocumentRoot
– They has a build-in PHP (fully configured) "C:/xampp/htdocs"
• Most web hosting providers offer PHP support
2. <FilesMatch "\.php$">
• In Apache web server, PHP files is configured to be
SetHandler application/x-
processed by a Zend Engine software implemented as
a module, a daemon or as a Common Gateway httpd-php
Interface (CGI) executable. 3. </FilesMatch>
– Setting DocumentRoot
4. LoadModule php7_module
– Adding PHP MIME type
"c:/xampp/php/php7apache2_4
– Loading Module .dll"
• In XAMPP, check [Link] & [Link] files
How the web server processes PHP files
• A PHP script can be placed anywhere in the file and starts with <?php and ends with ?>
• When a browser send a HTTP request to open a PHP file (with a .php extension):
1. The web server starts scanning the file in HTML mode. It assumes the statements are HTML and
sends them to the browser without any processing.
2. The web server continues in HTML mode until it encounters a PHP opening tag (<?php).
3. When it encounters a PHP opening tag, the web server hands the processing over to the PHP
module. The web server then uses the PHP module to execute the PHP statements. If there is
output from PHP, the server sends the output to the browser.
4. The web server continues in PHP mode until it encounters a PHP closing tag (?>).
5. When the web server encounters a PHP closing tag, it returns to HTML mode. It resumes scanning,
and the cycle continues from Step 1.
Basic PHP Syntax
Example
• A PHP file normally contains HTML tags, and PHP 1. <?php echo "How are you?"; ?>
scripting and other codes like CSS and JavaScript. 2. <?php
• A PHP script can be placed anywhere in the document 3. // comment
– starts with <?php 4. echo "How ";
5. echo "are ";
– ends with ?>
6. echo "you?";
• PHP syntax is very similar to C language where each
7. # another comment
statement ends with a semicolon (;).
8. /*
• Use double slashes (//) or hash (#) for a single-line 9. Line 1 comment
comment
10. Line 2 comment
• Multiple lines comment start with /* and end with */ 11. */
12. ?>
Creating (Declaring) Variables
Example
• In PHP, a variable starts with the $ sign, followed by 1. <?php
the name of the variable. 2. $_mycolor = "yellow";
• Since PHP is loosely typed language, it has no 3. $loop = 10;
command for declaring a variable. 4. $SIZE = 45.5;
– It is created the moment you first assign a value to it. 5. ?>
• Rules for PHP variables:
– A variable name must start with a letter or the
underscore character
– A variable name cannot start with a number
– A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
Case Sensitivity
Example
• In PHP, all keywords (e.g. if, else, while, echo, etc.), 1. <?php
classes, functions, and user-defined functions are NOT 2. $age = 23;
case-sensitive. 3. echo $age;
– However; all variable names ARE case-sensitive. 4. ECHO $AGE;
• Therefore, $age and $AGE are two different variables. 5. EchO $aGe;
6. ?>
Output Variable to HTML
Example
• PHP is used to output data to the screen. 1. <?php
• You can use: 2. echo ("red ");
– echo statement. 3. Echo "lorry, ";
4. Print ("yellow ");
– print statement.
5. Print "lorry.");
6. // red lorry, yellow lorry.
7. ?>
Variable Scope
Example
• Variables can be declared anywhere in the PHP script. 1. <?php
• The scope of a variable is the part of the script where 2. $text = "hi";
the variable can be referenced/used. 3. function print() {
• PHP has three different variable scopes: 4. global $text;
5. echo $text;
– global: It is declared outside the function. It can be
accessed anywhere in the program. To access it within a 6. echo GLOBAL['text'];
function, use the GLOBAL keyword before the variable. 7. {
8. ?>
– local: It is declared within a function. It can be accessed
within the function. It cannot be accessed outside the
function.
– static: local variables that does not free its memory after
the program execution leaves the scope.
Data Types
Example
• PHP supports the following variable data types: 1. <?php
– String – Array 2. $num = 100;
– Integer – Object 3. $text = (string) $num;
4. settype($num, "string");
– Float – NULL
5. var_dump($num);
– Boolean
6. ?>
• var_dump() is a predefined function to return data type
of a variable.
• We can change the datatype of a PHP variable by:
– explicit type casting
– settype(variable, type) – override variable
String
Example
• A string can be any text inside quotes. You can use 1. <?php
single or double quotes. 2. $str1 = "Student's ID";
• There are some commonly used functions to 3. $str2 = 'The "special" one';
manipulate strings: 4. ?>
– strlen() - Return the Length of a String
– str_word_count() - Count Words in a String
– strrev() - Reverse a String
– strpos() - Search For a Text Within a String
– str_replace() - Replace Text Within a String
• Refer to full list of string functions at
[Link]
foreach Loop
• The foreach loop works only on arrays, and is 1. <?php
used to loop through each key/value pair in an
array. 2. foreach ($array as $value) {
array key value 3. code to be executed;
4. }
Indexed array:
0 1 2 5. foreach ($array as $key => $value) {
$person = array(“Tom”, “Ben”, “Sarah”);
6. code to be executed;
7. }
Associative array:
8. ?>
$age = array(“Tom"=>“25", "Ben"=>“17", “Sarah"=>“21");
Array
Example
• An array refers to a data structure storing one or more related types of values in a single
value. For instance, if you are looking to store 50 numbers, instead of specifying 50
variables, you can simply define an array of length 50.
• There are three types of arrays, and you can assess each array value through an ID, also
known as the array index.
– Numeric Array - It refers to an array with a numeric index. Values are stored and accessed in a
linear fashion
– Associative Array - It refers to an array with strings as an index. Rather than storing element values
in a strict linear index order, this stores them in combination with key values.
– Multidimensional array - Arrays containing one or more arrays
• In PHP, the array() function is used to create an array.
Operators
Example
• Operators are used to perform operations on variables and values such as:
– Arithmetic operators – Logical operators
– Assignment operators – String operators
– Comparison operators – Array operators
– Increment/Decrement operators – Conditional assignment operators
• In general, the syntax of these operators similar to operators in C/Java language. We are
not going to discuss them except new operator introduced in PHP.
– Comparison Operators (identical and not identical)
– Array Operators (identity and non-identity)
isset()
Example
• Operators are used to perform operations on variables and values such as:
– Arithmetic operators – Logical operators
– Assignment operators – String operators
– Comparison operators – Array operators
– Increment/Decrement operators – Conditional assignment operators
• In general, the syntax of these operators similar to operators in C/Java language. We are
not going to discuss them except new operator introduced in PHP.
– Comparison Operators (identical and not identical)
– Array Operators (identity and non-identity)
if - elseif - else
Example
• The syntax of if statement in PHP is similar to the one in C/Java language.
• There are two ways to implement it:
– Pure PHP
– PHP + HTML
User Defined Function
Example
• Besides the built-in PHP functions, we can create our 1. <?php
own functions. It is called User Defined Functions
• A function: 2. function functionName() {
– is a block of statements that can be used repeatedly in a 3. code to be executed;
program. 4. }
– will not execute immediately when a page loads.
5. ?>
– will be executed by a call to the function.
Built-in Function: Date()
Example
• The PHP date() function formats a timestamp to a more readable date and time.
• Syntax: date(format, timestamp)
– format: Required. Specifies the format of the timestamp
• d - Represents the day of the month (01 to 31)
• m - Represents a month (01 to 12)
• Y - Represents a year (in four digits)
• l (lowercase 'L') - Represents the day of the week
– timestamp: Optional. Specifies a timestamp. Default is the current date and time
• Characters, like"/", ".", or "-" can also be inserted between the characters
• strtotime() to convert a string to date/time.
Built-in Function: Date() (2)
Example
• For times formatting, here are some characters that are commonly used:
– h - 12-hour format of an hour with leading zeros (01 to 12)
– i - Minutes with leading zeros (00 to 59)
– s - Seconds with leading zeros (00 to 59)
– a - Lowercase Ante meridiem and Post meridiem (am or pm)
• Refer to full list of formatting character at
[Link]
include() Files
Example
• It is possible to insert the content of one PHP file into 1. <?php
another PHP file (before the server executes it), with 2. include 'filename';
the include or require statement. 3. # or
• Including files saves a lot of work. 4. require 'filename';
– You can create a standard header, footer, or menu file for 5. ?>
all your web pages.
– You need to update the include file only.
• Upon failure (e.g. file not found):
– require will produce a fatal error (E_COMPILE_ERROR) and stop
the script
– include will only produce a warning (E_WARNING) and the script
will continue
Form Handling
Example
• The PHP superglobals $_GET and $_POST are used to 1. <?php
collect data from forms.
• When the user fills out the a form and clicks the submit 2. if (isset($_POST['id'])) {
button, the form data is sent for processing to a PHP 3. $myid = $_POST['id'];
file named in action attribute. The form data is sent 4. }
with the HTTP GET/POST method.
• $_GET is an array of variables passed to the current 5. ?>
script via the URL parameters.
• $_POST is an array of variables passed to the current
script via the HTTP POST method.
• Please use isset() to make sure the variable is set
When to use GET?
Example
• Information sent from a form with the GET method is visible to everyone (all variable
names and values are displayed in the URL).
• GET also has limits on the amount of information to send. The limitation is about 2000
characters.
• However, because the variables are displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases.
• GET may be used for sending non-sensitive data.
When to use POST?
Example
• Information sent from a form with the POST method is invisible to others (all names/values
are embedded within the body of the HTTP request) and has no limits on the amount of
information to send.
• Moreover POST supports advanced functionality such as support for multi-part binary
input while uploading files to server.
• However, because the variables are not displayed in the URL, it is not possible to
bookmark the page.
• Developers prefer POST for sending form data.
Thank you
For your attention