Python Notes for mca i year students osmania university.docx
TOT PHP DAY 1
1. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
mengembangkan Aplikasi web
menggunakan php
Riza Muhammad Nurman 1
2. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Rationale
Web applications have revolutionized the
way a business is conducted or day-to-day
tasks are performed.
These applications enable organizations
and individuals to share and access
information from anywhere and at any time.
With the phenomenal advent of open
source products owing to low development
cost and customizable source code, PHP is
fast emerging as the highly preferred
scripting languages for developing Web
Applications.
3. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Web Architecture
The components of the Web architecture are:
Client
Web server
URL
Protocols
4. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
three-tier architecture
5. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
A scripting language refers to a language that is interpreted rather
than compiled at runtime.
Consequently, scripting can be classified as:
Client-side scripting
Server-side scripting
PHP is one of the server side scripting languages that enables
creating dynamic and interactive Web applications.
INTRODUCING PHP
Some of the application areas of
PHP are:
Social networking
Project management
Content management
system
Blogs or online
communities
E-commerce
6. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
PHP ENgiNE
To process the PHP script embedded in a Web page, a PHP engine is
required.
A PHP engine parses the PHP script to generate the output that can
be read by the client.
The following figure depicts the process of interpretation of the PHP
code by the PHP engine.
7. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The following syntax is used to create the PHP script:
<?php
//code here
?>
A Web page can contain any number of PHP scripts.
Some of the common language constructs are:
echo
print()
die()
Exploring the Anatomy of a PHP Script
echo:
Is used to display an output on the screen.
For example:
<?php
echo "Welcome user";
?>
print():
Is also used to display an output.
Returns 1 on successful execution.
For example:
<?php
print("Welcome user");
?>
die:
Is used to terminate a script and print a message.
For example:
<?php
die( "Error occurred");
echo("Hello");
?>
8. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Comments:
They are used to enhance the readability of the code.
They are not executed.
Single-line comments are indicated by using the symbols, // and #.
Multi line comments are indicated by using the symbols, /* and */.
COMMENTS
9. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIAA variable:
Is used to store and manipulate data or values.
Refers to a memory location where some data value is stored.
Is declared using the ‘$’ symbol as a prefix with their name.
Rules that govern the naming of variables are:
A variable name must begin with a dollar ($) symbol.
The dollar symbol must be followed by a letter or an underscore.
A variable name can contain only letters, numbers, or an underscore.
A variable name should not contain any embedded spaces or symbols, such as ? ! @ # + - % ^ & * ( ) [ ] { }
. , ; : " ' / and .
The syntax to declare and initialize a variable is:
$<variable_name>=<value>;
For example:
$ID=101;
Using variables
10. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIAA constant:
Allows you to lock a variable with its value.
Can be defined using the define() function.
Syntax:
define (“constant_variable”,”value”);
For example:
define (“pi”,”3.14”);
The built-in function defined():
Checks whether the constant has been defined or not.
Syntax:
boolean defined(“constant_variable”);
For example:
echo defined("pi");
Using constant
11. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The variables of basic data type can contain only one value at a time.
The basic data types supported in PHP are:
Integer
Float
String
Boolean
Basic data types
12. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
array
An array:
Is a compound data type in PHP.
Represents a contiguous block of memory locations referred by a common name.
The following figure shows how an array is stored in the memory.
13. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Numeric array:
It represents a collection of individual values in a comma separated list.
Its index always starts with 0.
Syntax:
$<array_name> = array(value1,value2……);
For example:
$desig = array("HR","Developer","Manager","Accountant");
To print all the elements of an array, the built-in function print_r() is used.
For example:
print_r($desig);
The syntax for accessing the elements is:
$<variable_name> = $<array_name>[index];
For example:
echo $desig[0] . "<br>";
echo $desig[1] . "<br>";
echo $desig[2] . "<br>";
echo $desig[3] . "<br>";
Numeric array
14. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Associative array:
Is an array that has string index for all the elements.
Syntax:
<array_name> = array("key1" => "value1", "key2" => "value2");
For example:
$details = array("E101" => 20000, "E102"=>15000, "E103"=> 25000);
The syntax for accessing the elements of the associative array is:
$<variable_name> = $<array_name>[key];
For example:
$details = array("E101" => 20000, "E102" => 15000, "E103" => 25000);
echo $details['E101'] . "<br>";
echo $details['E102'] . "<br>";
echo $details['E103'] . "<br>";
Associative array
15. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Multidimensional array:
Is an array that has another array as a value of an element.
Syntax:
$<array_name> =
array(“key1”=>array(value1,value2,value3),“key2”=>array(value1,value2,value3),
…
…);
For example:
$flower_shop = array("category1" => array("lotus", 2.25, 10), "category2" =>
array("white rose", 1.75, 15), "category3" => array("red rose", 2.15, 8) );
echo $flower_shop['category1’][0] . "<br>";;
echo $flower_shop['category1'][1] . "<br>";
echo $flower_shop['category1'][2] . "<br>";
echo $flower_shop['category2'][0] . "<br>";
echo $flower_shop['category2'][1] . "<br>";
echo $flower_shop['category2'][2] . "<br>";
echo $flower_shop['category3'][0] . "<br>";
echo $flower_shop['category3'][1] . "<br>";
echo $flower_shop['category3'][2] . "<br>";
Multidimensional array
16. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
An operator:
Is a set of one or more characters that is used for computations or comparisons.
Can change one or more data values, called operands, into a new data value.
The following figure shows the operator and operands used in the expression, X+Y.
Operators in PHP can be classified into the following types:
Arithmetic
Arithmetic assignment
Increment/decrement
Comparison
Logical
Array
String
Implementing Operators
17. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Arithmetic operators supported in PHP are:
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulus)
Arithmetic assignment operators supported in PHP are:
+= (Addition assignment)
-= (Subtraction assignment)
*= (Multiplication assignment)
/= (Division assignment)
%= (Modulus assignment)
Types of operators
18. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Increment/decrement operators supported in PHP are:
++ (Increment)
-- (Decrement)
Comparison operators supported in PHP are:
== (Equal)
!= or <> (Not equal)
=== (Identical) – same data type
!== (Not Identical)
< (Less than)
> (Greater than)
<= (Less than or equal to)
>= (Greater than or equal to)
Types of operators
19. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Logical operators supported in PHP are:
&&
||
xor
!
Array operators supported in PHP are:
+ (Union) – key commons use left hand array
== (Equality)
=== (Identity) – same order, same type
!= or <> (Inequality)
!== (Non identity) – one of two arrays diff combination key / not same
order / diff type
Types of operators
20. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
String operator:
Is used for concatenation of two or more strings.
For example:
$username = “John”;
echo “Welcome ” . $username;
Operators precedence:
Is a predetermined order in which each operator in an expression is
evaluated.
Is used to avoid ambiguity in expressions.
Types of operators
The operators in precedence order from
highest to lowest are:
++ --
!
* / %
+ - .
< <= > >= <>
== != === !==
&&
||
= += -= *= /= .= %=
and
xor
HIGH
LOW
21. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Conditional constructs are decision-making statements.
The following conditional constructs can be used in a PHP script:
The if statement
The switch….case statement
Use conditional constructs
22. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The if statement :
Is used to execute a statement or a set of statements in a
script, only if the specified condition is true.
Syntax:
if (condition)
{
//statements;
}
For example:
$age=15;
if ($age>12)
{
echo "You can play the game";
}
If statements
Output
You can play the game
23. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The switch…case statement:
Is used when you have to evaluate
a variable against multiple values.
Can be used to enclose a string of
characters.
Syntax:
switch(VariableName)
{
case
ConstantExpression_1:
// statements;
break;
.
.
default:
// statements;
break;
}
The switch…case Statement
For example:
$day=5;
switch($day)
{
case 1:
echo "The day is Sunday";
break;
case 2:
echo "The day is Monday";
break;
case 3:
echo "The day is Tuesday";
break;
case 4:
echo "The day is Wednesday";
break;
case 5:
echo "The day is Thursday";
break;
case 6:
echo "The day is Friday";
break;
case 7:
echo "The day is Saturday";
break;
default:
echo "Leave";
}
Output
The day is Thursday
24. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Loops are constructs used to execute one or more lines of code repeatedly.
The following loops can be used in a PHP script:
The while loop
The do…while loop
The for loop
The foreach loop
Using loops
25. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The while loop:
Is used to repeatedly execute a block of statements till a condition evaluates to true.
Syntax:
while (expression)
{
statements;
}
For example:
$num=0;
while($num<20)
{
$num=$num+1;
echo $num;
echo "<br>";
}
The while Loop
26. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The do…while loop:
Executes the body of the loop execute at least once.
Syntax:
do
{
Statements;
}
while(condition);
For example:
$num=0;
do
{
$num=$num+1;
echo $num;
echo "<br>";
}
while($num<20);
The do…while Loop
27. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The for loop:
Executes a block of code depending on the evaluation result of the test condition.
Syntax:
for (initialize variable; test condition; step value)
{
// code block
}
For example:
$sum=0;
for ($num=100;$num<200;$num++)
{
$sum=$sum+$num;
}
echo $sum;
The for Loop
28. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The foreach loop:
Allows iterating through the elements of an array or a collection.
Iterate through the elements of an array in first-to-last order.
Syntax:
foreach ($array as $value)
{
code to be executed;
}
For example:
$books=array("Gone with the Wind", "Harry Potter", "Peter Pan", "Three States
of My Life", "Tink");
foreach ($books as $val)
{
echo $val;
echo "<br>";
}
The foreach Loop
Output
Gone with the Wind
Harry Potter
Peter Pan
Three States of My Life
Tink
29. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The date functions are used to format date and time.
Some date functions supported by PHP are:
date():
Enables you to format a date or a time or both.
Syntax:
string date(string $format[,int $timestamp])
For example:
echo date(“Y-m-d”);
date_default_timezone_set():
Sets the default time zone for the date and time functions.
Syntax:
bool date_default_timezone_set(string $timezone)
For example:
date_default_timezone_set("Asia/Calcutta");
Date function
30. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The SSI functions allow you to include the code of one PHP file into another file.
The SSI functions supported by PHP are:
include()
include_once()
require()
require_once()
SERVER SIDE INCLUDE FUNCTIONS
31. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
include():
Inserts the content of one PHP file into another PHP file during execution.
Syntax:
include(string $filename)
For example:
include('menu.php');
include_once():
Inserts the content of one PHP file into another PHP file during execution.
Will not include the file if it has already been done.
Syntax:
include_once(string $filename)
For example:
include_once('print.php');
INCLUDE
32. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
require():
Inserts the content of one PHP file into another PHP file during execution.
Generates an error and stops the execution of script if the file to be included is not found.
Syntax:
require(string $filename)
For example:
require('menu.php');
require_once():
Inserts the content of one PHP file into another PHP file during execution.
Will not include the file if it has already been done.
Syntax:
require(string $filename)
For example:
require_once('print.php');
require
33. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
A user-defined function:
Is a block of code with a unique name.
Can be invoked from various portions of a script.
Function:
Is created by using the keyword, function, followed by the function name and parentheses, ().
Syntax:
function functionName ([$Variable1], [$Variable2...])
{
//code to be executed
}
For example:
function Display()
{
echo "Hello";
}
Syntax for accessing a function is:
functionName();
For example:
Display();
Implementing User-defined Functions
34. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The scope of a variable:
Refers to the area or the region of a script where a variable is valid and accessible.
Can be classified into the following categories:
Local scope
Global scope
Static scope
Identifying the Scope of Variables
35. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Local scope:
A variable declared within a function of a PHP script has a local scope.
For example:
function show()
{
$count= 101;
echo "Value of a variable = " . $count;
}
show();
Local scope
Value of a variable = 101
Output
36. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Global scope:
A variable declared outside any function in a PHP script has a
global scope.
These variables can be accessed from anywhere in the PHP
script, but cannot be accessed inside any function.
For example:
$number1 = 10;
$number2 = 20;
function show()
{
global $number1, $number2;
$product = $number1 * $number2;
echo "Result = " . $product;
}
show();
You can access these variables inside the function by using the
global keyword with them.
Global scope
37. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Static scope:
You can preserve the current value of the variable in the memory by using the static keyword.
For example:
function show(){
static $count = 100;
echo $count;
echo "<br>";
$count++;}
show();
show();
STATIC SCOPE
100
101
Output
38. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
You need to know the various components of a Web form before retrieving and processing the information
provided in the Web form.
You need to identify the variables that can be used to retrieve the form data and the information sent by the
browser.
A Web form consists of the following basic components:
Form
Input type
Button
To retrieve values from Web form components, you can use the superglobal variables.
The superglobal variables are of the following types:
$_GET
$_POST
$_REQUEST
$_SERVER
$_FILES
RETRIEVING FORM DATA
39. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Multi valued fields:
Send multiple values to the server.
Include drop-down list and checkboxes.
End with square brackets.
The isset() function:
Is used to check whether the values are set in the fields.
Syntax:
bool isset ($var)
RETRIEVING FORM DATA
File upload fields:
These are used to upload a file.
Information about the uploaded file is stored in the $_FILES superglobal variable.
The elements of the $_FILES variable are:
Name
Type
Size
tmp_name
Error
For example:
$filesize=$_FILES["Image"] ["size"];
40. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The header() function:
Redirects the browser to a new URL using Location header:
Syntax:
header("Location:string")
For example:
header("Location:http://ThankYou.php");
REDIRECTING THE FORM
41. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Sanitizing and validating the form data includes:
Checking whether the user has filled all the fields.
Validating the data before processing it.
Sanitizing and Validating Form Data
42. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The empty() function:
Determines whether the value of a variable is empty or not.
Syntax:
bool empty($var);
For example:
if(!empty($_POST['Email'] ))
{
echo "Your email id is". $_POST['Email'];
}
else
{
echo "Please fill the email id";
}
Handling Null Values in Fields
43. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Sanitizing:
It is the process of removing invalid characters.
PHP provides the filter_var() function to filter a variable’s value.
Syntax:
filter_var($var, filter)
Commonly-used sanitize filters are:
FILTER_SANITIZE_NUMBER_INT
FILTER_SANITIZE_SPECIAL_CHARS
FILTER_SANITIZE_STRING
FILTER_SANITIZE_URL
FILTER_SANITIZE_EMAIL
FILTER_SANITIZE_NUMBER_FLOAT
For example:
$email=$_POST['Email'];
$sanitizedemail = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $sanitizedemail;
SANITIZING
44. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Validation:
It refers to checking the input data for correctness against some specified rules and criteria.
You can validate the input data by using:
Validation filters
Validation functions
Commonly-used validation filters are:
FILTER_VALIDATE_INT
FILTER_VALIDATE_EMAIL
FILTER_VALIDATE_URL
FILTER_VALIDATE_FLOAT
For example:
$email=$_POST['Email'];
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
echo "The email ID is valid";
}
else
{
echo "The email ID is not valid";
}
VALIDATION
45. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
The commonly-used validation functions are:
ctype_alnum
ctype_alpha
ctype_digit
ctype_cntrl
ctype_lower
ctype_upper
For example:
$name=$_POST['Name'];
if(!ctype_upper($name))
{
echo "Please enter the name in capital letters";
}
VALIDATION
46. Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
PHP offers a range of functions to manipulate and format string data.
The PHP functions are used to perform day-to-day operations, such as comparison and concatenation of strings.
PHP provides various built-in functions to manipulate strings.
Some of these functions are:
strlen(string $string1)
strcmp(string $string1,string $string2)
strpos(string $string1,string $substring[,int $start_pos])
strstr(string $string1,string $substring)
substr_count(string $string1,string $substring[,int $start_index][,int $length])
str_replace(string $substring,string $replace,string $string1[,resource $count])
substr(string $string1,int $start_index[,int $length])
explode(string $separator,string $string1[,int $limit])
implode([string $separator,]$array_name)
strtoupper(string $string1)
strtolower(string $string1)
str_split(string $string1[,int $length])
ord(string $string1)
chr(int $ascii_value)
strrev(string $string1)
STRING FUNCTIONS