0% found this document useful (0 votes)
5 views

5. Server-Side Scripting (PHP)

Chapter 5 covers server-side scripting using PHP, detailing its features, execution, and variable management. It explains PHP's compatibility with various platforms, data types, and control structures, as well as user-defined functions and form handling with databases. The chapter emphasizes the differences between GET and POST methods for form data submission and introduces database connectivity using PDO for managing data in applications.

Uploaded by

manavdeshmukh60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

5. Server-Side Scripting (PHP)

Chapter 5 covers server-side scripting using PHP, detailing its features, execution, and variable management. It explains PHP's compatibility with various platforms, data types, and control structures, as well as user-defined functions and form handling with databases. The chapter emphasizes the differences between GET and POST methods for form data submission and introduces database connectivity using PDO for managing data in applications.

Uploaded by

manavdeshmukh60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Chapter 5

Server-Side Scripting (PHP)


12th Information Technology
Maharashtra Board
Marks Distribution
Q. No. Description Marks /Question No. Marks
Of Questions
Q1. Fill in the blanks 1 1 1

Q2. State true of false 1 3 3

Q3. Multiple choice SINGLE answer 1 3 3

Q4. Multiple choice TWO correct answer 2 2 4

Q5. Multiple choice THREE correct answer 3 1 3

Q6. Match the following 1 1 1

Q7. Answer briefly (Any 5) 2 - -

Q8. Write code (HTML or JavaScript) 5 - -

Total 15
2
Introduction to PHP
Introduction to PHP
• PHP (Hypertext Preprocessor)
• Open source scripting language.
• Suited for web development
• Can be embedded into HTML.
• PHP runs on various platforms (Linux, Unix, Mac OS X,
Windows etc.).
• PHP is compatible with almost all servers used today
• For eg. XAMMP, Apache, NGINX, lighttpd
• Supports a wide range of databases.
• PHP is free
• One can download it from the official PHP resource: www.
php.net.
• PHP is easy to learn and runs efficiently on the server side.
Server Side Scripting Scripting Language

Web Server
Server Side Scripting
• A server is a computer system that serves as a central
repository of data and programs and is shared by the clients.
• The server-side environment that runs a scripting language is
termed web server.
• A user's request is fulfilled by running a script directly on the
web server to generate dynamic HTML pages.
• This HTML is then sent to the client browser.
• It is usually used to provide interactive web sites that
interfaces with databases or other data stores on the server.
Features of PHP
• Simple
• Interpreted
• Faster
• Open Source
• Platform Independent
• Case Sensitive
• Error Reporting
• Real-Time Access
• Monitoring
• Loosely Typed Language
First sample code of PHP
First sample code of PHP
How to execute PHP program
• Type the above program and save it as"first.php"using
any text editor (for e.g. notepad, gedit).

• Create folder with your name in /var/ www/html. (for


e.g. balbharati)
Folder created on web server:-
first.php in server directory:-
Go to browser and type "http://localhost/balbharati/"inURL bar. Click on 'first.php'.

(List of files on server directory)


(Output of first.php program)
PHP Case Sensitivity :
PHP Case Sensitivity :

• In PHP, the variable names are case sensitive.


• However keywords (e.g. if, else, break, for, while, echo
etc.), function and class names are case insensitive.
Output:-
PHP Variables
• Variable is a symbol or name that stands for a value.

• Variables are used for storing values such as numeric


values, characters, character strings, or memory
addresses, so that they can be used in any part of the
program.
Rules for declaring PHP
Variable :
Rules for declaring PHP Variable :

• A variable starts with the $ sign, followed by the name


of the variable

• A variable name must start with a letter or


the underscore character

• A variable name cannot start with a number

• A variable name can only contain alpha-numeric characters


and underscores (A-z, 0-9, and _ )

• Variable names are case-sensitive ($age and $AGE are


two different variables)
There are three different variable scopes in PHP:

• Local

• Global

• Static

A variable declared outside a function 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).
Output:-
• We can access a global variable $c from within a
function using "global" keyword before the variables
(inside the function).

• Note : PHP also stores all global variables in an


array called $GLOBALS[index].

• The index holds the name of the variable

• When a function is executed, then all of its variables


are deleted.

• In some cases, if we want a local variable not to be


deleted then the use of "static" keyword is must.
Output:-
PHP Data Types:
PHP Data Types:
● Variables can store data of different types and PHP supports the
following data types :

• 1) String
• 2) Integer
• 3) Float
• 4) Boolean
• 5) Array
• 6) NULL

• e.g. : One can check the data-type of variable using var_dump()


method in PHP.
PHP Data Types:
Output:-
Comments in PHP
Comments in PHP
• Comments are the statements in PHP code, which are not visible
in the output of the program. It is ignored during execution.

• A Single-line comment is possible if one adds // or # before a


statement in PHP.

• A multi-line comment is possible with /* and */ .


Control structures in PHP
Control structures in PHP
• If statement in PHP : if statement allows programmer to make
decision, based on one or more conditions; and execute a piece of
code conditionally.

• Syntax : if(condition) { block of statement; }


Control structures in PHP

• If-else statement in PHP : if-else statement allows programmer


to make decision based on either this or that conditions.

Syntax : if(condition) { Statement; } else { Statement; }


Control structures in PHP
Output:-
Control structures in PHP

• Loop Structure in PHP : Loops are used to execute the same block
of code repeatedly as long as a certain condition is satisfied.

For eg : 'For loop' in PHP

• Syntax :
• for(initialisation; condition; incrementation or decrementation) {
Statement;
}
Control structures in PHP
Output:-
Control structures in PHP

• Use of foreach loop : This loop 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;
}
PHP String Functions
• A string is series of characters.

• The real power of PHP comes from its functions.

• A function is a block of statements that can be used repeatedly in


a program.

• PHP has many built-in functions that can be called directly to


perform a specific task.
PHP String Functions
Function Description

Returns the length of a string (i.e. total no. of characters)


strlen(string)
Counts the number of words in a string
str_word_count(string)
Reverses a string
strrev(string)
Searches for a specific text within a string and returns the
strpos(string,find) character position of the first match and if no match is found,
then it will return false
Replaces some characters with some other characters in a
str_replace(find,replace,string) string
Returns a part of a string
substr(string,start,length)
Converts a string to lowercase
strtolower(string)
Counts the number of times a substring occurs in a string
substr_count(string,substring)
Converts the first character of each word in a string to
ucwords(string) uppercase
Removes whitespace and other predefined characters from
trim(string,charlist) both sides of a string
PHP String Functions
Output:-
PHP Arrays
PHP Arrays
PHP Arrays
• An array is a special variable, which can hold more than one
value at a time.
• An array stores multiple values in one single variable:

• Create an Array in PHP :


In PHP, the array() function is used to create an array.

• Syntax : $a = array( values )


PHP Arrays

● An array is a special variable, which can hold more than one


value at a time. An array stores multiple values in one single
variable:

● Create an Array in PHP : In PHP, the array() function is used to


create an array.

● Syntax : $a = array( values )


PHP Arrays

● In PHP, there are three types of arrays:

• Indexed arrays - Arrays with a numeric index

• Associative arrays - Arrays with named keys

• Multi-dimensional arrays - Arrays containing one or more arrays


Indexed arrays :

● The index can be assigned automatically (index always starts at 0).

● Syntax : $a = array( value1, value2, ..., value n)


Indexed arrays Example

Output:-
PHP Arrays
● In the example, we store subject in an array at following index
location.
$subjects[0] = "English";
$subjects[1] = "Hindi";
$subjects[2] = "Marathi";

The count() function is used to return the length of an array:

Note : An array can hold many values under a single name, and you
can access the values by referring to an index number.
PHP Associative Arrays

Associative arrays are arrays that use named keys instead of index to
identify record/value. Let us see how to create associative array.

Syntax : $a = array( key1 => value1, key2 =>value2, ...,key n => value n)
PHP Associative Arrays

Output:-
PHP Associative Arrays
In above example, the values of ‘student_mark’ array are stored in
following way:

$student_mark['English'] = "75"
$student_mark['Hindi'] = "64"
$student_mark['Marathi'] = "88"

Instead of index location, we can refer values with the help of keys.

Here 'English' refers to a key & value is '75'.

"=>" is used to associate key & value.


Use of foreach loop in an array

Output:-
PHP Multi-dimensional Arrays

Roll No. Name Percentage (%)

1 Munna 35

2 Guddu 40

3 Bablu 70
PHP Multi-dimensional Arrays
PHP Multi-dimensional Arrays

● A multidimensional array is an array containing one or more arrays.


● PHP can handle multiple levels of multidimensional array.

● Example : $emp = array(


array(1,"Munna",35),
array(2,"Guddu",40),
array(3,"Bablu",70)
);
PHP User Defined Functions
• A function is a block of statements that can be used
repeatedly in a program.
• It will not execute immediately when a page loads but will
be executed by a call to the function.
• Along with built-in PHP functions, we can always create our
own functions.
• A user-defined function declaration starts with the word
function.
• Syntax :
function functionName() {
code to be executed;
}
PHP User Defined Functions
• A function name can start with a letter or
underscore (not a number).
• Function names are NOT case sensitive.
PHP User Defined Functions
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.
PHP Function Arguments
The following example has a function with arguments
($rollno and $name):
Output:-
Returning Value
To let a function return a value, use the return statement:
Output:-
PHP Form Handling
A simple HTML form with two input fields and a submit button:

Output:-
PHP Form Handling
● When the user fills out the form above and clicks the submit button,
the form data is sent for processing to a PHP file named
"welcome.php".
● The form data is sent with the HTTP POST method.
PHP Form Handling
The code for "welcome.php" looks like this:
Output:-
PHP Form Handling
$_POST["email"] helps us to get the data of form field whose name
attribute is email.

Lets understand another example with HTTP GET method.


Output:-
bmioutput.php
Output:-
● The PHP superglobals $_GET and $_POST are used to collect form-
data.
● The same result could also be achieved using the HTTP POST
method.
● Just replace GET with POST .
Let us understand the difference between GET and POST Method

• Both GET and POST are treated as $_GET and $_POST


superglobals.
• which means that they are always accessible, regardless of scope.
• It can be accessed from any function, class or file without having to
do anything special.
• $_GET is an array of variables passed via the URL parameters.
• $_POST is an array of variables passed via the HTTP POST
method.
When to use GET ?
● Information sent from a form with the GET method is visible to
everyone (all variable names and values are displayed in the URL).
● GET also has limits on the amount of information to send.
● However, because the variables are displayed in the URL, it is
possible to bookmark the page.
● This can be useful in some cases.
● GET may be used for sending nonsensitive data.
● GET should NEVER be used for sending passwords or other sensitive
information
When to use POST?

• Information sent from a form with the POST method is invisible to


everyone
• All names/values are embedded within the body of the HTTP request.
• POST has no limits on the amount of information to send.
• Moreover POST supports advanced functionality such as support for
multi-part binary input while uploading files to server.
• The variables are not displayed in the URL so it is not possible to
bookmark the page.
Form connectivity with Database :
● Example : Create an admission form for the registration of the
college student.
● We have already studied HTML form creation in previous chapter
and database creation in DBMS chapter.
● Now create"college"database and create table"student"with
following fields in this Postgres SQL database.

Name gender
Now write following code in ‘admission. php’ file.

Output:-
● In above example, PHP Data Object class, i.e. PDO(),
helps us to connect PHP code with almost any database
server.
● It doesn't account for database-specific syntax, and one
can switch database simply by switching the
connection string in many instances.
● It provides database access layer providing a uniform
method of access to multiple databases.
1) Create database connection object

$conn = new
PDO($servername,$username,
$password);

In our example, we connect PHP with PostgreSQL server.


The above statement creates connectivity object ‘$conn’ with three
parameters as shown below:

1. Server host name or IP address and Database name


2. Database username
3. Database password
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.

Note : isset() method in PHP is used to check whether


variable has value or not, this help us to know if the button
is clicked or not.
● The above program is used to insert data from the user
into the database.
● Now let us understand how to fetch the data from
database and display as a webpage.
● The next program uses PDO exception. PDO exceptions
are used to handle errors, which means anything you do
with PDO should be wrapped in a try/catch block.
● The part of code which may be erroneous can be put in
try{ } block and the code to handle the error can be place
in catch{ } block.
● PDO exception class is used to throw errors due to
database connectivity.
● ‘$e’ is the object of PDO and using getMessage(), we can
print the error message for database connectivity.
● prepare($sql) is the secure way to execute SQL queries
using any programming language whereas fetchAll()
method is used to get all the records from the given
table and store in $result variable.

$conn -> null is to close the database connectivity object


Continue on next slide ->>
Output:-
Cookies and session in PHP :
Cookies :

● A cookie is a small text file that the server sends on the user's
computer. It is used to identify user or its machine and track activities
created on the user computer.
● When browser requests server page, cookies are sent along with the
request.
● PHP can be used both to create and retrieve cookie values.
● Eg. Cookies store visited page on browser to optimise search.
Cookies and session in PHP :
Session :

● This is used to store user information on server to track user activites.


● It helps web application to maintain user information on all the pages.
● Eg. If you login to gmail account, the session help us to access
youtube account also.

You might also like