You are on page 1of 45

PHP

UNIT - 4 PHP 1
 The Internet is the global system of interconnected computer networks that
uses the Internet protocol suite (TCP/IP) to communicate between networks
and devices. ...
 W W W – World Wide Web. It is the collections of Networks that make up
the internet
 URL – Uniform Resource Locator. The internet uses url to identify
resources available on the internet
protocol://domainname:port/websitename/webpagename
http://10.1.1.30:80/ecap/default.aspx
 HTTP – Hyper Text Transfer Protocol .The communications protocol used to
connect to Web servers on the Internet or on a local network (intranet).
Its primary function is to establish a connection with the server and send
HTML pages back to the user's browser.
It allows your web browser (i.e. Google Chrome, Mozilla Firefox, Apple
Safari or Internet Explorer) to communicate with the server where any given
website is hosted.

UNIT-4 PHP 2
UNIT-4 PHP 3
Web Application
A web application (or web app) is an application software that runs on
a web server, unlike computer-based software programs that are stored locally on
the Operating System (OS) of the device. Web applications are accessed by the
user through a web browser with an active internet connection.

Common web applications include email, online retail sales, online auctions,
wikis, instant messaging services and more.

Web Server
A web server is a computer that runs websites. It's a computer program that
distributes web pages as they are requisitioned. The basic objective of the web
server is to store, process and deliver web pages to the users. This
intercommunication is done using Hypertext Transfer Protocol (HTTP).

Web - Server Types


Apache HTTP Server
Internet Information Services.
Tomcat
XAMPP
UNIT-4 PHP 4
Web Browser
A web browser, or simply "browser," is an application used to access and view
websites. Common web browsers include Microsoft Internet Explorer, Google
Chrome, Mozilla Firefox, and Apple Safari. ...
Web Page
It is a document consists of plane text, hyper text, video files and links to another
pages to be displayed in a web borwser.
Static Web Page
Dynamic Web Page
Static Webpage : A page which don’t have any backend process is called Static
Web page
Ex : .html extension files.
Dynamic Webpage : A page which have got backend process is called dynamic
web page.
Ex : .php, .jsp, .aspx, .py extension files.

UNIT-4 PHP 5
What is PHP?
• PHP stands for Hypertext Preprocessor.
• PHP is a very popular and widely-used open source server-side
scripting language to write dynamically generated web pages.
• PHP was originally created by Rasmus Lerdorf in 1994.
• It was initially known as Personal Home Page.
• PHP scripts are executed on the server and the result is sent to the
web browser as plain HTML.
• PHP can be integrated with the number of popular databases,
including MySQL, PostgreSQL, Oracle, Microsoft SQL Server,
Sybase, and so on.
• The current major version of PHP is 7

UNIT - 4 PHP 6
What You Can Do with PHP
• You can generate pages and files dynamically.
• You can create, open, read, write and close files on the server.
• You can collect data from a web form such as user information,
email, phone no, etc.
• You can send emails to the users of your website.
• You can send and receive cookies to track the visitor of your
website.
• You can store, delete, and modify information in your database.
• You can restrict unauthorized access to your website.
• You can encrypt and decrypt data for safe transmission over
internet.

UNIT - 4 PHP 7
Setting Up a Local Web Server
PHP script execute on a web server running PHP. So before you start writing any
PHP program you need the following program installed on your computer.

• The Apache Web server


• The PHP engine
• The MySQL database server

You can either install them individually or choose a pre-configured package for
your operating system like Linux and Windows.
Popular pre-configured package are XAMPP and WampServer.

UNIT - 4 PHP 8
XAMPP Web Server

• XAMPP stands for Cross-Platform (X), Apache (A), MySQL (M),


PHP (P) and Perl (P).
• It is a simple, lightweight Apache distribution that makes it extremely
easy for developers to create a local web server for testing purposes.
Everything you need to set up a web server – server application
(Apache), database (MySQL), and scripting language (PHP) – is
included in a simple extractable file.
• XAMPP is also cross-platform, which means it works equally well on
Linux, Mac and Windows.

XAMPP Installation Steps

UNIT - 4 PHP 9
PHP File

• PHP is file the combination of template text and PHP Script


• template text can be plain text or HTML.
• template text is executed at the client side ie Web Browser.
• A PHP script is executed on the server, and the plain HTML result is
sent back to the browser.
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
• The default file extension for PHP files is ".php".

UNIT - 4 PHP 10
PHP Comments

• A comment in PHP code is a line that is not executed as a part of the


program. Its only purpose is to be read by someone who is looking at
the code.
• Singleline Comment
• //
• #
• Multiline Comment
/*
PHP code
*/

UNIT - 4 PHP 11
PHP output statements
The PHP echo Statement
• The echo statement can output one or more strings.
• The echo statement can display anything that can be displayed to the browser,
such as string, numbers, variables values, the results of expressions etc.
• you can use it without parentheses e.g. echo or echo().
• If you want to pass more than one parameter to echo, the parameters must not
be enclosed within parentheses.
<?php
// Displaying HTML code
echo "<h4>This is a simple heading.</h4>";
echo "<h4 style='color: red;'>This is heading with style.</h4>";
?>
The PHP print Statement
• You can also use the print statement (an alternative to echo) to display output to
the browser.
• You can also use it without parentheses like: print or print().
• Both echo and print statement works exactly the same way except that the print
statement can only output one string, and always returns 1.
<?php
// Displaying HTML code
print "<h4>This is a simple heading.</h4>";
print "<h4 style='color: red;'>This is heading with style.</h4>";
?> UNIT - 4 PHP 12
PHP processor modes

• The PHP processor has two modes:

• copy
• interpret.

• The processor starts off in copy mode; text from the file, typically HTML, is
copied to the network connection and sent to the client browser.
• When a <?php processing instruction is encountered the processor switches to
interpret mode. The PHP statements are interpreted, and their output, if any, is
sent to the browser. The processor remains in interpret mode until a ?> is
encountered.
• which switches it back to copy mode.

UNIT - 4 PHP 13
PHP Variables
• Variables are used to store data, like string of text, numbers, etc. Variable
values can change over the course of a script.
• In PHP, a variable does not need to be declared before adding a value to it.
• PHP automatically converts the variable to the correct data type, depending on
its value.
Naming Conventions for PHP Variables
• All variables in PHP start with a $ 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 in PHP can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _).
• A variable name cannot contain spaces.

$txt = "Hello World!";


$number = 10;

UNIT - 4 PHP 14
PHP Constants
• A constant is a name or an identifier for a fixed value. Constant are like
variables, except that once they are defined, they cannot be undefined or
changed
• Constants are very useful for storing data that doesn't change while the script is
running.
• Common examples of such data include configuration settings such as database
username and password, website's base URL, company name, etc.
• Constants are defined using PHP's define() function, which accepts two
arguments: the name of the constant, and its value. Once defined the constant
value can be accessed at any time just by referring to its name

<?php
//Defining constant
define("SITE_URL", "https://www.tutorialrepublic.com/");
// Using constant
echo ‘ Thank you for visiting - ' . SITE_URL;
?>

UNIT - 4 PHP 15
Data Types in PHP
The values assigned to a PHP variable may be of different data types including
simple string and numeric types to more complex data types like arrays and
objects.

PHP supports total eight primitive data types:

•Integer
•Float
•String
•Boolean
• Array
•Object
• resource
•NULL

UNIT - 4 PHP 16
PHP Operators
Operators are symbols that tell the PHP processor to perform certain actions.
Arithmetic Operators
+ - Addition
- - Subtraction
* - multiplication
/ - Division
% - Modulus
Assignment Operators
= - Assign
+= - Add and Assign
-= - Subtract and Assign
*= - Multiply and Assign
/= - Division and Assign
%= - Modulus and Assign
Comparison Operators
< - less than
> - greater than
<= - less than or equal to
>= - greater than or euqal to
== - equals
!= - not equals UNIT - 4 PHP 17
PHP Operators
Logical Operators
and - And
or - or
xor - Xor
&& - And
|| - Or
! - Not

Incrementing and Decrementing Operators


++ - increment
-- - decrement

String Operators
. - concatenation
.= - concatenation assignment

UNIT - 4 PHP 18
PHP Data type Conversion
The mechanism of converting one type data into another type is called data
type conversion

There are two types of conversion

• Implicit type conversion


• Explicit type conversion or type casting

Implicit type conversion


• PHP is a loosely typed language that allows you to declare a variable and
its type simply by using it.
• It also automatically converts values from one type to another whenever
required. This is called implicit casting.
<?php
$a = 56;
$b = 12;
$c = $a / $b;
echo $c; # 4.66
?>

UNIT - 4 PHP 19
PHP Data type Conversion
Explicit type conversion
Type casting refers to changing an variable of one data type into another
explicitly.
By placing the type name in parentheses in front of a variable, PHP converts
the value to the desired type:

Cast type Description


(int) (integer) Cast to an integer by dropping the decimal
portion

(bool) (boolean) Cast to a Boolean

(float) (double) (real) Cast to a floating-point number

(string) Cast to a string

(array) Cast to an array

(object) Cast to an object

$c = (int) ($a / $b);

UNIT - 4 PHP 20
PHP GET and POST
Methods of Sending Information to Server
A web browser communicates with the server typically using one of the two HTTP
(Hypertext Transfer Protocol) methods — GET and POST
The GET Method
In GET method the data is sent as URL parameters that are usually strings of name
and value pairs separated by ampersands (&). In general, a URL with GET data
will look like this:
http://www.example.com/action.php?name=john&age=24
Advantages and Disadvantages of Using the GET Method
• Since the data sent by the GET method are displayed in the URL, it is possible
to bookmark the page with specific query string values.
• The GET method is not suitable for passing sensitive information such as the
username and password, because these are fully visible in the URL query string
as well as potentially stored in the client browser's memory as a visited page.
• Because the GET method assigns data to a server environment variable, the
length of the URL is limited. So, there is a limitation for the total data to be
sent.
• PHP provides the super global variable $_GET to access all the information
sent either through the URL or submitted through an HTML form using the
method="get".
UNIT - 4 PHP 21
PHP GET and POST
The POST Method

In POST method the data is sent to the server as a package in a separate


communication with the processing script. Data sent through POST method will
not visible in the URL.

Advantages and Disadvantages of Using the POST Method

• It is more secure than GET because user-entered information is never visible in


the URL query string or in the server logs.
• There is a much larger limit on the amount of data that can be passed and one
can send text data as well as binary data (uploading a file) using POST.
• Since the data sent by the POST method is not visible in the URL, so it is not
possible to bookmark the page with specific query.
• Like $_GET, PHP provide another super global variable $_POST to access
all the information sent via post method or submitted through an HTML form
using the method="post".

UNIT - 4 PHP 22
PHP GET and POST
The $_REQUEST Variable

PHP provides another superglobal variable $_REQUEST that contains the values
of both the $_GET and $_POST variables as well as the values of the $_COOKIE
superglobal variable.

$name = $_GET[‘uname’]

$name = $_POST[‘uname’]

$name = $_REQUEST[‘uname’]

UNIT - 4 PHP 23
PHP Conditional Statements
PHP also allows you to write code that perform different actions based on the
results of a logical or comparative test conditions at run time.
• The if statement
• The if...else statement
• The if...else if....else statement
• The switch...case statement
The if Statement
The if statement is used to execute a block of code only if the specified condition
evaluates to true.
if(condition){
// Code to be executed
}
The if...else Statement
The if...else statement allows you to execute one block of code if the specified
condition is evaluates to true and another block of code if it is evaluates to false.
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
UNIT - 4 PHP 24
PHP Conditional Statements
The if...else if...else Statement
The if...else if...else a special statement that is used to combine multiple if...else
statements.
if(condition1){
// Code to be executed if condition1 is true
} else if(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
Switch…Case Statements
The switch-case statement is an alternative to the if-else if-else statement, which
does almost the same thing. The switch-case statement tests a variable against a
series of values until it finds a match, and then executes the block of code
corresponding to that match.
switch(n){
case label1:
// Code to be executed if n=label1
break;
case label2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels} UNIT - 4 PHP 25
PHP Loops
• Loops are used to execute the same block of code again and again, as long as a
certain condition is met.
• The basic idea behind a loop is to automate the repetitive tasks within a program
to save the time and effort
• while
• do-while
• for
• foreach
while Loop
The while statement will loops through a block of code as long as the condition
specified in the while statement evaluate to true.
while(condition){
// Code to be executed
}
do…while Loop
With a do-while loop the block of code executed once, and then the condition is
evaluated, if the condition is true, the statement is repeated as long as the specified
condition evaluated to is true.
do{
// Code to be executed
}while(condition);
UNIT - 4 PHP 26
PHP Loops
for Loop

The for loop repeats a block of code as long as a certain condition is met. It is
typically used to execute a block of code for certain number of times.

for(initialization; condition; increment){


// Code to be executed
}

foreach Loop
The foreach loop is used to iterate over arrays.

foreach($array as $value){
// Code to be executed
}

UNIT - 4 PHP 27
PHP Arrays
Arrays are complex variables that allow us to store more than one value or a
group of values under a single variable name.

Types of Arrays in PHP


There are three types of arrays that you can create. These are:
• Indexed or Numeric Arrays: An array with a numeric index where
values are stored linearly.
• Associative Arrays: An array with a string index where instead of linear
storage, each value can be assigned a specific key.
• Multidimensional Arrays: An array which contains single or multiple
array within it and can be accessed via multiple indices.

• An array is created using an array() function in PHP.

Indexed or Numeric Arrays


These type of arrays can be used to store any type of elements, but an index is
always a number. By default, the index starts at zero.

$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");


echo $name_one[0]; # Zack
UNIT - 4 PHP 28
PHP Arrays
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage,
every value can be assigned with a user-defined key of string type.

$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
echo "Salary of mohammad is ". $salaries['mohammad']

Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array
and each element in the sub-array can be an array or further contain array within
itself and so on. $contacts = array(
array(
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
),
array(
"name" => "Clark Kent",
"email" => "clarkkent@mail.com",
);
echo "Peter Parker's Email-id is: " .
$contacts[0]["email"];
# peterparker@mail.com
29
UNIT - 4 PHP
PHP Functions
Advantages of using functions:

• Functions reduces the repetition of code within a program


• Functions makes the code much easier to maintain.
• Functions makes it easier to eliminate the errors.
• Functions can be reused in other application

Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:

function functionName() {
code to be executed;
}
<?php
function writeMsg() {
echo "Hello world!";
}

To call the function, just write its name followed by brackets ():
writeMsg(); // call the function
UNIT - 4 PHP 30
PHP Functions
Functions with Parameters
• You can specify parameters when you define your function to accept input
values at run time.
• The parameters work like placeholder variables within a function; they're
replaced at run time by the values (known as argument) provided to the
function at the time of invocation.
function myFunc($oneParameter, $anotherParameter){
// Code to be executed
}
Functions with Optional Parameters and Default Values
You can also create functions with optional parameters — just insert the parameter
name, followed by an equals (=) sign, followed by a default value
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello,
world!</p>";
}
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
UNIT - 4 PHP 31
PHP Functions
Returning Values from a Function

A function can return a value back to the script that called the function using the
return statement. The value may be of any type, including arrays and objects.
A function can not return multiple values. However, you can obtain similar results
by returning an array

function getSum($num1, $num2){


$total = $num1 + $num2;
return $total;
}
function divideNumbers($dividend, $divisor){
$quotient = $dividend / $divisor;
$array = array($dividend, $divisor, $quotient);
return $array;
}

UNIT - 4 PHP 32
PHP Functions
Passing Arguments to a Function by Reference
• In PHP there are two ways you can pass arguments to a function: by value
and by reference.
• By default, function arguments are passed by value so that if the value of the
argument within the function is changed, it does not get affected outside of
the function.
• To allow a function to modify its arguments, they must be passed by
reference.
• Passing an argument by reference is done by prepending an ampersand (&) to
the argument name in the function definition

function selfMultiply(&$number){
$number *= $number;
return $number;
}

UNIT - 4 PHP 33
PHP Functions
Understanding the Variable Scope
• you can declare the variables anywhere in a PHP script.
• The location of the declaration determines the extent of a variable's visibility
within the PHP program i.e. where the variable can be used or accessed. This
accessibility is known as variable scope.
• By default, variables declared within a function are local and they cannot be
viewed or manipulated from outside of that function

The global Keyword


you can use the global keyword before the variables inside a function. This
keyword turns the variable into a global variable, making it visible or accessible
both inside and outside the function

$greet = "Hello World!";


function test(){
global $greet;
echo $greet;
}

UNIT - 4 PHP 34
PHP Cookies
What is a Cookie

A cookie is a small text file that lets you store a small amount of data (nearly
4KB) on the user's computer. They are typically used to keeping track of
information such as username that the site can retrieve to personalize the page
when user visit the website next time

Setting a Cookie in PHP

The setcookie() function is used to set a cookie in PHP. Make sure you call the
setcookie() function before any output generated by your script otherwise cookie
will not set
setcookie(name, value, expire, path, domain, secure);

parameters of the Cookie

setcookie("username", "John Carter");

UNIT - 4 PHP 35
PHP Cookies
Accessing Cookies Values
The PHP $_COOKIE superglobal variable is used to retrieve a cookie value. It
typically an associative array that contains a list of all the cookies values sent by
the browser in the current request, keyed by cookie name. The individual cookie
value can be accessed using standard array notation
echo $_COOKIE["username"];
it's a good practice to check whether a cookie is set or not before accessing its
value. To do this you can use the PHP isset() function
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
Removing Cookies
You can delete a cookie by calling the same setcookie() function with the cookie
name and any value (such as an empty string) however this time you need the set
the expiration date in the past
setcookie("username", "", time()-3600);

UNIT - 4 PHP 36
PHP Sessions
• Although you can store data using cookies but it has some security issues.
Since cookies are stored on user's computer it is possible for an attacker to
easily modify a cookie content to insert potentially harmful data in your
application that might break your application.

• Also every time the browser requests a URL to the server, all the cookie data
for a website is automatically sent to the server within the request. It means if
you have stored 5 cookies on user's system, each having 4KB in size, the
browser needs to upload 20KB of data each time the user views a page, which
can affect your site's performance.

• You can solve both of these issues by using the PHP session.
• A PHP session stores data on the server rather than user's computer.
• In a session based environment, every user is identified through a unique
number called session identifier or SID.
• This unique session ID is used to link each user with their own
information on the server like emails, posts, etc.

UNIT - 4 PHP 37
PHP Sessions
Starting a PHP Session
Before you can store any information in session variables, you must first start up
the session. To begin a new session, simply call the PHP session_start() function.
It will create a new session and generate a unique session ID for the user.
session_start();
The session_start() function first checks to see if a session already exists by
looking for the presence of a session ID. If it finds one, i.e. if the session is already
started, it sets up the session variables and if doesn't, it starts a new session by
creating a new session ID.
Storing and Accessing Session Data
You can store all your session data as key-value pairs in the $_SESSION[]
superglobal array. The stored data can be accessed during lifetime of a session.
Consider the following script, which creates a new session and registers two
session variables.
session_start();
// Storing session data
$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker";
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];

UNIT - 4 PHP 38
MYSQL DATABASE
• It is open-source database software, which is supported by Oracle Company.
• It is fast, scalable, and easy to use database management system in comparison
with Microsoft SQL Server and Oracle Database.
• It is developed, marketed, and supported by MySQL AB, a Swedish company,
and written in C programming language and C++ programming language.

PHP Connect to MySQL Server


• The mysqli_connect() function is used to connection.
• All communication between PHP and the MySQL database server takes place
through this connection.

$link = mysqli_connect("hostname", "username", "password", "database");

• The hostname parameter specify the host name (e.g. localhost), or IP address of
the MySQL server,
• whereas the username and password parameters specifies the credentials to
access MySQL server,
• The database parameter, if provided will specify the default MySQL database
to be used when performing queries.
UNIT - 4 PHP 39
Inserting Data into a MySQL Database Table
• The mysqli_query() function to insert data in table

mysqli_query(connection, query, resultmode)

connection : required
query : required
resultmode : optional

Retrieving data from a database


The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set
and returns it as an enumerated array.

mysqli_fetch_row(result)

The fetch_array() / mysqli_fetch_array() function fetches a result row as an


associative array, a numeric array, or both.

mysqli_fetch_array(result,resulttype)
UNIT - 4 PHP 40
AJAX
• AJAX stands for Asynchronous Javascript And XML.It is a technique for
better, faster and more interactive Web Applications with the help and Java
Script
• Synchronous Model : A Synchronous request blocks the client until operation
completes.
• Asynchronous Model : An Asynchronous request does not block the client
operation, at that time user can perform another operation also.

AJAX Benefits
• Reduce the server traffic in both side request. Also reducing the time
consuming on both side response.
• AJAX is much responsive.
• AJAX make asynchronous calls to a web server. This means client browsers
are avoid waiting for all data arrive before start the rendering.
• Form are common element in web page. Validation should be instant and
properly, AJAX gives you all of that, and more.
• No require to completely reload page again. AJAX is improve the speed and
performance. Fetching data from database and storing data into database
perform background without reloading page.

UNIT - 4 PHP 41
HOW AJAX WORKS?

UNIT - 4 PHP 42
AJAX
• User sends a request from the UI and a javascript call goes to
XMLHttpRequest object.
• HTTP Request is sent to the server by XMLHttpRequest object.
• Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
• Data is retrieved.
• Server sends XML data or JSON data to the XMLHttpRequest callback
function.
• HTML and CSS data is displayed on the browser.

Processing steps
To write an AJAX based application a programmer should follow the below steps
1. Create an XMLHttpRequest
It provides a set of properties and methods that are used to send httprequest and to
retrieve data from the server.
2. Specify handels
We must specify a function to be called when the http response from the server
comes back. We call this function as response handler. This function will receive
information returned by the server, extract the data and perform a specific task.

UNIT - 4 PHP 43
AJAX
Processing steps
3. AJAX readystate property
The process of communicating with the server for sending HttpRequest to getting
a response involves 5 states.
Property Description

onReadyStateChange It is called whenever readystate


attribute changes. It must not be used
with synchronous requests.
readyState represents the state of the request. It
ranges from 0 to 4.0 UNOPENED open()
is not called.
1 OPENED open is called but send() is
not called.
2 HEADERS_RECEIVED send() is called,
and headers and status are available.
3 LOADING Downloading data;
responseText holds the data.
4 DONE The operation is completed
fully.

reponseText returns response as text.


responseXML returns response as XML

UNIT - 4 PHP 44
AJAX
• Sending a request consists of two steps
1. Open a connection
2. Sending an HttpRequest.

Open a coonection : The open() is used establish communication between Web


Browser and Web Server.

open(method,URL)
open(method,URL,boolean)

Sending an HttpRequest.:

Once the TCP connection is established We can send the HttpRequest through the
server with this connection using send() method.

void send()
Retrieving Information :
We can retrieve the server’s response by using responseText or responseXML
properties. The response may be a simple string or a complete XML.

UNIT - 4 PHP 45

You might also like