SlideShare a Scribd company logo
1 of 46
Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
mengembangkan Aplikasi web
menggunakan php
Riza Muhammad Nurman 1
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.
Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
Web Architecture
The components of the Web architecture are:
 Client
 Web server
 URL
 Protocols
Center for Computing and
Information Technology
FAKULTAS TEKNIK
UNIVERSITAS INDONESIA
three-tier architecture
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
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.
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");
?>
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
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
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
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
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.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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"];
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
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
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
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
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
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
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

More Related Content

What's hot

Php Security3895
Php Security3895Php Security3895
Php Security3895
Aung Khant
 
Web app development_php_04
Web app development_php_04Web app development_php_04
Web app development_php_04
Hassen Poreya
 

What's hot (20)

Php Security3895
Php Security3895Php Security3895
Php Security3895
 
Web technology html5 php_mysql
Web technology html5 php_mysqlWeb technology html5 php_mysql
Web technology html5 php_mysql
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Php basics
Php basicsPhp basics
Php basics
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
PHP Training Part1
PHP Training Part1PHP Training Part1
PHP Training Part1
 
Web app development_php_04
Web app development_php_04Web app development_php_04
Web app development_php_04
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
php basics
php basicsphp basics
php basics
 
Perl
PerlPerl
Perl
 
Php
PhpPhp
Php
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
Basic php 5
Basic php 5Basic php 5
Basic php 5
 

Similar to TOT PHP DAY 1

Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 

Similar to TOT PHP DAY 1 (20)

Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Php
PhpPhp
Php
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbai
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Unit 1
Unit 1Unit 1
Unit 1
 
8 covid19 - chp 07 - php array (shared)
8   covid19 - chp 07 - php array (shared)8   covid19 - chp 07 - php array (shared)
8 covid19 - chp 07 - php array (shared)
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
php&mysql with Ethical Hacking
php&mysql with Ethical Hackingphp&mysql with Ethical Hacking
php&mysql with Ethical Hacking
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
php
phpphp
php
 
Php manish
Php manishPhp manish
Php manish
 
Php mysql training-in-mumbai
Php mysql training-in-mumbaiPhp mysql training-in-mumbai
Php mysql training-in-mumbai
 
Compiler design Introduction
Compiler design IntroductionCompiler design Introduction
Compiler design Introduction
 
Introduction to Perl Programming
Introduction to Perl ProgrammingIntroduction to Perl Programming
Introduction to Perl Programming
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Apache Velocity
Apache VelocityApache Velocity
Apache Velocity
 

More from Riza Nurman

More from Riza Nurman (20)

SE - Chapter 9 Pemeliharaan Perangkat Lunak
SE - Chapter 9 Pemeliharaan Perangkat LunakSE - Chapter 9 Pemeliharaan Perangkat Lunak
SE - Chapter 9 Pemeliharaan Perangkat Lunak
 
SE - Chapter 8 Strategi Pengujian Perangkat Lunak
SE - Chapter 8 Strategi Pengujian Perangkat LunakSE - Chapter 8 Strategi Pengujian Perangkat Lunak
SE - Chapter 8 Strategi Pengujian Perangkat Lunak
 
SE - Chapter 7 Teknik Pengujian Perangkat Lunak
SE - Chapter 7 Teknik Pengujian Perangkat LunakSE - Chapter 7 Teknik Pengujian Perangkat Lunak
SE - Chapter 7 Teknik Pengujian Perangkat Lunak
 
SE - Chapter 6 Tim dan Kualitas Perangkat Lunak
SE - Chapter 6 Tim dan Kualitas Perangkat LunakSE - Chapter 6 Tim dan Kualitas Perangkat Lunak
SE - Chapter 6 Tim dan Kualitas Perangkat Lunak
 
XML - Chapter 8 WEB SERVICES
XML - Chapter 8 WEB SERVICESXML - Chapter 8 WEB SERVICES
XML - Chapter 8 WEB SERVICES
 
XML - Chapter 7 XML DAN DATABASE
XML - Chapter 7 XML DAN DATABASEXML - Chapter 7 XML DAN DATABASE
XML - Chapter 7 XML DAN DATABASE
 
XML - Chapter 6 SIMPLE API FOR XML (SAX)
XML - Chapter 6 SIMPLE API FOR XML (SAX)XML - Chapter 6 SIMPLE API FOR XML (SAX)
XML - Chapter 6 SIMPLE API FOR XML (SAX)
 
XML - Chapter 5 XML DOM
XML - Chapter 5 XML DOMXML - Chapter 5 XML DOM
XML - Chapter 5 XML DOM
 
DBA BAB 5 - Keamanan Database
DBA BAB 5 - Keamanan DatabaseDBA BAB 5 - Keamanan Database
DBA BAB 5 - Keamanan Database
 
DBA BAB 4 - Recovery Data
DBA BAB 4 - Recovery DataDBA BAB 4 - Recovery Data
DBA BAB 4 - Recovery Data
 
DBA BAB 3 - Manage Database
DBA BAB 3 - Manage DatabaseDBA BAB 3 - Manage Database
DBA BAB 3 - Manage Database
 
DBA BAB 2 - INSTALASI DAN UPGRADE SQL SERVER 2005
DBA BAB 2 - INSTALASI DAN UPGRADE SQL SERVER 2005DBA BAB 2 - INSTALASI DAN UPGRADE SQL SERVER 2005
DBA BAB 2 - INSTALASI DAN UPGRADE SQL SERVER 2005
 
DBA BAB 1 - Pengenalan Database Administrator
DBA BAB 1 - Pengenalan Database AdministratorDBA BAB 1 - Pengenalan Database Administrator
DBA BAB 1 - Pengenalan Database Administrator
 
RMN - XML Source Code
RMN -  XML Source CodeRMN -  XML Source Code
RMN - XML Source Code
 
XML - Chapter 4
XML - Chapter 4XML - Chapter 4
XML - Chapter 4
 
XML - Chapter 3
XML - Chapter 3XML - Chapter 3
XML - Chapter 3
 
XML - Chapter 2
XML - Chapter 2XML - Chapter 2
XML - Chapter 2
 
XML - Chapter 1
XML - Chapter 1XML - Chapter 1
XML - Chapter 1
 
ADP - Chapter 5 Exploring JavaServer Pages Technology
ADP - Chapter 5 Exploring JavaServer Pages TechnologyADP - Chapter 5 Exploring JavaServer Pages Technology
ADP - Chapter 5 Exploring JavaServer Pages Technology
 
ADP - Chapter 4 Managing Sessions
ADP - Chapter 4 Managing SessionsADP - Chapter 4 Managing Sessions
ADP - Chapter 4 Managing Sessions
 

Recently uploaded

QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
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