You are on page 1of 79

Unit-5

Chapter-11
PHP
(HYPERTEXT PREPROCESSOR)
Server Side Scripting
• Server-side scripting is a technique used
in website design which involves
embedding scripts in an HTML source code
which results in a user's (client's) request to
the server website being handled by a script
running server-side before the server
responds to the client's request.

• The scripts can be written in any of a number


of server-side scripting languages available
(see below). Server-side scripting differs
• The down-side to the use of server-side
scripting is that the server website computer
needs to provide most of the computing
resources before sending a page to the client
computer for display via its web browser.

• When the server serves data in a commonly


used manner, for example according to
the HTTP or FTP protocols, users may have
their choice of a number of client programs
(most modern web browsers can request and
receive data using both of those protocols).
What is PHP?
• PHP is a powerful server-side scripting language for creating
dynamic and interactive websites.

• PHP is the widely-used, free, and efficient alternative to


competitors such as Microsoft's ASP. PHP is perfectly suited
for Web development and can be embedded directly into the
HTML code.

• The PHP syntax is very similar to Perl and C. PHP is often used
together with Apache (web server) on various operating
systems. It also supports ISAPI and can be used with
Microsoft's IIS on Windows.
What is PHP?
• PHP stands for PHP: Hypertext Preprocessor

• PHP may also stand for Personal Home Page

• PHP is a server-side scripting language, like ASP

• PHP scripts are executed on the server and their output,


which is plain HTML is returned to a client browser.

• PHP supports many databases (MySQL, Informix, Oracle,


Sybase, Solid, PostgreSQL, Generic ODBC, etc.)

• PHP is an open source software (OSS)

• PHP is free to download and use


PHP and Web server architecture
model
What is a PHP File?

• PHP files may contain text, HTML tags and


scripts
• PHP files are returned to the browser as plain
HTML
• PHP files have a file extension of ".php",
 PHP file can be created by an ASCII editor (e.g.
Notepad, vi etc. ) and stored on hard disk.
Why PHP?

• PHP runs on different platforms (Windows,


Linux, Unix, etc.)
• PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
• PHP is FREE to download from the official PHP
resource: www.php.net
• PHP is easy to learn and runs efficiently on the
server side
What is MySQL?

• MySQL is a database server


• MySQL is ideal for both small and large
applications
• MySQL supports standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use
Why PHP and MySql?(advantages)
• PHP is a server-side scripting language and
therefore PHP script are executed on the
server.
• PHP supports many database like MYSQL.
• PHP is free to download and use.
• MYSQL is a database server and is ideal for
both small and large application.
• MYSQL support standard SQL.
• MYSQL complies on a number of platforms.
Installing PHP
• Download WAMP server. WAMP is a form of
mini server that can run on almost any
windows operating system.
• WAMP is a combined package consisting of
Apache server 2,PHP 5 and MySql.
• WAMP server is available for free download
on www.wampserver.com.
• After completing the download a folder
named wamp is created automatically in the
drive specified while running the setup.
• Inside the wamp folder a subfolder named
“www” is automatically created.
• All the php files are saved inside the www
folder with file extension .php within inverted
commas (ex: “abc.php”).
• To execute php file go to desktop start-> All
programs-> Wamp server-> start WampServer.
• This will generate an icon on the screen.
• Then click on your browser and type the
following in address bar:-
Simple PHP program
<?php
echo “welcome to PHP”;
echo “<br>”;
print (“welcome to PHP”);
?>
• A PHP scripting block always starts with <?php and
ends with ?>.
• A PHP scripting block can be placed anywhere in the
document.
• On servers with shorthand support enabled you can
start a scripting block with <? and end with ?>.
• However, for maximum compatibility, we
recommend that you use the standard form (<?php)
rather than the shorthand form.
• A PHP file normally contains HTML tags, just like an
HTML file, and some PHP scripting code.
• Each code line in PHP must end with a semicolon.
The semicolon is a separator and is used to
distinguish one set of instructions from another.
Comments in PHP

• In PHP, we use // to make a single-line


comment or /* and */ to make a large
comment block.
Adding PHP to HTML
<html>
<body>
<?php
echo "welcome to php";
echo "<br>";
$txt="Hello World!";
print $txt;
?>
PHP Vaiables

• Declaring variable.
• Destroying variable.
• Rules
Variables in PHP

• Variables are used for storing a values, like


text strings, numbers or arrays.
• When a variable is set it can be used over and
over again in your script
• All variables in PHP start with a $ sign symbol.
• The correct way of setting a variable in PHP:
• $var_name = value;
• In PHP a variable does not need to be declared
before being set. Since PHP is a Loosely Typed
Language.
• In the example above, you see that you do not have
to tell PHP which data type the variable is.
• PHP automatically converts the variable to the
correct data type, depending on how they are set.
• In a strongly typed programming language, you have
to declare (define) the type and name of the variable
before using it.
• In PHP the variable is declared automatically when
you use it.
Variable Naming Rules

• A variable name must start with a letter or an


underscore "_"
• A variable name can only contain alpha-numeric
characters and underscores (a-Z, 0-9, and _ )
• A variable name should not contain spaces. If a
variable name is more than one word, it should be
separated with underscore ($my_string), or with
capitalization ($myString)
Example:

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
• Here $x, $y and $z are three variables
declared.
Destroying variables
• To destroy a variable we can use PHP’s unset()
function, as in the following example.
<?php
$car="nano";
echo "before using unset() it display,My car is a $car"."<br>";
unset($car);
echo "after using unset() it display,My car is a $car";
?>
• In the first line PHP scripting block always is
started.
• In the second line a value is assigned to a
variable.
• In third line we have just displayed the value
without using unset() function. And the
output will be “My car is a nano”.
• In the forth line we have used unset()function
and passed the variable $car as a argument to
the function.
• In the next line we have again displayed the
Testing the type of the variable
gettype()function
• Gettype()-returns the type of the variable.
Example:
<?php
$a=null;
echo gettype($a);
echo "<br>";
$a=15;
change the type of the variable
There are two ways to cast a variable in PHP as a
specific type: using the settype() function, or
using (int) ,(bool) (float) etc. Using the settype
function you can do this:
settype() function:

<?php
$a=23.555;
settype($a,"string");
Type casting the variable

<?php
$a=23.555;
echo (int)$a;
echo “<br>”;
echo (float)$a;
echo “<br>”;
echo (boolean)$a;
echo “<br>”;
PHP Operators
• A operator is a symbol which tells the computer to
perform certain mathematical or logical
manipulations. The operators are used in
mathematical and logical expression.

• Arithmetic Operators.
• Assignment Operators.
• Comparison Operators.
• Logical Operators.
• Conditional operator.
• Concatenation operator.
Arithmetic operators

+ addition
- subtraction
* multiplication
/ division
% modulo division
= assignment
Assignment Operators
= assignment .

+= add and assign.

-= subtract and assign.

*= multiply and assign.

/= divide and assign.

%= divide and assign modulus only.


comparison operators

< less than


> greater than
<= less than/equal to
>= greater than /equal to
= = is identical to(comparison only
values)
=== Is identical to (data types and values
both must match)
Logical operators:

&& logical AND

|| logical OR

! Logical NOT
Condition operators:

?:
Exp1 ? Exp2 : Exp3
The Concatenation Operator

• There is only one string operator in PHP.


• The concatenation operator (.) is used to put
two string values together.
• To concatenate two variables together, use the
dot (.) operator
Conditional Statements
• Very often when you write code, you want to
perform different actions for different decisions.
• You can use conditional statements in your code to
do this.
• if...else statement - use this statement if you want to
execute a set of code when a condition is true and
another if the condition is not true
• elseif statement - is used with the if...else statement
to execute a set of code if one of several condition
are true
The If...Else Statement
• the if....else statement.
• Syntax
if (condition)
{
code to be executed if condition is true;
}

else
{
Example-The If...Else Statement
<html>
<body>
<?php
$t=10;
if($t%2==0)
{
echo "even number";
}
The ElseIf Statement
• If you want to execute some code if one of several
conditions are true use the elseif statement
• Syntax
if (condition)
{
code to be executed if condition is true;
}

elseif (condition)
{
code to be executed if condition is true;
Example-The ElseIf Statement
<?php
$t=20;
if($t>0)
{
echo "positive number";
}
elseif($t<0)
{
PHP Switch Statement

• The Switch statement in PHP is used to


perform one of several different actions
based on one of several different conditions.
• If you want to select one of many blocks of
code to be executed, use the Switch
statement.
• The switch statement is used to avoid long
blocks of if..elseif..else code.
• Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1; break;

case label2:
code to be executed if expression = label2;
break;

default:
code to be executed if expression is different from both label1 and label2;

}
Example-Switch Statement
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
Example-Switch Statement
<html>
<body>
<?php
$x=10;
switch ($x)
{
case ($x>0):
echo “+ve Number ";
break;
Looping
• Looping statements in PHP are used to execute the same
block of code a specified number of times.
• Very often when you write code, you want the same block of
code to run a number of times. You can use looping
statements in your code to perform this.
• In PHP we have the following looping statements:
– while - loops through a block of code if and as long as a
specified condition is true
– do...while - loops through a block of code once, and then
repeats the loop as long as a special condition is true
– for - loops through a block of code a specified number of
times
syntax
• while (condition)
{
code to be executed;
}
----------------------------------------------------------------
----------
• do
{
code to be executed;
}
while (condition);
<html>
Example-while loop
<body>

<?php
$num=123;

$sum=0;
while($num>0)
{

$i=$num%10;

$sum=$sum+$i;

$num=$num/10;
}

echo "The addition of all the digits in a number= $sum”;

?>

</body>
</html>
Example-do while loop
• <html>
<body>

<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i>=5);
?>
Example-for loop
• <html>
<body>

<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br>";
}
?>

</body>
</html>
Break and Continue
• Break will break out of the loop, basically stopping all
further looping, and will start executing any code
after the loop.
• The continue keyword will continue the execution of
the next loop. So it will stop the execution of the
current statements, and will start the next execution
of the statements.
• break accepts an optional numeric argument which
tells it how many nested enclosing structures are to
be broken out of.
What is an array?
• An array can store one or more values in a single
variable name.
• When working with PHP, sooner or later, you might
want to create many similar variables.
• Instead of having many similar variables, you can
store the data as elements in an array.
• Each element in the array has its own ID so that it
can be easily accessed.

• There are three different kind of arrays:


– Numeric array - An array with a numeric ID key
– Associative array - An array where each ID key is
• Numeric Arrays
– A numeric array stores each element with a
numeric ID key.
– There are different ways to create a numeric
array

• Associative Arrays
– An associative array, each ID key is associated
with a value.
– When storing data about specific named
values, a numerical array is not always the best
way to do it.
– With associative arrays we can use the values
Initializing Arrays

• Array can be initialized by two ways:


– an array identifier
– the array() function
Using array identifier

• The array identifier is empty set of square


brackets.
<?php
$student[] = “ram”;
$student[] = “sham”;
?>
• The student array will contain ram, sham
(default indices 0 and 1)
Using array() function

• The array() function is used to assign multiple


values to an array simultaneously.
• <?php
• $student = array(“ram”,”sham”,”yash”);
print_r($student);
• ?>
Accessing Array Elements
• To access the values from the array we can use
the following ways:
• just write the array name followed by the
index of the value you want in square
brackets.
• using a for loop.
• using a foreach loop.
• Using print_r() function.
There are two different methods are
using a foreach-loop
foreach ($array_name as $value) {
statements;
statements;
}

foreach ($array_name as $index_name => $valu


e) {
statements;
statements;
}
Example Numeric Arrays
<html>
<body>
<?php
/* First method to create array. */
$n = array( 1, 2, 3, 4, 5);
print_r($n);
echo “<p>”;
for ( $i=0;$i<count($n);$i++)
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?>
Associative Arrays
<html>

<body>

<?php

/* First method to associate create array. */

$salaries = array( “leena" => 2000,“meena" => 1000,“geeta" => 500 );

echo "Salary of leena is ". $salaries[‘leena'] . "<br />";

echo "Salary of meena is ". $salaries[‘meena']. "<br />";

echo "Salary of geeta is ". $salaries[‘geeta']. "<br />";

-----------------------------------------------------------------------------------

Output:
Associative Arrays
<html>

<body>

<?php

/* second method to associate create array. */

$salaries = array( “leena" => 2000,“meena" => 1000,“geeta" => 500 );

foreach ($salaries as $key => $value)

echo "Salary of $key = $value"."<br />";

?>
Multidimensional Arrays

<?php
$a =array(array(10,20,30),array(100,200));
echo “<pre>”;
Print_r($a);
foreach($a as $i)
{
foreach($i as $c)
{
Array functions
• count()- length of an array.
• array_sum()- sum of the elements in the array.
• array_pop()-remove element from the end.
• array_push()-add element at the end.
• array_unshift()- add element at the beginning.
• array_shift()- remove element from the
beginning.
<?php
$a=array(10,20,30);
Print_r($a);
echo "<p>";

echo "addtion= ".array_sum($a)."<br>";


echo "<p>";

array_unshift($a,14,15);
echo "adding element in the beginning ";
echo "removed element from the last".array_pop($a)."<br>";

echo "after popping element is";

Print_r($a);

echo "<p>";

echo "removed element from the last".array_push($a,100)."<br>";

echo "after pushing element is";

Print_r($a);

echo "<p>";
Passing information between pages:
• With PHP it is possible to pass information
between pages.
• To do this we make use of $_GET() function
and $_POST() function and $REQUEST
variable along with HTML forms.
• HTML form elements can be by default used
with PHP scripts.
• The $_GET ()function is used to collect values
from a form with method="get".
• The $_POST()function is used to collect values
The $_GET()function

• The $_GET()function is an array of variable names


and values sent by the HTTP GET method.
• The $_GET()function is used to collect values from a
form with method="get". Information sent from a
form with the GET method is visible to everyone (it
will be displayed in the browser's address bar) and it
has limits on the amount of information to send
(max. 100 characters).
Why use $_GET()function ?

• When using the $_GET()function all variable


names and values are displayed in the URL.
• So this method should not be used when
sending passwords or other sensitive
information!
• The HTTP GET method is not suitable on large
variable values; the value cannot exceed 100
characters.
The $_POST()function
• The The $_POST()function is used to collect values
from a form with method="post".
• The $_POST()function is an array of variable names
and values sent by the HTTP POST method.
• The $_POST()function is used to collect values from a
form with method="post".
• Information sent from a form with The $_POST()
function is invisible to others and has no limits on the
amount of information to send.
Why use $_POST()function ?
• Variables sent with HTTP POST are not shown
in the URL .
• Variables have no length limit
• However, because the variables are not
displayed in the URL, it is not possible to
bookmark the page.
Example:
welcomepage.html
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" value=“check”/>
</form>
welcome.php
<html>
<body>
<?php
$x=$_POST["name"];
$y=$_POST["age"];
echo "Welcome $x"."<br />";
echo "You are $y years old.";
?>
PHP Functions
• PHP functions are similar to other
programming languages. A function is a piece
of code which takes one more input in the
form of parameter and does some processing
and returns a value.
• They are more than 700 built-in functions in
PHP but PHP also gives you option to create
your own functions as well.
• There are two parts associated with the
function:
Creating PHP functions:
• All functions start with the word "function()"
• Name the function - It should be possible to
understand what the function does by its name. The
name can start with a letter or underscore (not a
number)
• Add a "{" - The function code starts after the
opening curly brace
• Insert the function code
• Add a "}" - The function is finished by a closing curly
brace .
• Function Syntax:
function function_name (input_variable1, input_variabl
PHP functions without parameter
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage()
PHP functions with parameter

• PHP gives you option to pass your parameters


inside a function. You can pass as many as
parameters your like. These parameters work
like variables inside your function. Following
example takes two integer parameters and
add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters
</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
PHP Functions returning value:

• A function can return a value using


the return statement in conjunction with a
value or object. return stops the execution of
the function and sends the value back to the
calling code.
<html>
<head>
<title>Writing PHP Function which returns
value</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
The end

You might also like