Server Side Scripting –
PHP
Web Server
• A web server is a computer that runs websites.
• The basic objective of the web server is to store,
process and deliver web pages to the users.
• When users enter a URL address, such as
www.google.com, into a web browser, they’re
requesting a specific document from the web server.
Web Server ……
• Eg: Apache Tomcat , IIS
Lamp stack
• LAMP stack in Linux is used for creating a powerful web
server environment.
• LAMP stands for Linux, Apache web server, MySQL, and
PHP, and together they provide a robust platform for
developing and deploying web applications.
Server Side Scripting
• Server-side scripts provide an interface
to the user and limit access to
proprietary data.
•
• Examples of scripting languages are :
– PHP
– ASP.NET (C# OR Visual Basic)
– C++
– Java and JSP
– Python
– Ruby on Rails and so on.
PHP
• PHP stands for Hypertext Preprocessor
• PHP is a server-side scripting language.
• Scripts are embedded into static HTML files
• PHP supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC,
etc.)
• PHP is an open source software
• PHP is free to download and use
How a PHP script is embedded in a
webpage and executed
• A PHP scripting block always starts with <?php and ends with
?>
• A PHP scripting block can be placed anywhere in the
document.
• A PHP file normally contains HTML tags, just like an HTML
file, and some PHP scripting code.
• The file must have a .php extension to execute
sample.php
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Comments in PHP
• In PHP,
– Use // to make a single-line comment.
– /* and */ to make a large comment block
Variables in PHP
• All variables in PHP start with a $ sign symbol.
• The correct way of declaring a variable in PHP as
$var_name = value;
Eg:
$color = "red";
PHP Operators
• Operators are used to perform operations on variables and
values.
• PHP divides the operators in the following groups:
– Arithmetic operators
– Assignment operators
– Comparison operators
– Increment/Decrement operators
– Logical operators
– String operators
– Array operators
– Conditional assignment operators
a) Arithmetic Operators
Program: Sum of two variables
<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body>
</html>
b)Assignment Operators
• The basic assignment operator in PHP is "=".
Example
<html>
<body>
<?php
$x = 15;
$x% = 4;
echo $x;
?>
</body>
</html>
(c)Comparison operators
(d) Increment / Decrement Operators
e) Logical Operators
• The PHP logical operators are used to combine conditional
statements.
Example
(f) String Operators
Example
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
(g) Array Operators
PHP Conditional Statements
• In PHP we have the following conditional statements:
• if statement - executes some code if one condition is
true
• if...else statement - executes some code if a
condition is true and another code if that condition is
false
• if...elseif....else statement - executes different codes
for more than two conditions.
• switch statement - select one of many blocks of code
to be executed
The if Statement
• Use the if statement to execute some code only if a specified
condition is true.
• Syntax
if (condition) {
code to be executed if condition is true;
}
Eg:
<?php
$num = 14;
if ($num < 20) {
echo "Small No!";
}?>
The if...else Statement
• Use the if....else statement to execute some code if a condition is true and
another code if a condition is false.
• Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
The if...else if....else Statement
• It executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition
is true;
} else {
code to be executed if all conditions are false;
}
Example
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
The PHP Switch Statement
• Used to perform different actions based on different
conditions.
• Select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
…..
default:
code to be executed if n is different from both label1 and label2;
}
PHP Loops
• In PHP, supports the following looping
statements:
• while - loops through a block of code while a
specified condition is true
• do...while - loops through a block of code once,
and then repeats the loop as long as a specified
condition is true
• for - loops through a block of code a specified
number of times
• foreach - loops through a block of code for each
element in an array
The while Loop
• The while loop executes a block of code while a condition is
true.
Syntax
while (condition)
{
code to be executed;
}
Example
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
The do - while Statement
• The do...while statement will always execute the block of code once, it
will then check the condition, and repeat the loop while the condition is
true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
<?php
$i = 1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
The for Loop
• The for loop is used when you know in advance how many times the
script should run.
Syntax
for (init counter; test condition; increment)
{
code to be executed;
}
Example
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
PHP Arrays
• An array is a special variable, which can hold more than one
value at a time.
• In PHP, array() function is used to create an array.
• Types of arrays:
– Numeric array/Indexed array - An array with a numeric
index
– Associative array - An array where each ID key is
associated with a value
Numeric Arrays/Indexed Arrays
• A numeric array stores each array element with a numeric
index.
• There are two ways to create indexed arrays.
– The index can be assigned automatically (the index
starts at 0)
Eg: $car = array(“Honda", "Volvo", "BMW",
"Toyota");
– The index can be assigned manually:
Eg: $car[0]=“Honda";
$car[1]="Volvo";
$car[2]="BMW";
$car[3]="Toyota";
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
Associative Arrays
• Use keys to access array values.
• There are two ways to create an associative array:
Method 1
• In this example we use an array to assign ages to
the different persons:
$ages = array("Peter"=>32, “Ben"=>30,
"Joe"=>34);
Method 2
$ages['Peter'] = "32";
$ages[‘Ben'] = "30";
$ages['Joe'] = "34";
The foreach Loop
• The foreach loop is used to loop through arrays.
• Works only on arrays, and is used to loop through
each key/value pair in an array.
Syntax
foreach ($array as $value)
{
code to be executed;
}
• For every loop iteration, the value of the current
array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop
iteration, you'll be looking at the next array value.
Display array values
<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
print_r()
<?php
$a = array("red", "green", "blue");
print_r($a);
echo "<br>";
$b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
print_r($b);
?>
Output:
Array ( [0] => red [1] => green [2] => blue )
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
count() or sizeof() function : which returns length of an array
<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
Program to reverse an array
<?php
$array = array(1, 2, 3, 4);
$size = sizeof($array);
for($i=$size-1; $i>=0; $i--){
echo $array[$i];
}
?>
PHP Functions
• In PHP, there are more than 700 built-in functions.
• A function is a block of statements that can be used repeatedly in a
program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.
• A user-defined function start with the word function.
Syntax
function functionName()
{
code to be executed;
}
Example
<?php
function writeName()
{
echo “joan";
}
echo "My name is : ";
writeName();
?>
PHP Function Arguments
• Information can be passed to functions through arguments.
• An argument is just like a variable.
• Arguments are specified after the function name, inside the
parentheses.
Example
<?php
function Name($fname, $year) {
echo "$fname born in $year <br>";
}
Name(“Arun", "1975");
Name(“Varun", "1978");
?>
Example
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it
will return 10
?>
By adding the strict declaration, it will throw ‘Fatal Error’ , if the
data type mismatches
declare (strict_types=1);
Example
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it
will return 10
?>
By adding the strict declaration, it will throw ‘Fatal Error’ , if the
data type mismatches
declare (strict_types=1);
PHP Global Variables - Superglobals
• They are predefined variables in PHP.
• They are always accessible, regardless of scope.
• They can access from any function, class or file without
having to do anything special.
• The PHP superglobal variables are:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
PHP $GLOBALS
• They are used to access global variables from anywhere in the
PHP script (also from within functions or methods).
• PHP stores all global variables in an array called
$GLOBALS[index].
• The index holds the name of the variable.
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP $_SERVER
• It holds information about headers, paths, and script
locations.
Example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
PHP $_POST
• It collect form data after submitting an HTML form with
method="post".
• $_POST is also used to pass variables.
Example
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else { echo $name; }
}
?>
</body> </html>
PHP $_GET
• It collect form data after submitting an HTML form with
method="get".
• $_GET can also collect data sent in the URL.
Example - An HTML page that contains a hyperlink with parameters:
<html>
<body>
<a href="test.php?subject=PHP&web=nptel.com">Test $GET</a>
</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and
"web" are sent to "test_get.php", and we can then access their values in
"test_get.php" with $_GET.
test_get.php
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
PHP $_REQUEST
• It is used to collect data after submitting an HTML form.
Example
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else { echo $name; }
}
?>
</body>
</html>
PHP Form Handling
• $_GET and $_POST are used to collect form-data or retrieve
information from forms, like user input.
PHP Form Handling
Example - HTML form with two input fields and a submit
button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
When a user fills out the form and click on the submit button,
the form data is sent to a PHP file, called "welcome.php":
"welcome.php"
<html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
Output
Welcome John!
You are 28 years old.
PHP Form Validation
• PHP superglobals $_GET and $_POST are used to collect
form-data.
• An HTML form contains various input fields: (required and
optional) text fields, radio buttons, and a submit button:
The validation rules for the form above are:
Fields Validation Rules
Name Required. Must only contain letters and
whitespace
E-mail Required. Must contain a valid email address (with
@ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one
• The HTML code of the form element is :
• <form method="post" action="">
• The $_SERVER["PHP_SELF"] sends the submitted
form data to the page itself.
• The htmlspecialchars() function converts special
characters to HTML entities.