What does PHP stand for?
PHP Hypertext Processor
PHP Hypertext Processor
PHP Hypertext Processor
PHP Hypertext Processor Recursive acronym!
Not Personal Home Page
PHP Installation Guide
https://www.sitepoint.com/how-to-install-php-on-windows/
#step1downloadthephpfiles
PHP
• The full form of PHP is Hypertext Preprocessor.
• It was abbreviated previously as Personal Home Page.
• It is a programming language widely used to build web
applications or websites.
• It is the server-side scripting language encoded with
HTML to develop Dynamic website, Static website or
Web applications.
What is PHP?
•Server-side programming language
•Designed for quick development of HTML based
dynamic web pages
–Server side scripts embedded in HTML pages
–<?php …… ?>
•Elements of C, Java, and Perl
Evolution of PHP
• 1994, Rasmus Lerdorf: started off as a series of
Perl scripts
• June 8, 1995: Personal Home Page/Forms
Interpreter, released to the public
• June, 1998, PHP3
• PHP4 introduced features of object-oriented
programming
– Objects/classes
– Pass/return by reference
• PHP5 added more OO features
– Exception handling
– Abstract classes and methods
Client: makes a request
requests an Internet
Client resource by
(browser) specifying a URL and
providing input via HTTP
Web encoded strings
browser
GET hello.php HTTP/1.1 Server
Host: www.massey.ac.nz:80
os
Web
server
os
Internet
Network Core
Work Flow : Client Side
1.Client Request (Browser to Web Server):
1. The user interacts with a web application by entering a
URL or clicking on a link.
2. The browser sends an HTTP request to the web server.
2.Web Server Processing (PHP file):
1. The web server (e.g., Apache, Nginx) receives the HTTP
request.
2. If the request involves dynamic content generated by PHP,
the web server routes the request to the appropriate PHP
file.
3. The PHP script executes on the server, processing any
logic required for the request.
3.Database Interaction (PHP to Database):
1. If the PHP script needs to retrieve or manipulate data
from the database, it interacts with the database
management system (DBMS) using a database-specific
extension or library like PDO (PHP Data Objects) or MySQLi.
2. The PHP script typically sends SQL queries to the
database server.
Server: responds
• Webserver supports
HTTP.
Server
Web
server My codes
PHP
HTTP HTML MySQL
interpreter
Client
Operating System
Web
TCP/IP
browser
Internet
Work Flow : Server Side
4. Data Processing (PHP):
1. The PHP script processes the data received from the
database as needed.
2. It may perform additional calculations, formatting, or
other operations on the data.
5. HTML Generation (PHP to HTML):
1. The PHP script generates HTML content dynamically
based on the processed data and any logic defined in the
script.
2. The generated HTML, along with any other necessary
assets (CSS, JavaScript), is sent back to the web server.
6. Server Response (Web Server to Browser):
1. The web server sends the HTTP response, containing the
HTML content and any associated assets, back to the
client's browser.
7. Client Rendering (Browser):
1. The browser receives the HTTP response.
2. It renders the HTML content received, displaying the web
What’s happening?
Client (browser) Web server
GET hello.php HTTP/1.1
Host: www.massey.ac.nz:80
Find hello.php
Parse the file
Run php parts through PHP interpreter
Deliver resulting document to port 80
HTTP/1.1 200 OK
(document body)
Display resulting
document on the
screen
PHP Designer
Configure your PHP editor to access the PHP interpreter
From the menu bar, select Tools/Preferences
1st PHP program
Enter this text in a file called “hello.php”
<html>
<head><title>Hello</title></head>
<body>
<?php
print "<h1>Hi there!</h1>";
?>
</body>
</html>
Load the URL in a browser and see what happens
Comparison with Javascript
Javascript is sent from server and runs on the client
side.
PHP runs on the server, just like CGI scripts.
The client does not see the PHP code - only the
results.
results
But PHP has some advantages.
Interpreted language
PHP is an interpreted language, i.e. an interpreter runs the code
directly without compiling
Interpreted languages include: PHP, Perl, Python
Compiled languages include: C, C++, Java
PHP code is executed on the server, and the plain HTML result is
sent to the browser.
Basic Syntax
• a PHP scripting block always starts with <?php and ends
with ?>.
• a PHP scripting block can be placed anywhere in the
document.
• contains HTML tags, just like an HTML file, and some PHP
scripting code.
• each code line in PHP must end with a semicolon.
• The file must have a .php extension. If the file has a .html
extension, the PHP code will not be executed.
• possible extensions: ".php", ".php3", ".php4", ".php5“,
".phtml”,
• ".inc", ".tpl",
PHP Variables
Variables in PHP are dynamically typed - no need to declare them
- PHP is a weakly-typed programming language
Variable names begin with $ then a character (not number)
$value = 1;
$x = 1.432344;
$myName = “Rasmus Lerdorf”;
yourName = “Zeev Suraski”; //invalid, missing $
$7eleven = “McGyver”; //invalid, starts with a number
PHP supports references (BE CAREFUL syntax is slightly different
from C++!)
$a = &$x;
Assign by reference (an alias)
To assign by reference, simply place an ampersand (&) at the
beginning of the variable which is being assigned (the source
variable). For instance, the following code snippet outputs 'My name is
Angus' twice:
<html><head><title>1st PHP</title></head><body>
<?php
$foo = "Angus"; // Assign the value ‘Angus' to
$foo
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is $bar"; // Alter $bar...
echo $bar;
echo "<br>"; // Newline
echo $foo; // $foo is altered too.
?>
</body></html>
Try the following
Modify “hello.php” to print your name after assigning it to a variable.
What happens if this line is inserted into the php script?
print "<small>" . date("Y M d", getlastmod()) . "</small>";
What happens if you call phpinfo()?
phpinfo() is a valuable debugging tool as it contains all EGPCS
(Environment, GET, POST, Cookie, Server) data.
<?php
$name = "Your Name";
echo "Hello, $name!";
?>
If the line print "<small>" . date("Y M d", getlastmod()) .
"</small>"; is inserted into the PHP script, it will print the last
modification date of the script in a small font.
This line concatenates the result of date("Y M d", getlastmod()),
which formats the last modification date in the format "Year Month
Day", with HTML tags <small> and </small> to display it in a smaller
font.
If you call phpinfo() in the script, it will display a comprehensive
information page about the PHP environment, including PHP version,
server information, PHP configuration settings, environment variables, and
more.
This can be useful for debugging and troubleshooting purposes but
should be used with caution, especially in production environments, as it
reveals potentially sensitive information about your server configuration.
Jumping in and out of PHP
<html><head><title>1st PHP</title></head><body>
<?php
print "This line was PHP generated";
?>
<p> This line was not... </p>
<?php
print "This line was also PHP generated";
?>
</body></html>
Comments
C-style:
// this is a comment
Shell script style:
# this is a comment
Multi-line comments:
/* this is a comment
this is the continuation of the comment */
Note: Nested multi-line comments are not allowed.
PHP Variables
Boolean boo
Integer int
Float flo
String str
Array arr
Object obj
PHP Variables
Convention:
$strName1='some name';
$intNumber1=2000000000;
$floNumber2=2.456;
$floNumber3=1.8e308; //notice scientific notation
PHP Constants
By default, case-sensitive as are variables
define(“DEFAULT_SCRIPT”, “php”);
define(“MIN_SPEED”, 2);
define(“DEFAULT_SCRIPT”, “php”,TRUE);
You can turn a constant variable case-insensitve
using a third argument set to TRUE.
PHP Constants
<?php
// Define constants
define('DEFAULT_SCRIPT', 'php');
define('MIN_SPEED', 2);
// Using the constants
echo "Default script: " . DEFAULT_SCRIPT .
"<br>";
echo "Minimum speed: " . MIN_SPEED . "<br>";
// You can use them in conditional statements
if (MIN_SPEED > 5) {
echo "The speed is acceptable.<br>";
} else {
echo "The speed is too slow.<br>";
}
// You can use them in function parameters
function processScript($script) {
if ($script == DEFAULT_SCRIPT) {
echo "Processing script: $script<br>";
} else {
PHP Constants
}
processScript(DEFAULT_SCRIPT);
?>
PHP Operators
=, ==, +, -, /, *, &&, ||, !, ++, --, %, /=, *=, >, <, >=, <=, &, |, ^, ~
– All similar to C
Additionally,
String concatenation
. $fullName = $firstName . “ “ . $lastName;
Identical test operator:
operator same type as well as same
===, !=== value
Error suppression command
@ When placed in front of an expression in PHP, any
error messages that might be generated by that
expression will be ignored.
Back tick to execute shell commands (be careful for
`` variations on different platforms)
Identical test operator:
operator same
type as well as same value
<?php
// Identical comparison
$a = 10;
$b = "10";
// This will return false because $a and $b have different types
var_dump($a === $b); // Output: bool(false)
// Another example
$c = 10;
$d = 10;
// This will return true because $c and $d have the same value
and type
var_dump($c === $d); // Output: bool(true)
Identical test operator:
operator same
type as well as same value
<?php
// Identical comparison
$a = 10;
$b = "10";
// This will return false because $a and $b have different types
var_dump($a === $b); // Output: bool(false)
// Another example
$c = 10;
$d = 10;
// This will return true because $c and $d have the same value
and type
var_dump($c === $d); // Output: bool(true)
Identical test operator:
operator same
type as well as same value
// Example with different types but same value
$e = 10;
$f = "10";
// This will return false because $e and $f have different types
var_dump($e === (int)$f); // Output: bool(false)
// Example with arrays
$arr1 = array(1, 2, 3);
$arr2 = array(1, 2, 3);
// This will return false because $arr1 and $arr2 are different instances
var_dump($arr1 === $arr2); // Output: bool(false)
// Example with identical arrays
$arr3 = array(1, 2, 3);
$arr4 = $arr3;
// This will return true because $arr3 and $arr4 have the same value and type
var_dump($arr3 === $arr4); // Output: bool(true)
?>
@ Error suppression
command
<?php
$result = 1 / 0; // This will trigger a warning: "Division by zero"
?>
// Without error suppression
$result = 1 / 0; // This will trigger a warning: "Division by zero"
// echo "Result: $result"; // This line will not be executed due to the error
// With error suppression $result = @1 / 0; // This will not trigger a
warning
echo "Result: $result"; // This line will be executed, but the result will be
undefined or NaN (depending on PHP version)
Execution Operator (` `)
Note that these are not single-quotes!
PHP will attempt to execute the contents of the
backticks as a shell command;
<?php
$output = `dir *.php`;
echo "<pre>$output</pre>";
?>
<html>
<head><title>Date of Birth</title></head>
HTML with Form
<body>
<p>Please enter your date of birth </p>
<form action="dataEntry.php" method="post">
<table cellspacing="5">
<tr><td valign="middle" colspan=2> Day
<!-- drop-down list for days -->
<select name=day>
<option selected="selected" value=""> no day </option>
<option value="1">1</option>
Consider this html source to <option value="2">2</option>
<option value="3">3</option>
produce a simple form.
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
Very cumbersome <option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
and error prone! <option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
</td></tr>
</table>
</form> </body> </html>
PHP makes it easier
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<?php
<option value="7">7</option>
<option value="8">8</option>
for ($day = 1; $day<= 31; ++$day) {
<option value="9">9</option>
<option value="10">10</option> print "\t<option value=\"$day\">$day</option>\n";
<option value="11">11</option>
<option value="12">12</option> }
<option value="13">13</option>
<option value="14">14</option> ?>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
Note: use the escape sequence \” to produce double quotes
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
Escape Characters
\n line feed character
\r carriage return character
\t tab
\\ backslash character
\$ dollar sign
\” double quote character
Arrays
An array in PHP is actually an ordered map.
A map is a type that associates values to keys.
array( key => value , ... )
// key may only be an integer or string
// value may be any value of any type
Creating & printing Arrays
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);
Output: Array
( [0] =>
1 [1] =>
2 [2] =>
3 [3] =>
4 [4] =>
5 )
Creating & printing Arrays
// Create an array with forced indices.
$array = array(1, 1, 1, 1, 1, 8 => 1, 4 => 1, 19, 3 => 13);
print_r($array);
Array
Output: ( [0] => 1
[1] => 1
[2] => 1
[3] => 13
[4] => 1
[8] => 1
[9] => 19
)
Type of indices may vary within
the same array
<?php
$arr = array(“candy" => "bar", 12 => true);
echo $arr[“candy"]; // bar
echo $arr[12]; // 1
?>
Note: Attempting to access an array key which has not been defined is the same as
accessing any other undefined variable: an E_NOTICE-level error message will be
issued, and the result will be NULL.
Auto-indexing
<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);
// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
Printing Array Elements
<?php
$array = array(5=>43, 32, 56, "b"=> 12);
print("\$array[\"b\"]=");
echo $array["b"];
print "<br>";
print("\$array[\"b\"]= $array['b']");
print("\$array[\"b\"]= {$array['b']}");
print("\$array[\"b\"]= {$array[“b”]}");
print("\$array[\"b\"]= $array["b"]");
?>
Output of the correct statements: $array["b"]=12
More Print Examples
<?php
print "<br>";
print("Hello World<br>");
print "Hello World<br>"; //print() also works without parentheses
$number=7;
print $number; //you can just print variables without double quotes
print '<br>$number'; //this will print the variable name.
?>
Output: Hello World
Hello World
7
$number
Extending & Modifying Arrays
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
int array_unshift()
array_unshift
Prepend one or more elements to the beginning of an array
Note that the list of elements is prepended as a whole, so that the prepended elements stay in
the same order. All numerical array keys will be modified to start counting from zero while literal
keys won't be touched.
-returns the new number of elements.
<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>
Array (
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)
int array_push()
Push one or more elements onto the end of array.
Returns the new number of elements
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
mixed array_pop()
pops and returns the last value of the array, shortening the array by one
element. If array is empty (or is not an array), NULL will be returned. Will
additionally produce a Warning when called on a non-array.
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>
Array
(
[0] => orange
[1] => banana
[2] => apple
)
Iterating through Arrays
foreach (array_expression as $value) {
statement
}
Example: • Loops over the array given
<html> by array_expression.
<body> • On each loop, the value of the
<?php current element is assigned
to $value and the internal array
$x=array(“red",“green",“blue"); pointer is advanced by one (so on the
foreach ($x as $value) { next loop, you'll be looking at the next
element).
echo $value . "<br />"; • Note: acts on a copy of the array
}
Output:
?>
red
</body> green
</html> blue
Iterating through Arrays
foreach (array_expression as $key => $value)
statement
Example: • Loops over the array given
<html> by array_expression.
<body>
<?php • On each loop, the current element’s
$numbers = array("one"=>"une", "two"=>"deux", key is assigned to the variable $key.
"three"=>"trois", "four"=>"quatre", "five"=>"cinq");
• Note: acts on a copy of the array
foreach($numbers as $key=>$val) {
print "English: " . $key . ", French " . $val . "<br/>";
}
Output:
?> English: one, French une
</body>
English: two, French deux
</html> English: three, French trois
English: four, French quatre
English: five, French cinq
PHP Control Structures
• if, else, switch … case …, break, continue
– Similar to C, but must use brackets {} always
• elseif
– Different syntax to C, same semantics
• While loop …, do … while loop, for loop…
– All similar to C
PHP Control Structures
switch(expression){
case $Example: //variable name
statements;
break;
case “text”:
//…
case 75:
//…
case -123.45:
//…
default:
//…
}
PHP Control Structures
<?php <?php
$t = 14; $a = 200;
$b = 33;
if ($t < 20) { $c = 500;
echo "Have a good day!";
} if ($a > $b && $a < $c ) {
?> echo "Both conditions are true";
}
?>
<?php
$a = 5;
if ($a == 2 || $a == 3 || $a == 4 || $a == 5 || $a == 6 || $a == 7) {
echo "$a is a number between 2 and 7";
}
?>
PHP Control Structures
<?php <?php
$t = date("H"); $t = date("H");
echo "<p>The hour (of the server) is " . $t;
if ($t < "20") { echo ", and will give the following
echo "Have a good day!"; message:</p>";
} else {
echo "Have a good night!"; $t = date("H");
} if ($t < "10") {
?> echo "Have a good
morning!"; } elseif ($t < "20")
{
echo "Have a good day!"; }
else {
echo "Have a good night!"; }
?>
PHP Control Structures
<?php
<?php
<?php
$a = 13;
$a = 13; if ($a > 10) {
echo "Above 10";
$b = $a < 10 ? "Hello" : "Good Bye"; if ($a > 20) {
echo " and also above 20";
echo $b; } else {
?> echo " but not above 20";
}
}
?>
PHP Functions
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>
PHP Function Arguments
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
PHP Function Arguments
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
PHP Default Argument
Value
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of
50 setHeight(135);
setHeight(80);
Output:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
PHP Functions - Returning
values
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
Output:
5 + 10 = 15
7 + 13 = 20
2+4=6
Passing Arguments by
Reference
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
Output:
7
Variable Number of
Arguments
<?php
function sumMyNumbers(...$x) {
$n = 0;
$len = count($x);
for($i = 0; $i < $len; $i++) {
$n += $x[$i];
}
return $n;
}
$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a; Output:
?> 29
Summary
• PHP runs in the web server
• The server creates HTML dynamically
• It is more efficient than using CGIs
• Variables
• Arrays
• Control structures
• Functions