[go: up one dir, main page]

0% found this document useful (0 votes)
28 views20 pages

Server-Side Scripting (PHP) : Let Us Learn

The document provides an overview of PHP, a widely-used open-source server-side scripting language suitable for web development. It covers PHP features, variables, data types, arrays, string functions, and control structures, as well as how to execute PHP programs. Additionally, it discusses the importance of PHP's simplicity, speed, and compatibility with various platforms and databases.

Uploaded by

rajkamble30659
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views20 pages

Server-Side Scripting (PHP) : Let Us Learn

The document provides an overview of PHP, a widely-used open-source server-side scripting language suitable for web development. It covers PHP features, variables, data types, arrays, string functions, and control structures, as well as how to execute PHP programs. Additionally, it discusses the importance of PHP's simplicity, speed, and compatibility with various platforms and databases.

Uploaded by

rajkamble30659
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

5 Server-Side Scripting (PHP)

Let us learn programs and is shared by the clients.


The server-side environment that runs a
 Features of PHP scripting language is termed web server.
 PHP variables, datatypes A user's request is fulfilled by running a
 PHP Array, String function and user- script directly on the web server to
defined functions generate dynamic HTML pages. This
HTML is then sent to the client browser.
 PHP form handling
It is usually used to provide interactive
 PHP connectivity with database web sites that interfaces with databases
server or other data stores on the server.
5.1 Introduction to PHP Few Programming languages for
server-side programming are :
PHP (Hypertext Preprocessor) is a
widely-used open source general-purpose 1) PHP
scripting language. It is especially suited 2) Java and JSP
for web development and can be 3) Python
embedded into HTML.
PHP mainly focuses on server-side
 PHP runs on various platforms (Linux,
scripting, which is used to collect form
Unix, Mac OS X, Windows etc.).
data, generate dynamic page content, or
 PHP is compatible with almost all send and receive cookies. There are three
servers used today (For eg. XAMMP, things to make this work : the PHP parser
Apache, NGINX, lighttpd). a web server and a web browser. You
 PHP supports a wide range of need to run the web server, with a
databases. connected PHP installation. You can
access the PHP program output with a
 PHP is free and one can download it
web browser, viewing the PHP page
from the official PHP resource: www.
through the server. Note : PHP hides the
php.net.
code from the user.
 PHP is easy to learn and runs
efficiently on the server side. 5.3 Features of PHP
PHP is most popular and frequently
5.2 Server Side Scripting
used world wide server-side scripting
A server is a computer system that language and the main reason of
serves as a central repository of data and popularity is :
59
 Simple : It is very simple and easy to we can do things like adding a string
use, as compared to other scripting to an integer without causing an error.
languages. 5.4 First sample code of PHP
 Interpreted : It is an interpreted A PHP file normally contains HTML
language, i.e. there is no need for tags, and some PHP scripting code. The
compilation. PHP code is usually enclosed in special
start and end processing instructions
 Faster : It is faster than other scripting
<?php and ?> that allow us to move into
language e.g. JSP and ASP.
and out of "PHP mode." Even it allows to
 Open Source : Open source means embed HTML code within PHP code.
you need not pay for use of PHP. You All the PHP files have extension ".php".
can freely download and use. A PHP script can be placed anywhere in
 Platform Independent : PHP code the html document. For e.g. : PHP
will be run on every platform, Linux, program to display the text "Hello
Unix, Mac OS X, Windows. World!" on a web page. Note that 'echo'
is used to display text on web page.
 Case Sensitive : PHP is case sensitive
scripting language while declaration Program 5.1:
of variables and its use in the program. <!DOCTYPE html>
In PHP, all keywords (e.g. if, else, <html>
while, echo, etc.) classes, functions, <body>
and user-defined functions are NOT <h1>My First PHP Page</h1>
case-sensitive. <?php
echo "Hello World!";
 Error Reporting : PHP have some ?>
predefined error reporting constants </body>
to generate a warning or error notice. </html>
 Real-Time Access Monitoring : PHP
provides access logging by creating Output 5.1:
the summary of recent accesses for
the user.
 Loosely Typed Language : PHP
supports variable usage without
declaring its data type. It will be taken
at the time of execution Based on the
type, data has its value. Since the Note : The PHP code is embedded with
data types are not set in a strict sense, HTML tags using <?php and ?>.

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..

How to execute PHP program :

1. Type the above program and save it


Fig 5.3: List of files on server directory
as"first.php"using any text editor (for
e.g. notepad, gedit).

2. Create folder with your name in /var/


www/html. (for e.g. balbharati)
Fig 5.4 : Output of first.php program

Note : Create folder in servers root


PHP Case Sensitivity :
directory. In case of Linux the path of
root directory is var/www/html. In case In PHP, the variable names are case
of windows the path is C:/XAMPP/ sensitive. However keywords (e.g.
htdocs. if, else, break, for, while, echo etc.),
function and class names are
case insensitive.
For e.g. : The echo keyword is case
insensitive in the program 5.2.
Program 5.2:

Fig 5.1: Folder created on web server <?php


ECHO "Hello World!<br>";
3. Save the 'first.php' file in balbharati echo "Hello World!<br>";
folder. EcHO "Hello World!<br>";
?>

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 */ .

PHP Data Types: Note :


Variables can store data of different 1) PHP Operators are similar to
types and PHP supports the following JavaScript Operators.
data types : 2) Accepting value from the user at
1) String 2) Integer 3) Float 4) Boolean runtime is possible through HTML
5) Array 6) NULL Form and is covered in section 5.8

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:

Once you click on 'Calculate' button,


the output is displayed as shown above.

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

 PHP is widely-used open source server-side programming language which runs


on various platforms.
 PHP is a script executed on server which generate dynamic HTML pages.
 The PHP code can also be embedded with HTML tags using <?php and ?>.
 PHP is case sensitive only at time of variable declaration and not-case sensitive
for other keywords.
 PHP variable start with $ sign followed by name of variable which must start
with a alpha-numeric characters or underscore character.
 PHP variable has three different scopes namely : local, global and static.
 PHP supports String, Integer, Float, Boolean, Array and NULL data types.
 Three types of Arrays are Indexed array, Associative array and Multi-dimensional
array.
 PHP supports ‘foreach’ loop to iterate easily.
 String functions are used to manipulate strings.
 A function is a block of statements that can be used repeatedly in a program.
 Information can be passed to functions through arguments.
 Form is used to collect information from user and process or store in database.
 Form data can be submitted by GET or POST method.
 The PHP superglobals $_GET and $_POST are used to collect form-data.
 $_GET is an array of variables passed via the URL parameters and are visible to
everyone.
 $_POST is an array of variables passed via the HTTP POST method and are
invisible to others.
 GET has limits on the amount of information to send whereas POST has no limits
on the amount of information to send.
 GET should NEVER be used for sending sensitive information.
 PDO- PHP Data Object helps us to connect PHP code in uniform method of access
to multiple databases.
 Cookies are sent along when browser requests server pages.
 Session helps web application to maintain user information on all the pages.

74
For information purpose only

PHP LAMP Install


How To Install Apache, PHP and php-pgsqlstack on Ubuntu 18.04
A "LAMP" stack is a group of open-source software that is typically installed
together to enable a server to host dynamic websites and web apps. His term is actually
an acronym which represents the Linux operating system, with the Apache web server.
The site data is stored in a MySQL database, and dynamic content is processed by
PHP.
Open Terminal and type following commands
Step 1 : Installing Apache
$ sudo apt update
$ sudo apt install apache2
To verify the installation, type following statement in the browser address bar.
http://your_server_ip or http://localhost/
If you get following page, its installed succesfully.

Step 2 : Installing connector for php-pgsql


$ sudo apt install php-pgsql
This command, too, will show you a list of the packages that will be installed,
along with the amount of disk space they'll take up. Enter Y to continue.
Step 3 : Installing PHP
$ sudo apt install php libapache2-mod-php
After this, restart the Apache web server in order for your changes to be recognized.
Do this by typing:
75
$sudo systemctl restart apache2
Step 4 : Testing PHP Processing on your Web Server
In order to verify PHP installation, you create a very basic PHP script called myde-
mo.php.
Now go to /var/www/html/. Create the file at that location. The file should contain
following statement.
File Name : mydemo.php
<?php
echo"Hurray !!! First PHP Program is working";
?>
Now go to browser and type following line in the address bar.
http://your_server_ip/mydemo.php or http://localhost/mydemo.php
Step 5 : To configure Apache server for postgresql
For Ubuntu
Open 'php.ini' file located at /etc/php/x.x/apache2/php.ini and add the line below at
the end of file.
extension=pgsql.so
How To Install XAMPP on Window
Step 1 : Download and install XAMPP from https://www.apachefriends.org/down-
load.html
Step 2 : Testing PHP Processing on your Web Server
In order to verify PHP installation, you create a very basic PHP script called myde-
mo.php.
Now go to C:\XAMPP\htdocs\. Save the above mydemo.php file at this location.
The file should contain following statement.
File Name : mydemo.php
<?php
echo"Hurray !!! First PHP Program is working";
?>
Now go to browser and type following line in the address bar.
http://your_server_ip/mydemo.php or http://localhost/mydemo.php

Note : your_server_ip is the actual IP address of your server machine which is in


digits.
76
Step 3 : To configure Apache server for postgresql
Open 'php.ini' file located at C:\xampp\php\php.ini or click on 'config' button on
the XAMPP Apache control panel.
Now add the line below at the end of file.
extension=php_pgsql.dll
extension=php_pdo_pgsql.dll

Exercise

Q.1 Fill in the blanks. Q2. State True/False.


1. PHP is ___________ side 1. PHP is platform dependent
scripting language. scripting language.
2. PHP is ___________ language 2. $_POST is an array of variables
i.e. there is no need for passed via the URL parameters.
compilation.
3. A Function is a block of statements
3. A variable starts with ________ that can be used repeatedly in a
sign followed by variable name. program.
4. An ____________ is a variable, 4. PHP cannot be embeded along
which can hold more than one with HTML tags.
value at a time.
5. GET should NEVER be used for
5. Information can be passed to sending sensitive information.
functions through __________.

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?

3. The ________ function returns a 3) What is server side scripting?


part of a string. 4) List the supported datatypes in
a) trim() b) ucwords() PHP.
c) substr() d) strpos() 5) Explain any two string
Q4. Multiple Choice Question. manipulation function.
(2 correct) Q7. Write Programs for the following.
1. The _______ & ______ are valid 1) Write a PHP code which
datatype in PHP. calculates square of any number
a) Double b) Varchar using form.
c) Integer d) Array 2) Write a PHP code to count no. of
e) BigInt words in the given string.
2. Single line comment in PHP is 3) Create a website with two PHP
possible using _______, ______. webpage in which each webpage
a) // b) /* */ is connected.
c) # d) <!-- --> The first page of the website
e) $ contains two form fields for
taking ‘name’ and ‘password’
Q5. Multiple Choice Question.
from users. On onclick event,
(3 correct)
details of forms should be
1. In PHP, three types of arrays are displayed on second webpage.
______, _______, _______ .
a) Indexed b) Simple

c) Associative
d) Multidimensional
e) Complex f) General
78

You might also like