Ostp Unit 2
Ostp Unit 2
Ostp Unit 2
3
Most servers support PHP
Download PHP for free here:
http://www.php.net/downloads.php
Download MySQL for free here:
http://www.mysql.com/downloads/index.html
Download Apache for free here:
http://httpd.apache.org/download.cgi
5
WHAT IS PHP (CONT’D)
Interpreted language, scripts are parsed at run-time
rather than compiled beforehand
Executed on the server-side
6
WHAT DOES PHP CODE LOOK LIKE?
<?php
…
?>
7
HOW IT WORKS
PHP code is usually embedded into HTML
Freely available
The PHP group provides complete source code free of
charge
Similar syntax to C, Perl
9
HISTORY – INITIAL DEVELOPMENT
Originally created by Rasmus Lerdorf
PHP originally stood for Personal Home Page
Replaces small set of Perl (Practical Extraction and Report
Language) scripts.
Perl is a general-purpose programming language originally
developed for text manipulation and now used for a wide
range of tasks including system administration, web
development, network programming, GUI development,
and more.
Used as a tool for observing traffic on webpage
PHP4
Added Zend engine. The Zend Engine is the open source
scripting engine that interprets the PHP programming
language.
Introduced 'superglobals' ($_GET, $_POST, $_REQUEST, etc)
It includes :
Significant Examples
Facebook
Wikipedia
Yahoo!
MyYearbook
Flickr
Wordpress.com
Tumblr
Flipkart etc…. 14
CREATING BASIC PHP SCRIPTS
Embedded language refers to code that is embedded within a
Web page (XHTML document)
A PHP file that does not contain any PHP code should have
an .html extension
16
CREATING PHP CODE BLOCKS
Code declaration blocks are separate sections within a Web
page that are interpreted by the scripting engine
17
STANDARD PHP SCRIPT DELIMITERS
A delimiter is a character or sequence of characters used to
mark the beginning and end of a code segment
18
THE <SCRIPT> ELEMENT
The <script> element identifies a script section in a Web page
document
<script type='text/javascript'>
function test()
{
alert("<?php echo "Testing"; ?>");
}
test();// to call the function
19
</script>
SHORT PHP SCRIPT DELIMITERS
The syntax for the short PHP script delimiters is
<? statements; ?>
Short delimiters can be disabled in a Web server’s
php.ini configuration file
PHP scripts will not work if your Web site ISP does not
support short PHP script delimiters
Short delimiters can be used in XHTML documents, but
not in XML documents
Do following change in php.ini
short_open_tag=On 20
ASP-STYLE SCRIPT DELIMITERS
The syntax for the ASP-style script delimiters is
<% statements; %>
ASP-style script delimiters can be used in XHTML
documents, but not in XML documents
ASP-style script delimiters can be enabled or disabled in the
php.ini configuration file
To enable or disable ASP-style script delimiters, assign a
value of “On” or “Off ” to the asp_tags directive in the
php.ini configuration file
21
DISPLAYING SCRIPT RESULTS (CONTINUED)
23
DISPLAYING SCRIPT RESULTS (CONTINUED)
Use the echo() and print() statements to return the results of
a PHP script within a Web page that is returned to a client
24
CREATING MULTIPLE CODE DECLARATION
BLOCKS
For multiple script sections in a document, include a
separate code declaration block for each section
...
</head>
<body>
<h1>Multiple Script Sections</h1>
<h2>First Script Section</h2>
<?php echo “<p>Output from the first script section.</p>”;
?>
<h2>Second Script Section</h2>
<?php echo “<p>Output from the second script section.</p>”
;?>
</body>
</html>
25
CREATING MULTIPLE CODE DECLARATION
BLOCKS (CONTINUED)
PHP code declaration blocks execute on a Web server before
a Web page is sent to a client
...
</head>
<body>
<h1>Multiple Script Sections</h1>
<h2>First Script Section</h2>
<p>Output from the first script section.</p>
<h2>Second Script Section</h2>
<p>Output from the second script section.</p>
</body>
</html>
26
CREATING MULTIPLE CODE DECLARATION
BLOCKS (CONTINUED)
<?php
echo “<p>Explore <strong>Africa</strong>, <br />”;
28
ADDING COMMENTS TO A PHP SCRIPT
Comments are nonprinting lines placed in code such as:
The name of the script
Your name and the date you created the program
Notes to yourself
Instructions to future programmers who might need to
modify your work
29
ADDING COMMENTS TO A PHP SCRIPT
(CONTINUED)
Line comments hide a single line of code
Add // or # before the text
Block comments hide multiple lines of code
Add /* to the first line of code
And */ after the last character in the code
# Shell-style comments
30
/* C-style comments
These can span multiple lines */
ADDING COMMENTS TO A PHP SCRIPT
(CONTINUED)
<?php
/*
This line is part of the block comment.
This line is also part of the block comment.
*/
echo “<h1>Comments Example</h1>”; // Line comments can follow code statements
// This line comment takes up an entire line.
# This is another way of creating a line comment.
/* This is another way of creating
a block comment. */
?>
31
USING VARIABLES AND CONSTANTS
The values stored in computer memory are called
variables
The name you assign to a variable is called an
identifier and it:
Must begin with a dollar sign ($)
Cannot begin with an underscore (_) or a number
Cannot include spaces
Is case sensitive
32
DECLARING AND INITIALIZING VARIABLES
Specifying and creating a variable name is called
declaring the variable
Assigning a first value to a variable is called
initializing the variable
In PHP, you must declare and initialize a variable in
the same statement:
$variable_name = value;
33
DISPLAYING VARIABLES
To print a variable with the echo() statement, pass the
variable name to the echo()
statement without enclosing it in quotation marks:
$VotingAge = 18;
Echo $VotingAge;
To print both text strings and variables, send
them to the echo() statement as individual arguments,
separated by commas:
echo "<p>The legal voting age is ", $VotingAge, ".</p>";
34
DISPLAYING VARIABLES
To print text strings and variables, you can send them to the
echo() statement as one argument enclosed in double
quotes:
echo "<p>The legal voting age is $VotingAge.</p>";
The legal voting age is 18.
To print text strings and the variable name, you can send
them to the echo() statement as one argument enclosed in
single quotes:
echo ‘<p>The legal voting age is $VotingAge.</p>’;
The legal voting age is $VotingAge
35
MODIFYING VARIABLES
You can modify a variable’s value at any point in a script
$SalesTotal = 40;
echo "<p>Your sales total is
$$SalesTotal</p>";
$SalesTotal = 50;
echo "<p>Your new sales total is
$$SalesTotal</p>";
36
WORKING WITH VARIABLES
Settype($var, “integer”)
allows you to set variable according to your wish
Gettype()
write the type of variable
(.)
Connects 2 variables of string type
strlen()
finds the length of a string
37
VARIABLES - SCOPE
regular PHP variables have a single scope – the context
within the variable is defined (function, file etc.); the scope
include required and include files
ex.: $n=4;
include “vars.php”; //$n is visible in “vars.php”
local variables from user-defined functions have a local
function scope:
$n=4;
function foo() { echo $n; } // $n is undefined here
static variables – have a local function scope, but they exist
outside the function and keep their values between calls;
ex.: 38
function test() {
static $n = 0; $n++; echo $n; }
VARIABLES – GLOBAL SCOPE
global variables declared within a function will refer to the
global version of those variables; ex.:
$a=2; $b=2;
function test() {
global $a, $b;
$c = $a + $b; //$c is here 4
}
global variables can be accessed through the $GLOBALS
array:
$c = $GLOBALS[‘a’] + $GLOBALS[‘b’];
the $GLOBALS array is an associative array with the name
of the global variable being the key and the contents of that
variable being the value of the array element; $GLOBALS
exists in any scope, this is because $GLOBALS is a 39
superglobal
VARIABLES – SUPERGLOBAL SCOPE
superglobal variables are available in all scopes throughout the script; no need to be
declared global in a local function; were introduced in PHP 4
the superglobal variables are:
$GLOBALS – contains references to all variables defined in the global scope of the
script
$_SERVER - array containing information such as headers, paths, and script locations;
built by the web server
$_GET - array of variables passed to the current script via the URL parameters
$_POST - array of variables passed to the current script via the HTTP POST method
$_FILES - array of items uploaded to the current script via the HTTP POST method
$_COOKIE - array of variables passed to the current script via HTTP Cookies
$_SESSION - array containing session variables available to the current script
$_REQUEST - array that by default contains the contents of $_GET, $_POST and
$_COOKIE
$_ENV - array of variables passed to the current script via the environment method40
if the register_global directive is on, the variables from the superglobal arrays
become available in the global scope
VARIABLES (5) – GLOBAL VS. SUPERGLOBAL
EXAMPLES
function test_global()
{
// Most predefined variables aren't "super" and require
// 'global' to be available to the functions local scope.
global $HTTP_POST_VARS;
echo $HTTP_POST_VARS['name'];
will print:
$foo in global scope: Example content
$foo in current scope: local variable 42
$_SERVER
keys:
‘PHP_SELF’ – the filename currently executed
‘SERVER_ADDR’ – the IP address of the server
‘SERVER_PROTOCOL’ – name and version of the protocol via which the
page is requested; HTTP/1.1
‘REQUEST_METHOD’ – the request method
‘QUERY_STRING’ – the query string
‘DOCUMENT_ROOT’ – the document root under which the current script
is executed
‘REMOTE_ADDR’ – the client IP address
‘REMOTE_PORT’ – the client port
43
‘HTTP_ACCEPT’ – the HTTP accept field of the HTTP protocol
etc.
$_GET
an html example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
after submit, the URL is:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
the ‘welcome.php’ file:
Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
44
$_POST
an html example
<form action="welcome.php" method=“post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
after submit, the URL is:
http://www.w3schools.com/welcome.php
the ‘welcome.php’ file:
Welcome <?php echo $_POST["fname"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old!
45
DEFINING CONSTANTS
A constant contains information that does not
change during the course of program execution
Constant names do not begin with a dollar sign
Constant names use all uppercase letters
Use the define() function to create a constant
define("CONSTANT_NAME", value);
define("VOTING_AGE",18);
define("VOTING_AGE",18,TRUE);
The value you pass to the define() function can be
a text string, number, or Boolean value
46
WORKING WITH DATA TYPES
A data type is the specific category of information
that a variable contains
Data types that can be assigned only a single value are
called primitive types
47
WORKING WITH DATA TYPES (CONTINUED)
The PHP language supports:
A resource data type – a special variable that holds a
reference to an external resource such
as a database or XML file
Reference or composite data types, which contain
multiple values or complex types of information
Two reference data types: arrays and objects
48
NUMERIC DATA TYPES
PHP supports two numeric data types:
An integer is a positive or negative number with no
decimal places (-250, 2, 100, 10,000)
A floating-point number is a number that contains
decimal places or that is written in exponential
notation (-6.16, 3.17, 2.7541)
Exponential notation, or scientific notation, is short for
writing very large numbers or numbers with many
decimal places (2.0e11)
49
BOOLEAN VALUES
A Boolean value is a value of true or false
It decides which part of a program should execute
and which part should compare data
In PHP programming, you can only use true or false
50
BUILDING EXPRESSIONS
An expression is a literal value or variable that can
be evaluated by the PHP scripting engine to produce a
result
Operands are variables and literals contained in an
expression
A literal is a value such as a literal string or a number
51
BUILDING EXPRESSIONS (CONTINUED)
52
BUILDING EXPRESSIONS (CONTINUED)
53
ARITHMETIC OPERATORS
Arithmetic operators are used in PHP to perform
mathematical calculations (+ - x ÷)
54
ARITHMETIC OPERATORS (CONTINUED)
$DivisionResult = 15 / 6;
$ModulusResult = 15 % 6;
echo "<p>15 divided by 6 is
$DivisionResult.</p>"; // prints '2.5'
echo "The whole number 6 goes into 15 twice, with a
remainder of $ModulusResult.</p>"; // prints '3'
55
Figure : Division and modulus expressions
ARITHMETIC UNARY OPERATORS
The increment (++) and decrement (--) unary
operators can be used as prefix or postfix operators
A prefix operator is placed before a variable
56
ARITHMETIC UNARY OPERATORS (CONTINUED)
57
ARITHMETIC UNARY OPERATORS (CONTINUED)
58
Arithmetic Unary Operators (continued)
60
ASSIGNMENT OPERATORS
Assignment operators are used for assigning
a value to a variable:
$MyFavoriteSuperHero = "Superman";
$MyFavoriteSuperHero = "Batman";
Compound assignment operators perform
mathematical calculations on variables and literal
values in an expression, and then assign
a new value to the left operand
61
ASSIGNMENT OPERATORS (CONTINUED)
62
ASSIGNMENT OPERATORS
$x = 100;
$y = 200;
$x += $y;
echo $x;
$x = 10;
$y = 7;
$x -= $y;
echo $x;
63
COMPARISON AND CONDITIONAL OPERATORS
Comparison operators are used to compare two operands
and determine how one operand compares to another
A Boolean value of true or false is returned after two
operands are compared
The comparison operator compares values, whereas the
assignment operator assigns values
Comparison operators are used with conditional
statements and looping statements
64
COMPARISON AND CONDITIONAL OPERATORS
(CONTINUED)
65
COMPARISON AND CONDITIONAL OPERATORS
(CONTINUED)
The conditional operator executes one of two
expressions, based on the results of a conditional
expression
The syntax for the conditional operator is:
conditional expression ? expression1 :
expression2;
If the conditional expression evaluates to true,
expression1 executes
If the conditional expression evaluates to false,
expression2 executes
66
COMPARISON AND CONDITIONAL OPERATORS
(CONTINUED)
$BlackjackPlayer1 = 20;
($BlackjackPlayer1 <= 21) ? $Result =
"Player 1 is still in the game. " :
$Result =
"Player 1 is out of the action.";
echo "<p>", $Result, "</p>";
68
LOGICAL OPERATORS
<?php
$TrueValue = true;
$FalseValue = false;
!$TrueValue ? $ReturnValue = "true" :
$ReturnValue = "false";
echo "<p>$ReturnValue<br />";
!$FalseValue ? $ReturnValue = "true" :
$ReturnValue = "false";
echo "$ReturnValue<br />";
$TrueValue || $FalseValue ? $ReturnValue = "true" :
$ReturnValue = "false";
echo "$ReturnValue<br />";
$TrueValue && $FalseValue ? $ReturnValue = "true" :
$ReturnValue = "false";
echo "$ReturnValue<br />";
?>
69
SPECIAL OPERATORS
70
TYPE CASTING
Casting or type casting copies the value contained in
a variable of one data type into a variable of another
data type
The PHP syntax for casting variables is:
$NewVariable = (new_type)
$OldVariable;
(new_type) refers to the type-casting operator
representing the type to which you want to cast the
variable
71
GETTYPE()SETTYPE()FUNCTION
gettype($var_name): Returns one of the following strings,
depending on the data type:
Boolean
Integer
Double
String
Array
Object
Resource
NULL
Unknown type
<?php
$a=5.2;
echo gettype($a);
echo "<br>";
settype($a,"int");
echo gettype($a); 72
?>
TYPE VALIDATION FUNCTIONS
is_int() - Find whether the type of a variable is integer
is_bool() - Finds out whether a variable is a boolean
73
EXAMPLE
<?php
$values = array(23, "23", 23.5, "23.5", null, true, false);
foreach ($values as $value) {
echo "is_int(";
var_export($value);
echo ") = ";
var_dump(is_int($value));
}
?>
The above example will output:
is_int(23) = bool(true)
is_int('23') = bool(false)
is_int(23.5) = bool(false)
is_int('23.5') = bool(false)
is_int(NULL) = bool(false)
is_int(true) = bool(false)
is_int(false) = bool(false)
74
UNDERSTANDING OPERATOR PRECEDENCE
Operator precedence refers to the order in which
operations in an expression are evaluated
Associativity is the order in which operators of equal
precedence execute
Associativity is evaluated on a left-to-right or a right-
to-left basis
75
UNDERSTANDING OPERATOR PRECEDENCE
(CONTINUED)
76
CONDITIONAL STATEMENTS
If/ else
After each statement stands (;)
If more than one command should be executed, use curly
braces { }
Switch / break
Used for choosing one possibility from multiple cases
Switch ($var )
{
case : “x” : echo “good”;
break;
default : echo “wrong input” ; 77
}
LOOPS
while - loops through a block of code 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
foreach -
78
THE WHILE STATEMENT
while (condition)
code to be executed;
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?> 79
THE DO...WHILE STATEMENT
do
{
code to be executed;
}
while (condition);
80
THE FOR STATEMENT
for (initialization; condition; increment)
{ code to be executed; }
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
81
THE FOREACH STATEMENT
<?php
$string = 'We have a string';
$array = explode(" ",$string);
foreach($array as $value)
echo $value . '<br />';
?>
82
BREAK AND CONTINUE
break ends execution of the current for,
foreach while, do..while or switch structure.
83
WHY FUNCTIONS?
PHP has lots of built-in functions that we use all
the time
We write out own functions when our code reaches
a certain level of complexity
84
TO FUNCTION OR NOT TO FUNCTION...
Organize your code into “paragraphs” - capture a
complete thought and “name it”
Don’t repeat yourself - make it work once and then
reuse it
If something gets too long or complex, break up
logical chunks and put those chunks in functions
Make a library of common stuff that you do over and
over - perhaps share this with your friends...
85
BUILT-IN FUNCTIONS...
function greet() {
print "Hello\n";
} Hello
Hello
greet(); Hello
greet(); 87
greet();
CHOOSING FUNCTION NAMES
Much like variable names - but do not start with a
dollar sign
Start with a letter or underscore - consist of letters,
numbers, and underscores ( _ )
Avoid built in function names
Case does not matter – but please do not take
advantage of this
88
RETURN VALUES
function greeting() {
return "Hello"; Hello Glenn
} Hello Sally
print greeting() . " Glenn\n"; 89
print greeting() . " Sally\n";
ARGUMENTS
function howdy($lang) {
if ( $lang == 'es' ) return "Hello";
if ( $lang == 'fr' ) return “morning";
return "How are you?"; Hello john
} morning Rita
90
print howdy('es') . " john\n";
print howdy('fr') . " Rita\n";
OPTIONAL ARGUMENTS
function howdy($lang='es') {
if ( $lang == 'es' ) return "Hello";
if ( $lang == 'fr' ) return “morning";
return "Hello"; Hollo john
} morning Rita
function double($alias) {
$alias = $alias * 2;
return $alias; Value = 10 Doubled = 20
}
$val = 10;
92
$dval = double($val);
echo "Value = $val Doubled = $dval\n";
CALL BY REFERENCE
function triple(&$realthing) {
$realthing = $realthing * 3;
}
$val = 10;
triple($val);
93
echo "Triple = $val\n"; Triple = 30
PHP ARRAYS
WHAT IS AN ARRAY?
-An array can store one or more values in a
single variable name.
95
3 KINDS OF ARRAYS
1) Numeric Array
2) Associative Array
3) Multidimensional Array
96
NUMERIC ARRAY
97
AUTOMATICALLY
Example:
$names = array("Peter","Quagmire","Joe");
98
MUNUALLY
Example:
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
99
THE ID CAN BE USED IN A SCRIPT
Example:
<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
101
ASSOCIATIVE ARRAYS
-An associative array, each ID key is associated with a value.
102
EXAMPLE
Using an array to assign an age to a person.
$ages[’Brent'] = ”42";
$ages[’Andrew'] = ”25";
$ages['Joshua'] = ”16";
103
THE ID CAN BE USED IN A SCRIPT
<?php
$ages[‘Brent’] = ”42";
$ages[‘Andrew’] = ”25";
$ages[‘Joshua’] = ”16";
104
OUTPUT
105
MULTIDIMENSIONAL ARRAYS
- In a multidimensional array, each element in
the main array can also be an array.
106
EXAMPLE
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan" ),
"Quagmire"=>array ( "Glenn" ),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
); 107
OUPUT
Array
(
[Griffin] => Array echo "Is " . $families['Griffin'][2] .
( " a part of the Griffin family?";
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array Is Megan a part of the Griffin family?
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
108
)
END OF UNIT-2 : SUMMARY
Background information of PHP History and Basics of
PHP
Using variables, operators and expressions