Server-Side Scripting (PHP) : Let Us Learn
Server-Side Scripting (PHP) : Let Us Learn
60
Do you know?
Popular PHP Frameworks
1. Laravel : It is used to build robust
web application with MVC support.
It simplifies task such as caching, Fig 5.2: first.php in server directory
security, authentication and many
4. Go to browser and type
more.
"http://localhost/balbharati/"inURL
2. Symfony : It is used for fast app
bar. Click on 'first.php'.
development due to reusable
components. It provides many
app building blocks like Form
management etc..
61
Output 5.2: has a GLOBAL SCOPE and can only be
accessed outside a function (variable $a).
And a variable declared within a function
has a LOCAL SCOPE and can only be
accessed within that function (variable
$b).
Note : In above example, HTML tag Program 5.3:
<br> is enclosed in echo output string.
<?php
$a = 20;
PHP Variables :
$c = 15;
Variable is a symbol or name that function myFunction(){
stands for a value. Variables are used for $b = 10;
storing values such as numeric values, global $c;
characters, character strings, or memory echo "<p> value of 'a' inside function
addresses, so that they can be used in any is : $a </p>";
part of the program. echo "<p> value of 'b' inside function
Rules for declaring PHP Variable : is : $b </p>";
• A variable starts with the $ sign, echo "<p> value of 'c' inside function
followed by the name of the variable is : $c </p>";
}
• A variable name must start with a
letter or the underscore character
myFunction();
• A variable name cannot start with a echo "<p> value of 'a' outside function
number is : $a </p>";
• A variable name can only contain echo "<p> value of 'b' outside function
alpha-numeric characters and is : $b </p>";
underscores (A-z, 0-9, and _ ) ?>
• Variable names are case-sensitive Output 5.3:
($age and $AGE are two different
variables)
There are three different variable
scopes in PHP:
• local
• global
• static We can access a global variable $c
A variable declared outside a function from within a function using
62
"global"keyword before the variables e.g. : One can check the data-type of
(inside the function). variable using var_dump() method in
PHP.
Note : PHP also stores all global
variables in an array called Program 5.5:
$GLOBALS[index]. The index holds <?php
the name of the variable echo "<br> -- String --<br>";
$x = "Hello World !";
When a function is executed, then all echo var_dump($x);
of its variables are deleted. In some cases, echo "<br> -- Decimal --<br>";
if we want a local variable not to be $x = "1234";
deleted then the use of "static"keyword is echo var_dump($x);
must. ?>
Program 5.4: Output 5.5:
<?php
function myCount(){
static $c = 0; // Static Keyword
echo $c;
$c++; var_dump() gives different output for
} each type of data type. It gives the length
echo "Output of myCount() with use of of string for 'string' data type, it gives
'static' keyword : <br>"; actual digit for 'integer' data type and
myCount(); true/false for 'boolean' data type.
echo "<br>";
myCount(); 5.4.5 Comments in PHP
echo "<br>"; Comments are the statements in PHP
myCount(); code, which are not visible in the output
?> of the program. It is ignored during
execution. A Single-line comment is
Output 5.4:
possible if one adds // or # before a
statement in PHP. A multi-line comment
is possible with /* and */ .
63
Control structures in PHP : 3. Loop Structure in PHP : Loops are
1. If statement in PHP : if statement used to execute the same block of
allows programmer to make decision, code repeatedly as long as a certain
based on one or more conditions; and condition is satisfied.
execute a piece of code conditionally. For eg : 'For loop' in PHP
Syntax : Syntax :
if(condition) for(initialisation;condition;incrementation
{ or decrementation)
block of statement;
{
}
Statement;
2. If-else statement in PHP : if-else }
statement allows programmer to
Program 5.7:
make decision based on either this or
that conditions. <?php
for($i=1;$i<=5;$i++)
Syntax :
{
if(condition)
echo"The number is".$i."<br>";
{
}
Statement;
?>
}
else Output 5.7:
{
Statement; The number is:1
} The number is:2
Program 5.6: The number is:3
The number is:4
<?php
The number is:5
$marks=80;
if($marks>=60) Use of foreach loop : This loop works
{ echo"you passed with first class"; only on arrays, and is used to loop through
} each key/value pair in an array.
else
Syntax :
{ echo"you can do better";
foreach ($array as $value) {
}
code to be executed;
?>
}
Output 5.6:
Note : Use of '.' in PHP. It is used for
you passed with first class concatenation purpose.
64
Following are the few predefined functions in PHP to manipulate string.
Function Description
strlen() Returns the length of a string (i.e. total no. of characters)
str_word_count() Counts the number of words in a string
strrev() Reverses a string
strpos() Searches for a specific text within a string and returns the character
position of the first match and if no match is found, then it will
return false
str_replace() Replaces some characters with some other characters in a string
substr() Returns a part of a string
strtolower() Converts a string to lowercase
substr_count() Counts the number of times a substring occurs in a string
ucwords() Converts the first character of each word in a string to uppercase
trim() Removes whitespace and other predefined characters from both
sides of a string
Table 5.1: Pre-defined functions for string manipulation.
Example : The program below shows few string manipulation functions.
Program 5.8:
5.5 PHP String Functions
<?php
A string is series of characters. The
$str="Textbooks produced by Balbharati
real power of PHP comes from its are also published in pdf format. ";
functions. A function is a block of echo "<br>String: ".$str;
statements that can be used repeatedly in echo "<br>";
a program. PHP has many built-in echo "<br>String Length : ".strlen($str);
functions that can be called directly to echo "<br>";
perform a specific task. echo "<br>String Word Count
: ".str_word_count($str);
echo "<br>";
Output 5.8: echo "<br>Reverse String : ".
strrev($str);
echo "<br>";
echo "<br>Retrun position of string
search : ".strpos($str,"Balbharati");
echo "<br>";
echo "<br>Replace string :
".str_replace("Balbharati","State
Board",$str);
?>
65
5.6 PHP Arrays In above example, we store subject in
An array is a special variable, which an array at following index location.
can hold more than one value at a time. $subjects[0] = "English";
An array stores multiple values in one $subjects[1] = "Hindi";
single variable:
$subjects[2] = "Marathi";
Create an Array in PHP :
The count() function is used to return
In PHP, the array() function is used to the length of an array:
create an array.
Syntax : Note : An array can hold many values
$a = array( values ) under a single name, and you can
access the values by referring to an
index number.
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a PHP Associative Arrays :
numeric index Associative arrays are arrays that use
Associative arrays - Arrays with named keys instead of index to identify
named keys record/value. Let us see how to create
Multi-dimensional arrays - Arrays associative array.
containing one or more arrays Syntax :
Indexed arrays : $a = array( key1 => value1, key2
=>value2, ...,key n => value n)
The index can be assigned automatically
(index always starts at 0). Program 5.10:
Syntax : <?php
$a = array( value1, value2, ..., value n) $student_mark =
array("English"=>"75",
Program 5.9: "Hindi" =>"64",
<?php "Marathi"=>"88");
$subjects = array("English", "Hindi", echo "You have scored ".$student_
"Marathi"); mark['English']." in English .";
echo "I like ".$subjects[0].", ?>
".$subjects[1]." and ".$subjects[2];
echo "<br> Count : ".count($subjects); Output 5.10:
?>
Output 5.9:
In above example, the values of
‘student_mark’ array are stored in
following way:
66
$student_mark['English'] = "75" functions, we can always create our own
$student_mark['Hindi'] = "64" functions. A user-defined function
declaration starts with the word function.
$student_mark['Marathi'] = "88"
Syntax :
Instead of index location, we can function functionName() {
refer values with the help of keys. Here code to be executed;
'English' refers to a key & value is '75'. }
"=>" is used to associate key & value.
Note : A function name can start with a
PHP Multi-dimensional Arrays :
letter or underscore (not a number).
A multidimensional array is an Function names are NOT case-
array containing one or more arrays. PHP sensitive.
can handle multiple levels of
multidimensional array. Program 5.12:
Use of foreach loop in an array <?php
function writeMsg(){
Program 5.11: echo "This is user-defined function";
<?php }
$subjects = array("English","Hindi", writeMsg(); //call the function
"Marathi"); ?>
foreach ($subjects as $value) {
Output 5.12:
echo "$value <br>";
} This is user-defined function
?>
PHP Function Arguments :
Output 5.11: 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. The following example has
In above example we have used a function with arguments ($rollno and
'foreach' loop where for every loop $name):
iteration, the value of the current array
Program 5.13:
element is assigned to '$value' and the
array pointer is moved by one, until it <?php
reaches the last array element. function Student($rollno, $name){
echo "Roll No is $rollno and Name is
5.7 PHP User Defined Functions $name <br>";
A function is a block of statements }
that can be used repeatedly in a program. Student(1,"Ashwini");
It will not execute immediately when a Student(2,"Raj");
page loads but will be executed by a call Student(3,"Sonam");
to the function. Along with built-in PHP ?>
67
Output 5.13: Program 5.15.1:
<html>
<body>
<form action="welcome.php"
method="post">
Name: <input type="text"
Note : String is written in double name="name"><br>
quotes. E-mail: <input type="text"
name="email"><br>
<input type="submit">
Returning Value : </form>
</body>
To let a function return a value, use
</html>
the return statement:
Output 5.15.1:
Program 5.14:
<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z; When the user fills out the form above
} and clicks the submit button, the form
echo "5 + 10 = " . sum(5, 10) . "<br>"; data is sent for processing to a PHP file
echo "7 + 13 = " . sum(7, 13) . "<br>"; named "welcome.php". The form data is
echo "2 + 4 = " . sum(2, 4); sent with the HTTP POST method.
?> The code for "welcome.php" looks
like this:
Output 5.14: Program 5.15.2:
5 + 10 = 15 <html>
7 + 13 = 20 <body>
2+4=6 Welcome
<?php echo $_POST["name"]; ?> <br>
Your email address is:
<?php echo $_POST["email"]; ?>
5. 8 PHP Form Handling
</body>
A simple HTML form with two input </html>
fields and a submit button:
Output 5.15.2:
Welcome balbharti Your email address
is: balbharti@balbharati.in
68
$_POST["email"] helps us to get the bmioutput.php
data of form field whose name attribute Program 5.16.2:
is email. And the output is displayed as
shown in output 5.15.2. <?php
$height = $_GET["height"];
Lets understand another example with $weight = $_GET["weight"];
HTTP GET method. $heightInMs = $height/100;
$bmi = $weight/
Program 5.16.1: ($heightInMs*$heightInMs);
<html>
<head> if($bmi < 18.5)
<title>BMI Calculator</title> {
$message = "You are underweight.";
</head>
}
<body>
else if($bmi >=18.5 && $bmi <= 24.9)
<form method="get"
{
action="bmioutput.php">
$message = "Congrats!!! You have
normal weight.";
Weight (kg): <input name="weight" }
id="weight" type="text" /> <br/> else if($bmi >24.9 && $bmi <=29.9)
Height (cm): <input name="height" {
id="height" type="text" /> <br/> $message = "You are overweight.";
}
<input name="submit" id="submit" else
value="Calculate" type="submit" /> {
$message = "Be careful!!! You are
obese.";
</form>
}
</body>
</html>
echo $message;
echo "</br> BMI : ".$bmi;
Output 5.16.1: ?>
Output 5.16.2:
69
The PHP superglobals $_GET and When to use POST?
$_POST are used to collect form-data.
Information sent from a form with the
The same result could also be achieved POST method is invisible to everyone
using the HTTP GET method. Just replace (all names/values are embedded
POST with GET. Let us understand the within the body of the HTTP request).
difference between GET and POST
Method. POST has no limits on the amount of
information to send.
GET vs POST :
Moreover POST supports advanced
Both GET and POST are treated as functionality such as support for
$_GET and $_POST superglobals, which multi-part binary input while
means that they are always accessible, uploading files to server.
regardless of scope. It can be accessed
from any function, class or file without The variables are not displayed in the
having to do anything special. URL so it is not possible to bookmark
the page.
$_GET is an array of variables passed
via the URL parameters. Form connectivity with Database :
$_POST is an array of variables
passed via the HTTP POST method.
Note : Ensure you have configured
When to use GET? 'php.ini' file before PHP & Database
connectivity.
Information sent from a form with the
GET method is visible to everyone
(all variable names and values are Example : Create an admission form for
displayed in the URL). the registration of the college student. We
have already studied HTML form
GET also has limits on the amount of
creation in previous chapter and database
information to send. However,
creation in DBMS chapter. Now
because the variables are displayed in
create"college"database and create
the URL, it is possible to bookmark
table"student"with following fields in
the page. This can be useful in some
this Postgres SQL database.
cases.
Name gender
GET may be used for sending non-
sensitive data. Now write following code in ‘admission.
GET should NEVER be used for php’ file.
sending passwords or other sensitive
information!
70
Program 5.17:
<!DOCTYPE html>
<head lang="en">
<title>Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1> Student Admission Form</h1>
<form method="post" >
<label> First Name </label>
<input type="text" name="name" id="id_name" maxlength="30" required
placeholder="Enter your Name" />
</br>
<label> Gender </label>
<input type="radio" name="gender" id="id_gender" value="male"> Male
<input type="radio" name="gender" id="id_gender" value="female"> Female
<input type="radio" name="gender" id="id_gender" value="other"> Other
</br>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
<?php
$servername = "pgsql:host=localhost;dbname=college";
$username = "postgres";
$password = "postgres";
$conn = new PDO($servername,$username , $password);
if(isset($_POST['submit']))
{
$name=$_POST["name"];
$gender=$_POST["gender"];
$sql = "INSERT INTO student (name, gender) VALUES ('".$name."', '".$gender."')";
$conn->exec($sql);
echo "New record created successfully";
}
?>
71
Output 5.17: string to insert values in the table named
‘student’.
$conn -> exec($sql);
In the above statement ‘->’ is used to
execute SQL statement using $conn as
connectivity object.
In above example, PHP Data Object Note : isset() method in PHP is used to
class, i.e. PDO(), helps us to connect PHP check whether variable has value or
code with almost any database server. It not, this help us to know if the button is
doesn't account for database-specific clicked or not.
syntax, and one can switch database
The above program is used to insert
simply by switching the connection string
data from the user into the database. Now
in many instances. It provides database
let us understand how to fetch the data
access layer providing a uniform method from database and display as a webpage.
of access to multiple databases. The next program uses PDO exception.
1) Create database connection object PDO exceptions are used to handle errors,
which means anything you do with PDO
$conn = new should be wrapped in a try/catch block.
PDO($servername,$username, The part of code which may be erroneous
$password); can be put in try{ } block and the code to
In our example, we connect PHP with handle the error can be place in catch{ }
PostgreSQL server. The above statement block.
creates connectivity object ‘$conn’ with PDO exception class is used to throw
three parameters as shown below: errors due to database connectivity. ‘$e’
is the object of PDO and using
1. Server host name or IP address and getMessage(), we can print the error
Database name message for database connectivity.
2. Database username prepare($sql) is the secure way to execute
SQL queries using any programming
3. Database password language whereas fetchAll() method is
2) SQL statement and its execution used to get all the records from the given
table and store in $result variable.
$sql = "INSERT INTO student
$conn -> null is to close the database
(name, gender) VALUES connectivity object.
('".$name."', Note : For datatbase connectivity you
'".$gender."')"; may use any other database such as
The above statement creates SQL mysql, .maliadb etc.
72
Program 5.18: Output 5.18 :
<!doctype html>
<html> <body>
<h1>Display data</h1>
<?php
$servername = "pgsql:host=localhost;
dbname=college";
$username = "postgres";
$password = "postgres";
try Cookies and session in PHP :
{
$conn = new Cookies :
PDO($servername,$username , A cookie is a small text file that the
$password);
server sends on the user's computer. It is
}
catch (PDOException $e) used to identify user or its machine and
{ track activities created on the user
echo "connection error". computer. When browser requests server
$e->getMessage(); page, cookies are sent along with the
} request. PHP can be used both to create
try and retrieve cookie values.
{
$sql1 = "select * from student"; Eg. Cookies store visited page on browser
$sqlp=$conn->prepare($sql1); to optimise search.
$sqlp->execute();
Session :
$result=$sqlp->fetchAll();
echo "Name -- Gender"; This is used to store user information
foreach($result as $row) on server to track user activites. It helps
{ web application to maintain user
echo $row["name"]."--"; information on all the pages.
echo $row["gender"]." ";
echo "</br>"; Eg. If you login to gmail account, the
} session help us to access youtube account
} also.
catch (PDOException $e) Note : For database connection use
{ username and password values which
echo "connection error".
you have given at the time of postgres
$e->getMessage();
installation.
}
$conn=null; Program 5.17 and 5.18 uses username
?> as 'postgres' and password as 'postgres'
</body></html> while programming.
73
Summary
74
For information purpose only
Exercise
77
Q3. Multiple Choice Question. 2. The scope of variable can be
(1 correct) ______________.
1. The program file of PHP have a) local b) global
____________ extension. c) universal d) static
a) .asp b) .php e) final f) outside
c) .js d) .txt
Q6. Brief Questions.
2. A variable declared ________ a
1) Explain any two features of PHP?
function has global scope.
a) outside b) anywhere 2) What are the rules to declare
c) inside d) none variable in PHP?