Unit 2 Introduction to Server Side Scripting Language
Unit 2 Introduction to Server Side Scripting Language
connectivity
Unit-2
Prepared by Laxman pr Pant.
Introduction to server side scripting language
• Server-side scripting: is a technique used in web development which involves
employing scripts on a web server which produces a response customized for each user's
(client's) request to the website.
• Server-side scripting is often used to provide a customized interface for the user.
• It can also be used to provide dynamic websites.
• It helps work with the back end.
• It doesn’t depend on the client.
• It runs on the web server.
• It helps provide a response to every request that comes in from the user/client.
• This is not visible to the client side of the application.
• It requires the interaction with the server for the data to be process.
• Server side scripting requires languages such as PHP, ASP.net, ColdFusion, Python, Ruby on
Rails.
Client-side Scripting
Web server
• C om pute r or c olle c tion of c omp ute rs use d to d elive r we b p a g e s a n d other content
to multiple users.
• Eg. Apache HTTP Server, Apache Tomcat,Microsoft IIS IIS
Database server
• A database server is a computer system that provides other computers with services
related to accessing a n d retrieving d a t a from a database.
• Ex. Mysql, sql,oracle etc
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is an open-source, interpreted, and object-oriented scripting
language that can be executed at the server-side
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• It is powerful enough to be at the core of the biggest blogging system
on the web (WordPress)!
Why PHP?
• Easy to learn.
• Best suited for rapid application development.
• Easy to implement.
• PHP community is big support for the programmers.
• Runs on almost every platform.
• Its free and develop dynamic web pages
• PHP is most used server side programming language.
PHP Basics Syntax
PHP script can be used any number of times in the php file.
• Integer
• Boolean
• Array
• Object
• Null
• Resource
PHP variable scope
• The scope of a variable is defined as its range in the program under which it can be
accessed
• PHP has four different variable scopes
• Local
• Global
• Static
• Parameter
Local variable:
• The variables that are declared within a function are called local variables for that function
Example:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Global variable
• The global variables are the variables that are declared outside the function
• To access the global variable within a function, use the GLOBAL keyword before the variable. However, these
variables can be directly accessed or used outside the function without any keyword.
• Example:
<?php
$x=5; //global scope
function myTest()
{
global $x;
echo $x; //global scope
}
myTest();
?>
Static variable
• When a function is completed, all of its variable are normally deleted.
• Sometimes you want a local variable not to be deleted.
• To do this, use the Static keyword when you first declare the variable.
Example:
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest()
myTest()
myTest()
?>
Parameter scope:
• A parameter is a local variable whose value is passed to the function
by the calling code.
• Parameters are declared in a parameter list as part of the function
declaration.
Example
<?php
function myTest($x)
{
echo $x;
}
myTest(5);
?>
PHP operators
• PHP operator s can be categorized in the following group.
• Arithmetic operator
• Assignment Operator
• Comparison Operator
• Increment/Decrement Operator
• Logical Operator
• String Operator
• Array Operator
Arithmetic Operators
Operator Name Example Result
x=y x=y The left operand gets set to the value of the expression on the right
x += y x=x+y Addition
x -= y x=x–y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
Comparison Operators
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the
same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not
of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater
than zero, depending on if $x is less than, equal to,
or greater than $y. Introduced in PHP 7.
Increment/decrement Operators
Operator Name Description
• If … else statement
• Switch statement
• Looping statement
• While loop
• Do…while loop
• For loop
• Foreach loop
If statement in PHP
The if statement executes some code if one condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
For Example:
<?php
$day = 18;
if ($day < "20") {
echo "Have a good day!";
}
?>
If ….else statement in PHP
The if...else statement executes some code if a condition is
true and another code if that condition is false.
Syntax:
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
For Example:
<?php
$t = date("H");
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The PHP do…while Loop
• The do...while loop - Loops through a block of code once, and
then repeats the loop as long as the specified condition is true.
• The do...while loop will always execute the block of code once,
it will then check the condition, and repeat the loop while the
specified condition is true.
Syntax:
do {
code to be executed;
} while (condition is true);
The PHP do…while Loop
Example:
<?php Output
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The PHP for Loop
• The for loop - Loops through a block of code a specified number of times.
• The for loop is used when you know in advance how many times the
script should run.
Syntax:
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
} Output
Example:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP for each Loop or foreach () array
method
• The foreach loop - Loops through a block of code for
each element in an array.
• The foreach loop works only on arrays, and is used to
loop through each key/value pair in an array.
Syntax:
forEach (function);
code to be executed;
}
The PHP foreach Loop
Example:
<?php
$colors = array("red", "green", "blue", "yellow");
• PHP multidimensional array can be represented in the form of matrix which is represented by row * column.
Syntax:
$<array_name>=array(array<elements>,array<elements>….array<elements>);
$num[0][0]=1
$num[0][1]=2
………………
$num[2][2]=9
<?php
$b=array(array(9,9,9,7,4),array(9,8,4,2,3));
echo "<pre>";
echo print_r($b);
echo"</pre>";
echo"<hr>";
for($i=0;$i<2;$i++)
for($j=0;$j<5;$j++)
echo $b[$i][$j];
echo"<br>";
?>
Exercise
• Write a PHP program to create a multidimensional array that holds the marks
of three subject like math Nepali and physics of three student
Ram,Shyam,Hari. Then display the average marks of each student.
• Write a PHP program to input 30 students marks in a subject and count the
pass student's where the pass marks is >=32
• Write a PHP program to input 10 employees salary and display the employees
salary where the salary is >=32000 by using associative array.
Exercise
Write a PHP program to create a multidimensional array that holds the marks of three subject like math Nepali and
physics of three student Ram,Shyam,Hari. Then display the total and average marks of each student.
<?php
$marks = array( "Ram" => array("math" => 85, "Nepali" => 90, "physics" => 78), "Shyam" => array("math" => 75, "Nepali" => 88,
"physics" => 92), "Hari" => array("math" => 92, "Nepali" => 78, "physics" => 85) );
$totalMarks = array_sum($subjectMarks);
?>
Function in php
• PHP function is a piece of code that can be reused many times.
• It can take input as argument list and return value.
• Syntax for defining function
<?php
function <function name>(<parameters>)
{
//statements;
}
?>
Syntax:
Function <function_name>(<parameters>)
{
//code to be executed;
//return statement;
}
Note:
• A function should start with keyword function and all the function code should be put inside { and} brace
<?php
function printName()
{
echo(“Laxman");
}
echo("My name is ");
printName();
?>
Output: My name is Laxman.
Return values
• A function call can be anywhere in the program, and it can be inside another
function too.
• A simple function that returns value when it is called:
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
Output: 1 + 16 = 17
• Note: Function will return only one value.
Function with arguments:
• Information may be passed to functions via the argument list, which is a comma-
delimited list of expressions.
<?php
function Multiply($x,$y)
{
$total=$x*$y;
echo("The Multiplication of two number=$total");
}
$a=6;$b=9;
Multiply($a,$b);
?>
Default Parameters
• Default parameters enable you to specify a default value for function
parameters that aren’t passed to the function during the function call.
• The default values you specify must be a constant value and default value can
be specified for each of the last arguments.
• To do this, simply use the assignment operator and a value for the arguments
in the function definition.
• If the value is specified then this default value is ignored and the passed value
is used instead.
Example
<?php
echo "<h3>Use of Default Parameter<br></h3>";
function increment($num, $increment = 1)
{
$num += $increment;
echo $num."<br>";
}
$num = 4;
increment($num);
increment($num, 3);
?>
Output: 5
7
Pass by value and pass by reference
• Normally, when you are passing a variable to a function , you are passing “by
value” which means the PHP processor will make a duplicate variable to work on.
• When you pass a variable to a function “by reference” you passing the actual
variable and all work done on that variable will be done directly on it.
Pass by value-Example
<?php
$a=10; $b=20;
echo "<h3>Before Swapping<br></h3>";
echo "a:".$a."b:".$b."<br>";
swap($a,$b);
echo "<h3>After Swapping<br></h3>";
echo "a:".$a."b:".$b."<br>";
function swap($no1,$no2)
{
$temp=$no1;
$no1=$no2;
$no2=$temp;
}
?>
Pass by reference-Example
<?php
$a=10; $b=20;
echo "<h3>Before Swapping<br></h3>";
echo "a:".$a."b:".$b."<br>";
swap($a,$b);
echo "<h3>After Swapping<br></h3>";
echo "a:".$a."b:".$b."<br>";
function swap(&$no1,&$no2)
{
$temp=$no1;
$no1=$no2;
$no2=$temp;
}
?>
Recursive Function
• Recursive function is a function which calls itself again and again until the termination
condition arrive.
<?php
function fact($n)
{
if ($n === 0)
{
// our base case
return 1;
}
else
{
return $n * fact($n-1); // <--calling itself.
}
}
echo fact(5);
?>
Built-in Functions in PHP
• are predefined functions in PHP
• Built in functions are functions that exist in PHP installation package.
• The built in functions can be classified into many categories
• String Functions
• Trim() :Remove whitespace or other characters from the beginning and end of the string.
• strcasecmp():It is used to compare two strings.
• Strlen() :It is used to return the length of a string.
• Strrev(): It is used to reverse a string
• Strtolower(): Convert the string in lowercase
• Strtoupper(): Convert the strings in uppercase
• ucwords(): Make the first character of each word in a string to uppercase
• explode(): It is used to break a string into an array.
• implode(): : It is used to return a string from the elements of an array
Numeric Functions
• Round(): Round off a number with decimal points to the nearest whole
number.
• The predefined $_GET variable is used to collect data in form with method =“get” information
sent from a form with the GET method is visible to everyone (it will be displayed in the browser
address bar).
• The name of form field will automatically be the keys in the $_GET arrays.
$_POST:
• The predefined $_POST variable use to collect values in a form with method =“post” information
sent from a form with POST method is invisible to others.
• The name of form field will automatically be the keys in the $_POST arrays.
• Form validation is process of checking that form has been filled in correctly
before it is processed.
Client-side validation
• Server-side validation:
• Server-side validation is done usually done using php, asp and jsp etc.
Some of Validation rules for field
•If matches are found for parenthesized substrings of pattern and the function is
called with the third argument regs, the matches will be stored in the elements of the
array regs.
1.Checking matched string using preg_match() function:
<?php
$user= "laxmanpant2054";
$password="Laxman@2054";
if(preg_match('/2054/',$user))
{
echo "<b>User Name is Correct</b>";
}
else
{
echo"<div style='color:red;'>You Enter Wrong User Name</div>";
}
?>
2.Checking validation by using preg_match() function:
<?php
$a = "Laxman2054";
if(preg_match('/^[a-zA-Z0-9]{3,18}$/', $a))
{
echo “<b>okay for login **Laxman**</b>";
}
else
{
echo "Not valid";
}
?>
3.Checking validation by using preg_match() function:
<?php
}
else
{
echo "Not valid";
}
?>
3.Checking validation by using preg_match() function:
<?php
}
else
{
echo "Not valid";
}
?>
PHP FUNCTION filter_var()
Syntax:
<?php
// Variable to check
$email = “[email protected]";
// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>web</title>
</head>
<body>
<form action="conn.php" method="post">
Full Name:<input type="text" name="n1">
<br><br>
Email:<input type="email" name="n2">
<br><br>
Password:<input type="password" name="n3">
<br><br>
<input type="submit" name="n4" value="Login">
</form>
</body>
</html>
Example: conn.php
<?php
if(isset($_POST['n4']))
{
$name=$_POST['n1'];
$email=$_POST['n2'];
$password=$_POST['n3'];
if(strlen($name)>=10)
{
echo " Max length";
}
if(preg_match('/^([a-z]+[0-9]*)@([a-z]+)\.[a-z]{2,5}$/', $email))
{
echo "The email is=$email<br>";
}
else{
echo "<div style='color:red;'> Write a correct email format</div>";
}
if(preg_match('/^[A-Za-z0-9]{8,}+$/', $password))
{
echo " Valid Password is =$password ";
}
else
{
echo "Enter max 8 above</br>";
}
}
?>
Introduction of cookies in php
• PHP cookie is a small piece of information which is stored at client
browser. It is used to recognize the user.
• Cookie is created at server side and saved to client browser.
• Each time when client sends request to the server, cookie is embedded
with request. Such way, cookie can be received at the server side.
Introduction of cookies in php cont….
• In short, cookie can be created, sent and received at server end.
• PHP setcookie() function is used to set cookie with HTTP response.
Once cookie is set, we can access it by $_COOKIE superglobal variable.
• PHP $_COOKIE superglobal variable is used to get cookie.
• Implementation of cookies as given below.
Step 1: Creating Cookies
Syntax:
• Expire: the time the cookies expires example time()+60 will create cookoe of lifetime 60 seconds.
• Path: it can be used to set the cookie path on the server. The forward slash “/” means that the cookie will be
• Secure: is optional, the default is false. It is used to determine whether the cookie is sent via https if it is set to
• Httponly: optional , when true the cookie will be made accessible only through the http protocol.
Step 2.Access or view a cookie value:
• To access a cookie value, the super global variable $_COOKIE[‘cookie_name’] can be used.
• To delete a cookie, use the setcookie () function with an expiration date in the past
Eg:
• Session is used to store and pass information from one user to another ,
• Session creates unique user id for each browser to recognize the user
$_SESSION['uid']=12345;
$_SESSION['name']=“Laxman Pant";
?>
Session_test.php
<?php
session_start();
if (isset($_SESSION['uid'])&&isset($_SESSION['name']))
echo "wellcome, ".$_SESSION['name']." you have successfully logged in.";
else
echo "you are not logged in.";
?>
Session_delete.php
<?php
session_start();
session_unset();
session_destroy();
?>
File Handling in PHP
• File handling in PHP involves opening, reading, writing, closing
and manipulating files stored on a file system. The fopen()
function is used to open a file for reading, writing, or
appending. The fwrite() function is used to write to a file, while
the fread() function is used to read from a file.
• Using file handling access, read, write, and manipulate the file
easily in php by using different predefined functions.
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist.
File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of
the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist.
File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of
the file. Creates a new file if the file doesn't exist
Opening a file in PHP
fopen():- This function is used to open a file or URL. Before Reading something form file and writing to
file ,we must be opened the file. The syntax of file open as follows:
fopen(filename,mode);
Example:
<?php
$handling=fopen("file.txt" ,"r");
if($handling)
{
echo "File is Opened";
}
Else
{
echo “Not found";
?>
Reading a file in PHP
fgets():- This function is used to read a file or URL. Before Reading something form file ,we must be opened the file. For
reading file in php, programmer can used the while loop , feof() ,fgetc(),fgets(),fread() functions.
feof():- This function is used to read the file until file finished.
The syntax of fread() as follows:
fgets(filename,mode);
Example:
<?php
$handle=fopen("handling.txt","r");
while (!feof($handle))
{
$text=fgets($handle);
echo $text."<br>";
}
?>
Writing to a file in PHP
The fwrite() writes to an open file. The function will stop at the end of the file (EOF) or when it reaches the
specified length, whichever comes first.
Syntax:
fwrite(file, string, length);
Example:
<?php
$handle=fopen("handling.txt","w");
if(fwrite($handle, “Hello hi how are you”)==FALSE)
{
echo “Could not write”
}
else
{
echo “ sucessed”
}
?>
File uploading in PHP
According to above figure: A PHP script can be used with a HTML form to allow users to
upload files to the server by using $_FILE superglobal variable. Initially files are uploaded
into a temporary directory and then relocated to a target destination by a PHP script.
The process of uploading a file follows these steps −
• The user opens the page containing a HTML form featuring a text files, a browse
button and a submit button.
• The user clicks the browse button and selects a file to upload from the local PC.
• The full path to the selected file appears in the text filed then the user clicks the
submit button.
• The selected file is sent to the temporary directory on the server.
• The PHP script that was specified as the form handler in the form's action attribute
checks that the file has arrived and then copies the file into an intended directory.
• The PHP script confirms the success to the user.
Uploading.php
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>form</title>
<style type="text/css">
body{border: 8px solid black;height: 50%;width: 70%;}
</style>
</head>
<body>
<h1>हालसालै खिचिएको फोटो अपलोड गर्नुहोस् </h1>
<form action="uploadphp.php" method="post" enctype="multipart/form-data">
<input type="file" name="image"/><br><br>
<input type="submit" value="बुझाउनुहोस"/><br>
</form>
</body>
</html>
Uploadphp.php
<?php
if(isset($_FILES['image']))
{
$file_name=$_FILES['image']['name'];
$file_size=$_FILES['image']['size'];
$file_tmp=$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
move_uploaded_file($file_tmp,"upload/".$file_name);
echo " बधाइ! तपाइको फाइल अपलोड भइसकेको छ";
}
?>
Introduction to MySQL in PHP
• MySQL is the most popular database system used with PHP.
• MySQL is a database system used on the web
• MySQL is a database system that runs on a server
• MySQL is ideal for both small and large applications
• MySQL is very fast, reliable, and easy to use
• MySQL uses standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use
• MySQL is developed, distributed, and supported by Oracle Corporation
• MySQL is named after co-founder Monty Widenius's daughter: My
• The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.
Database and MySQL
• Database give us an easy way to issue commands to insert select, organize and
remove data.
MySQL:
• Open source database , relatively easy to set up, easy to use with php.
• MySQL AB. Was a software company that was founded in 1995, where MySQL
was developed.
• It was acquired by sun Microsystem in 2008
• MySQL database server can contain many databases, each of which can contain many tables.
• Connecting to MySQL via php includes following steps.
– Connect to MySQL
– MySQLi (procedural)
– PDO
1.Connect to MySQL:
Syntax:
Syntax:
mysqli_select_db($conn, dbname);
Syntax:
$result=mysqli_query($con,$sql);
5. Retrieve the result and handle them
mysqli_fetch_array() :Return the rows from the number of records available in the database as an
associative array or numeric array
mysqli_fetch_assoc() :return the rows from the number of records available in the database as an associative
array.
Syntax:
mysqli_close($con);
• This is a very important function as it closes the connection to the
database server.
• Your script will still run if you do not include this function.
• And too many open MySQL connections can cause problems for your
account.
• This is a good practice to close the MySQL connection once all the
queries are executed.
Example for connection to MySQL with PHP
<?php
$con=mysqli_connect("localhost","root",""); //Step 1. connect to mysql.
$dbs=mysqli_select_db($con,"college"); //Step 2. select database.
$dbs=mysqli_select_db($con,"college");
$result=mysqli_query($con,$sql);
if ($result)
echo "Insert successfully";
else
echo "Error in Insert";
mysqli_close($con);
?>
Example: Delete Data From database(delete.php)
<?php
$con=mysqli_connect("localhost","root","");
$dbs=mysqli_select_db($con,"college");
$result=mysqli_query($con,$sql);
if ($result)
echo "1 row deleted successfully";
else
echo "Error in delete";
mysqli_close($con);
?>
Example: Update Data in database(update.php)
<?php
$con=mysqli_connect("localhost","root","");
$dbs=mysqli_select_db($con,"college");
$result=mysqli_query($con,$sql);
if ($result)
echo "1 row updated successfully";
else
echo "Error in update";
mysqli_close($con);
?>
Insert Multiple Records Into MySQL
$dbs=mysqli_select_db($con,"college");
$result=mysqli_multi_query($con,$sql);
if ($result)
echo "multiple data inserted successfully";
else
echo "Error in multiple insertion";
mysqli_close($con);
?>
Form Handling in MySQL
Q.N.1. Create a following given Form and make a database connection by using any scripting language.
//clientside.php
<!DOCTYPE html>
<html>
<head>
<title>web</title>
<style>
fieldset{heigt: 50%; width: 30%;}
</style>
</head>
<body>
<fieldset>
<legend><strong>Register</strong></legend>
<form action="conn.php" method="post">
*requiredfields<br>
Your Full Name*:<br>
<input type="text" name="n1" required>
<br><br>
Email Address*:<br>
<input type="email" name="n2" required>
<br><br>
User Name*:<br>
<input type="text" name="n3" required>
<br><br>
Password*:<br>
<input type="text" name="n4" required><br><br>
<input type="submit" name="n5" value="Submit">
</form>
</fieldset>
</body>
</html>
//conn1.php
<?php
if(isset($_POST['n5']))
{
$name=$_POST['n1'];
$email=$_POST['n2'];
$user=$_POST['n3'];
$password=$_POST['n4'];
$host="localhost";
$servername="root";
$serverpassword="";
$dbname="System";
$conn=mysqli_connect($host,$servername,$serverpassword,$dbname);
if($conn)
{
$sql="insert into Record(Full_Name,Email,User_Name,Password)values('$name',
'$email','$user','$password')";
$result=mysqli_query($conn,$sql);
if($result)
{
echo "Inserted Sucessifully";
}
}
else
{
die(mysqli_error($conn));
}
mysqli_close($conn);