SlideShare a Scribd company logo
Pre Processor Hypertext
By:- Farzad FWadia
Agenda
Core PHP
· Software Engineering
· Web Programming
· Introduction to PHP
· HTML and CSS
· PHP as a Scripting Language
· Variables and Expressions in PHP
· PHP Operators
· Conditional Test, Events and Flows in PHP
· Functions and Arrays using PHP
· PHP Syntax and Variables
· String functions
· DBMS&RDBS
· MYSQL database and queries
· Sessions and Cookies in PHP
· Files and Directory Access
· Handling e-mail
· Use of JavaScript, AJAX and XML
Program..
 Sequence of instructions written for specific purpose
 Like program to find out factorial of number
 Can be written in higher level programming languages

that human can understand
 Those programs are translated to computer
understandable languages
 Task will be done by special tool called compiler
 Compiler will convert higher level language code to

lower language code like binary code
 Most prior programming language was ‘C’
 Rules & format that should be followed while writing
program are called syntax
 Consider program to print “Hello!” on screen
void main()
{
printf(“Hello!”);
}
 Void main(), function and entry point of compilation
 Part within two curly brackets, is body of function
 Printf(), function to print sequence of characters on
screen
 Any programming language having three part

Data types
2. Keywords
3. Operators
 Data types are like int, float, double
 Keyword are like printf, main, if, else
 The words that are pre-defined for compiler are
keyword
 Keywords can not be used to define variable
1.
 We can define variable of data type
 Like int a; then ‘a’ will hold value of type int and is

called variable
 Programs can have different type of statements like
conditional statements and looping statements
 Conditional statements are for checking some
condition
Conditional Statements…
 Conditional statements controls the sequence of

statements, depending on the condition
 Relational operators allow comparing two values.
1. == is equal to
2. != not equal to
3. < less than
4. > greater than
5. <= less than or equal to
6. >= greater than or equal to
SIMPLE IF STATEMENT
 It execute if condition is TRUE
 Syntax:

if(condition)
{
Statement1;
.....
Statement n;
}
main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b) {
printf(“n a is greater than b”); }
}
 OUTPUT:
Enter a,b values:20 10
a is greater than b
IF-ELSE STATEMENT
 It execute IF condition is TRUE.IF condition is FLASE it execute ELSE

part
 Syntax:
if(condition)
{
Statement1;
.....
Statement n;
}
else
{
Statement1;
.....
Statement n;
}
main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b) {
printf(“n a is greater than b”); }
else {
printf(“nb is greater than b”); }
}
 OUTPUT:
Enter a,b values:10 20
b is greater than a
IF-ELSE IF STATEMENT:
 It execute IF condition is TRUE.IF condition is FLASE it checks ELSE IF

part .ELSE IF is true then execute ELSE IF PART. This is also false it
goes to ELSE part.
 Syntax:
if(condition)
{
Statementn;
}
else if
{
Statementn;
}
else
{
Statement n;
}
main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b) {
printf(“n a is greater than b”); }
else if(b>a) {
printf(“nb is greater than b”); }
else {
printf(“n a is equal to b”); }
}
 OUTPUT:
Enter a,b values:10 10
a is equal to b
NESTED IF STATEMENT
 To check one conditoin within another.
 Take care of brace brackets within the conditions.
 Synatax:

if(condition)
{
if(condition)
{
Statement n;
}
}
else
{
Statement n;
}
main()
{

}

int a,b;
printf(“n Enter a and b values:”);
scanf(“%d %d ”,&a,&b);
if(a>b) {
if((a!=0) && (b!=0)) {
printf(“na and b both are +ve and a >b);
else {

printf(“n a is greater than b only”) ; } }
else {
printf(“ na is less than b”); }
}
 Output:
Enter a and b values:30 20
a and b both are +ve and a > b
Switch..case
 The switch statement is much like a nested if .. else statement.
 switch statement can be slightly more efficient and easier to

read.
 Syntax :
switch( expression )
{
case constant-expression1:
statements1;
case constant-expression2:
statements2;
default :
statements4;
}
main()
{
char Grade = ‘B’;
switch( Grade )
{
case 'A' :
printf( "Excellentn" ); break;
case 'B' :
printf( "Goodn" ); break;
case 'C' :
printf( "OKn" ); break;
case 'D' :
printf( "Mmmmm....n" ); break;
default :
printf( "What is your grade anyway?" );
break;
}
}
Looping…
 Loops provide a way to repeat commands and control how









many times they are repeated.
C provides a number of looping way.
while loop
A while statement is like a repeating if statement.
Like an If statement, if the test condition is true: the
statements get executed.
The difference is that after the statements have been
executed, the test condition is checked again.
If it is still true the statements get executed again.
This cycle repeats until the test condition evaluates to false.
 Basic syntax of while loop is as follows:

while ( expression )
{
Single statement or Block of statements;
}
 Will check for expression, until its true when it gets
false execution will be stop
main()
{
int i = 5;
while ( i > 0 ) {
printf("Hello %dn", i );
i = i -1; }
}
 Output
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1
Do..While
 do ... while is just like a while loop except that the test

condition is checked at the end of the loop rather than
the start.
 This has the effect that the content of the loop are
always executed at least once.
 Basic syntax of do...while loop is as follows:
do {
Single statement or Block of statements;
}
while(expression);

Version 1.4
main()
{
int i = 5;
do{
printf("Hello %dn", i );
i = i -1; }
while ( i > 0 );
}
 Output
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1
For Loop…
 for loop is similar to while, it's just written differently.

for statements are often used to proccess lists such a
range of numbers:
 Basic syntax of for loop is as follows:
for( initialization; condition; increment)
{ Single statement or Block of statements;
}
main()
{
int i; int j = 5;
for( i = 0; i <= j; i ++ )
{
printf("Hello %dn", i );
}
}
 Output
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Break & Continue…
 C provides two commands to control how we loop:
 break -- exit form loop or switch.
 continue -- skip 1 iteration of loop.
 Break is used with switch case
main()
{
int i; int j = 5;
for( i = 0; i <= j; i ++ ) {
if( i == 3 )
{
break;
}
printf("Hello %dn", i ); }
}
 Output
Hello 0
Hello 1
Hello 2
Version 1.4
Continue Example..
main()
{
int i; int j = 5;
for( i = 0; i <= j; i ++ )
{
if( i == 3 )
{
continue;
}
printf("Hello %dn", i );
}
}
 Output
Hello 0
Hello 1
Hello 2
Hello 4
Hello 5

Version 1.4
Functions…
 A function is a module or block of program code which

deals with a particular task.
 Making functions is a way of isolating one block of
code from other independent blocks of code.
 Functions serve two purposes.
1.

2.

They allow a programmer to say: `this piece of code
does a specific job which stands by itself and should
not be mixed up with anything else',
Second they make a block of code reusable since a
function can be reused in many different contexts
without repeating parts of the program text.
Version 1.4
int add( int p1, int p2 ); //function declaration
void main()
{
int a = 10;
int b = 20, c;
c = add(a,b); //call to function
printf(“Addition is : %d”, c);
}
int add( int p1, int p2 ) //function definition
{
return (p1+p2);
}
Version 1.4
Exercise…
1.
2.
3.

4.
5.

Find out factorial of given number
Check whether given number is prime number or
not
Check whether given number is Armstrong number
or not
Calculate some of first 100 even numbers
Prepare calculator using switch

Version 1.4
OOPS Fundamentals…
 Class – group of data members & member functions
 Like person can be class having data members height

and weight and member functions as get_details() and
put_details() to manipulate on details
 Class is nothing until you create it’s object
 Object – instantiates class allocates memory

Version 1.4
OOPS Fundamentals…
 Access to data members & member functions can be

done using object only (if they are not static!)
 OOPS features are
1.
2.
3.
4.
5.

Encapsulation
Data hiding
Data reusability
Overloading (polymorphism)
Overriding

Version 1.4
OOPS Features…
 Encapsulation – making one group of data members &

member functions
 Can be done through class
 Then group of data members & Member functions will
be available just by creating object.

Version 1.4
OOPS Features…
 Data Hiding – can be done through access modifiers
 Access modifiers are private, public, protected and

internal
 Private members or member function won’t be
available outside class
 Public – available all over in program outside class also

Version 1.4
OOPS Features…
 Protected – members that are available in class as well

as in it’s child class
 Private for another class
 Protected access modifier comes only when
inheritance is in picture
 Internal is used with assembly creation

Version 1.4
class employee
//Class Declaration
{
private:
char empname[50];
int empno;
public:
void getvalue()
{
cout<<"INPUT Employee Name:";
cin>>empname;
cout<<"INPUT Employee Number:";
cin>>empno; }
void displayvalue()
{
cout<<"Employee Name:"<<empname<<endl;
cout<<"Employee Number:"<<empno<<endl;
};
main()
{

employee e1;
e1.getvalue();
e1.displayvalue();

//Creation of Object

}
Version 1.4

}
OOPS Features…
 Overloading – taking different output of one method

or operator based on parameters and return types
 Like add() method performs addition and add(int a,int
b) performs addition of ‘a’ and ‘b’ passed when calling
 Also, + operator performs addition of two numbers as
well as concatenation of strings

Version 1.4
class arith
{
public:
void calc(int num1)
{
cout<<"Square of a given number: " <<num1*num1 <<endl;
}

};

void calc(int num1, int num2 )
{
cout<<"Product of two whole numbers: " <<num1*num2 <<endl;
}

int main() //begin of main function
{
arith a;
a.calc(5);
a.calc(6,7);
}
 This is example of method overloading, output will be
Square of given number : 25
Product of two whole numbers : 42

Version 1.4
OOPS Features…
 Data Reusability – helps in saving developers time
 You can use already created class to crate new one
 Called inheritance
 Already existing class is base class and new created is

derived class
 Base class members can be available in derived class
and to access them create object of derived class
 Like from parent to child

Version 1.4
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
class CRectangle: public CPolygon {
public: int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public: int area ()
{ return (width * height / 2); } };
int main () {
CRectangle rect;
CTriangle trgl; rect.set_values (4,5);
trgl.set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
Version 1.4
OOPS Features…
 In C++, overriding is a concept used in inheritance which involves a

base class implementation of a method.
 Then in a subclass, you would make another implementation of the
method. This is overriding. Here is a simple example.
class Base
{
public:
virtual void DoSomething() {x = x + 5;}
private:
int x;
};
class Derived : public Base
{
public:
virtual void DoSomething() { y = y + 5; Base::DoSomething(); }
private:
int y;
};
Version 1.4
What is Website?
 Website – Everyday you visit on internet
 Follows some rules & regulations i.e. client-server

architecture standard
 Websites – providing information from anywhere in
world

Version 1.4
Client-Server…

Version 1.4
Client-Server…
 Client – end user’s computer that runs software or

website
 Server – area in host or remote computer to which
client communicates
 Network – means of communication
 Can be HTTP(for www), FTP(machine to machine
transfer),SMTP(mail transfer)

Version 1.4
Website – basic parts
 Websites are consist of three parts
 GUI – web pages that you visit
 Coding – logic that provides functionality or makes

website dynamic
 Database – manages data provided by end user
 For GUI building HTML is used from long time

Version 1.4
HTML…
 HTML is the "mother tongue" of your browser.

 HTML – Hypertext Markup Language
 HTML is a language, which makes it possible to
present information on the Internet.
 What you see when you view a page on the
Internet is your browser's interpretation of HTML.
 To see the HTML code of a page on the Internet,
simply click "View" in the top menu of your

browser and choose "Source".
Version 1.4
HTML…
 HTML documents are defined by HTML elements.
 An HTML element starts with a start tag / opening

tag
 An HTML element ends with an end tag / closing tag
 The element content is everything between the start
and the end tag
 Some HTML elements have empty content
 Empty elements are closed in the start tag
 Most HTML elements can have attributes
 Ex : <p>This is paragraph</p>
Version 1.4
HTML…
 Attributes provide additional information about

HTML elements.
 Attributes provide additional information about an
element
 Attributes are always specified in the start tag
 Attributes come in name/value pairs like:
name="value“
 For ex: <p id=“p1”>This is paragraph</p>

Version 1.4
<html>
<head>
<title>First Application</title>
</head>
<body>
<p>This is paragraph</p>
</body>
</html>

Version 1.4
Explanation…
 Content between <html> and </html> is considered as

html content
 Content between <head> and </head> will be
considered as head part
 <title> and </title> is title of page that will be shown
in browser
 <body> and </body> is part of page that will be filled
with controls

Version 1.4
Database…
 Back end part of website
 Used to maintain information provided by users
 Built up with list of tables, tables having rows and

columns
 Data in cells are records
 When tables are connected in database system it is
RDBMS.

Version 1.4
Database…
 A DBMS that follows rules of Dr.E.F.Codd is RDBMS
 RDBMS stores data in form of tables and relation ship

between those tables in form of tables
 Ideally there is no DBMS exist that follows all rules of
E.F.Codd!

Version 1.4
Example…

Version 1.4
Database…
 Queries – sentences executed on database for data

manipulation
 Will be handled by database engines and will perform
action on data that are stored on database server
 Ex are create, alter, insert, update, delete etc
 SQL – structured query language is used for this

Version 1.4
SQL
 DDL – data definition Language
 Commands are : create, alter, truncate, drop
 Syntax :

create table table_name(col_name datatype(size)…);
 Example :
Create table Person_Master(name nvarchar(50));

Version 1.4
SQL
 DML – data manipulation language
 Like insert, update, delete
 Syntax:

insert into table_name(col1,col2,..coln)
values(val1,val2,..valn);
 Example:
insert into Person_Master(name) values(‘name1’);

Version 1.4
SQL
 Update Syntax:

update table_name set col1=val1, col2=val2 where col =
val;
 Ex :
update Person_Master set name = ‘name1’ where ID=1;
 It will set name to ‘name1’ for which ID is 1

Version 1.4
SQL
 Delete syntax :

delete from table_name where condition;
 Example :
delete from Person_Master where ID=1;
 It will delete whole row for which ID is 1
 It is conditional delete operation
 To delete all rows simply omit the condition

Version 1.4
SQL
 Select syntax :

select * from table_name;
 It will select all rows from specified table
 To select particular row
select * from table_name where condition;
 To select particular column
select col1,col2 from table_name;

Version 1.4
Database…
 Constrains – terms that needs to be satisfied on data
 For ex all students must have unique roll number
 Can be defined as primary key, foreign key, unique key

etc.
 Primary key – column of table whose value can be used
to uniquely identify records

Version 1.4
Database…
 Foreign key – column inside table that is primary key

of another table
 Unique key – like primary key can be used to uniquely
identify a record
 Difference between primary key and unique key is
primary key will never allow null where as unique key
will allow it for once

Version 1.4
Normalization…
 The process of structuring data to minimize

duplication and inconsistencies.
 The process usually involves breaking down the single
table into two or more tables and defining
relationships between those tables.
 Normalization is usually done in stages.
 Most people in creating database, never need to go to
beyond the third level of normalization.

Version 1.4
1NF
 Eliminate duplicative columns from the same table.
 Create separate tables for each group related data and

identify each row with a unique columns.
 In this, one table will be divided in two tables with
relevant contents

Version 1.4
2NF
 Once 1NF has been done then and only then 2NF can

be done
 In this, provide key constrains to the columns of tables
based on uniqueness
 Like assign primary key to one table column and refer
this as foreign key in another table

Version 1.4
3NF
 Only after 2NF, third normalization can be done
 In this, further more analyze tables and divide them

for data uniqueness

Version 1.4
SDLC…
 For project development rules & regulation need to be

followed for best quality output at defined time limit
 Rules are Software Development Life Cycle – SDLC
 It’s part of software engineering
 Six rules to be followed…

Version 1.4
1.
2.
3.
4.
5.
6.

Requirement Gathering
Analysis & SRS
Designing
Implementation (Coding)
Testing
Maintenance
SDLC…
1. Requirement collection




Phase of collecting requirements from client
Will be done by business analyst of company
He will create questioner, in which put answers from client

2. Analysis & SRS (Software Requirement Specification)





Collected requirements will be analyzed for time limit,
budget and market trade
Will be filtered and SRS will be created as result
Will be discussed with client

Version 1.4
SDLC…






1.




Based on requirements users, their activities and flow of data,
modules will be defined
Will be done by system analyst
Based on diagrams all will be done
Main diagrams are use-case, DFD and flow charts

USE-CASE
Have to define users and their tasks
Like website is college management system

Version 1.4
SDLC…
 User is student having activities registration, login,

view & download assignments, view fees details, view
time table etc.
 Can be shown in use-case as given below

Version 1.4
Registration
Login
View & Download
Assignment
View Result
Student
View Timetable

Version 1.4
SDLC…
 Once actions are defined, need to divide project in

modules
 DFD is used for this
 DFD – Data Flow Diagrams
 Graphical representation of flow of data inside
application can also be used for visualization and data
processing

Version 1.4
SDLC…
 DFD elements are..

External Entity
2. Process
3. Data Flow
4. Data Store
1.

Version 1.4
SDLC…
1.




External entity
Can be user or external system that performs some
process or activity in project
Symbolized with rectangle
Like, we have entity ‘admin’ then symbol will be

Admin
Version 1.4
SDLC…
2. Process
 Work or action taken on incoming data to produce
output
 Each process must have input and output
 Symbolized as

1. Login
output
input
Version 1.4
SDLC…
3. Data Flow
 Can be used to show input and output of data
 Should be named uniquely and don’t include word
‘data’
 Names can be ‘payment’, ‘order’, ’complaint’ etc
 Symbolized as

Payment
Version 1.4
SDLC….
4. Data Store
 Can be used to show database tables
 Only process may connect data stores
 There can be two or more process sharing same data
store
 Symbolized as

Registration_Master

Version 1.4
DFD Rules…
 6 rules to follow
 Consider data flow diagram as given below

Version 1.4
Version 1.4
Rule 1
 Each process must have data flowing into it and

coming out from it

Version 1.4
Rule 2
 Each data store must have data going inside and data

coming outside

Version 1.4
Rule 3
 A data flow out of a process should have some relevance to

one or more of the data flows into a process

Version 1.4
Rule 3
 In process 3 all data flows are connected to process

claim.
 The claim decision can not be made until the claim
form has been submitted and the assessor makes a
recommendation

Version 1.4
Rule 4
 Data stored in system must go through a process

Version 1.4
Rule 5
 Two data stores can’t communicate with each other

unless process is involved in between

Version 1.4
Rule 6
 The Process in DFD must be linked to either another

process or a data store
 A process can’t be exist by itself, unconnected to rest of
the system

Version 1.4
Version 1.4
Types of DFD…
 Physical DFD
 An implementation-dependent view of the current

system, showing what tasks are carried out and how
they are performed. Physical characteristics can
include:






Names of people
Form and document names or numbers
Equipment and devices used
Locations
Names of procedures

Version 1.4
Types Of DFD…
 Logical Data Flow Diagrams
 An implementation-independent view of the a system,

focusing on the flow of data between processes
without regard for the specific devices, storage
locations or people in the system. The physical
characteristics listed above for physical data flow
diagrams will not be specified.

Version 1.4
DFD Levels…
 DFD level-0
 It’s also context level DFD
 Context level diagrams show all external entities.
 They do not show any data stores.
 The context diagram always has only one process

labeled 0.

Version 1.4
DFD Level-1(or 2)
 include all entities and data stores that are directly

connected by data flow to the one process you are
breaking down
 show all other data stores that are shared by the
processes in this breakdown
 Like login process will linked to users & database in
further leveling

Version 1.4
Example (Physical-0)

Version 1.4
Example (logical – 0)…

Version 1.4
Example.. (Physical -1)

Version 1.4
Example (logical -1)

Version 1.4
Flow Charts…
 Used to show algorithm or process
 Can give step by step solution to the problem
 The first flow chart was made by John Von Newman in

1945
 Pictorial view of process
 Helpful for beginner and programmers

Version 1.4
Flow Chart…
 Flowcharts are generally drawn in the early stages of

formulating computer solutions.
 Flowcharts facilitate communication between
programmers and business people.
 These flowcharts play a vital role in the programming
of a problem and are quite helpful in understanding
the logic of complicated and lengthy problems.

Version 1.4
Flow Chart…
 Once the flowchart is drawn, it becomes easy to write

the program in any high level language.
 Often we see how flowcharts are helpful in explaining
the program to others.
 Hence, it is correct to say that a flowchart is a must for
the better documentation of a complex program.

Version 1.4
Flow Chart…
 Symbols are..
1.



Start Or End
Show starting or ending of any flow chart
Symbolized as
OR

Start

End

Version 1.4
Flow Charts…
2. Process
 Defines a process like defining variables or initializing
variable or performing any computation
 Symbolized as

res = num1 + num2

Version 1.4
Flow Charts…
3. Input or Output
 Used when user have to get or initialize any variable
 Like get num1 and num2 from user
 Symbolized as

Int num1,num2

Version 1.4
Flow Charts…
4. Decision Making
 For checking condition this symbols can be used
 Like if num1 is greater than num2
 Can be symbolized as

If num1>num2
Version 1.4
Flow Charts…
5. Flow lines
 Lines showing flow of data and process
 Showing flow of instructions also
 Can be symbolized as

Version 1.4
Flow chart
 Any program can be in three format

Linear or sequence
2. Branching
3. Looping
 Following are notations can be used to show this
format
1.

Version 1.4
Linear Program Structure…
Start
Process-1

Process-2

End
Version 1.4
Branching Program Structure..
Start
Process-1

Process-2

Process-3

End
Version 1.4

Process-4
Looping Program Structure….
Start
Process-1
Process-2 Yes
No
Process-3
End

Version 1.4
Sum of 1-50 numbers..

Version 1.4
Max among three numbers…

Version 1.4
Factorial of number…

Version 1.4
SDLC…
3. Designing






The Design document should reference what you are going to
build to meet the requirements, and not how it can include
pseudo code but shouldn’t contain actual code functionality.
Design elements describe the desired software features in
detail, and generally include functional hierarchy diagrams,
screen layout diagrams, tables of business rules, business
process diagrams, pseudo code, and a complete entityrelationship diagram with a full data dictionary.
These design elements are intended to describe the software
in sufficient detail that skilled programmers may develop the
software with minimal additional input. At this phase the test
plans are developed.
SDLC…
4. Implementation (Coding)




To launch the coding phase, develop a shell program that is
then put under some form of version control.
This phase includes the set up of a development environment,
and use of an enhanced editor for syntax checking.
SDLC…
5. Testing






Each developer insures that their code runs without warnings
or errors and produces the expected results.
The code is tested at various levels in software testing. Unit,
system and user acceptance tasting’s are often performed. This
is a grey area as many different opinions exist as to what the
stages of testing are and how much if any iteration occurs.
Types of testing: Defect testing, Path testing, Data set
testing, Unit testing, System testing, Integration testing,
Black box testing, White box testing, Regression testing,
Automation testing, User acceptance testing, Performance
testing, etc.
SDLC…
6. Maintenance








User’s guides and training are developed to reflect any new
functionality and changes which need to be identified to the
production staff.
Any changes needed to operations and/or maintenance need
to be addressed.
Every run in production needs to be verified. Any problems
with production need to be addressed immediately.
A Change Request system may be set up to allow for feedback
for enhancements.
Create Exercise
Overview of Software
Engineering
What is Software Engineering?
The term software engineering first appeared in the 1968 NATO Software
Engineering Conference and was meant to provoke thought regarding the current
"software crisis" at the time.
Definition:“state of the art of developing quality software on
time and within budget”
•Trade-off between perfection and physical constraints
•SE has to deal with real-world issues
•State of the art!
•Community decides on “best practice”+ life-long education
Software development activities
Requirements
Collection

Establish Customer Needs

Analysis

Model And Specify the requirements-“What”

Design

Model And Specify a Solution –“Why”

Implementation

Construct a Solution In Software

Testing

Validate the solution against the requirements

Maintenance

Repair defects and adapt the solution to the new
requirements
Web Programming


WWW (World Wide Web)




Web addresses are URL (uniform resource locator)
A server address and a path to a particular file
URLs are often redirected to other places

http://students. -int.com/classes/PHP&MYSQL/index.html







protocol= http://
web server= students
domain= . -int.com
path= /classes/PHP&MYSQL/ (dirs(folders))
file= index.html
file extension= .html(hypertext markup language)
CLIENTS AND SERVERS
 Web programming languages are usually classified as server-side or client-side. Some
languages, such as JavaScript, can be used as both client-side and server-side languages,
but most Web programming languages are server-side languages.
 The client is the Web browser, so client-side scripting uses a Web browser to run scripts.
The same script may produce different effects when different browsers run it.
 A Web server is a combination of software and hardware that outputs Web pages after
receiving a request from a client. Server-side scripting takes place on the server. If you
look at the source of a page created from a server-side script, you'll see only the HTML
code the script has generated. The source code for the script is on the server and doesn't
need to be downloaded with the page that's sent back to the client.






Web Programming Languages
PHP
ASP
Perl
JAVA
Client/Server Interaction
For Web pages, the client requests a page the server returns it:
there’s no permanent connection, just a short conversation
•Details of the conversation are specified by HTTP
Server-Side
 PHP is a Server-side language
 Even though it is embedded in HTML files much like the client-side JavaScript language,
PHP is server-side and all PHP tags will be replaced by the server before anything is sent

to the web browser.

•So if the HTML file contains:
<html>
<?php echo "Hello World"?>
</html>
•What the end user would see with a "view
source" in the browser would be:

<html>
Hello World
</html>
PHP Introduction
 PHP can be installed on any web server: Apache, IIS, Netscape, etc…
 PHP can be installed on any OS: Unix, Linux, Windows, MacOS, etc…
 XAMPP is a free and open source cross-platform web server package, consisting mainly of
the Apache HTTP Server, MySQL database, and interpreters for scripts written in the
PHP and Perl programming languages.
 It is used as a development tool, to allow website designers and programmers to test their
work on their own computers without any access to the Internet. .
 XAMPP's name is an acronym for:






X (meaning cross-platform)
Apache HTTP Server
MySQL
PHP
Perl

 LAMP package is used for Linux OS
 WAMP package is used for Windows OS
 PHP is a powerful server-side scripting language for creating dynamic

and interactive websites.

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

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

 The PHP syntax is very similar to Perl and C. PHP is often used

together with Apache (web server) on various operating systems. It also
supports ISAPI and can be used with Microsoft's IIS on Windows.

 A PHP file may contain text, HTML tags and scripts. Scripts in a PHP

file are executed on the server.

 What is a PHP File?
 •PHP files may contain text, HTML tags and scripts
 •PHP files are returned to the browser as plain HTML

 •PHP files have a file extension of ".php", ".php3", or ".phtml"
What is PHP?










PHP stands for PHP: Hypertext Preprocessor
PHP is a server-side scripting language, like ASP
PHP scripts are executed on the server
PHP supports many databases (MySQL, Informix, Oracle, Sybase,
Solid, Postgre SQL, Generic ODBC, etc.)
PHP is an open source software (OSS)
PHP is free to download and use
Created in 1994
Syntax inherited from C, Java and Perl
Powerful, yet easy to learn

Why PHP?





PHP runs on different platforms (Windows, Linux, Unix, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP is FREE to download from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
Diff Between php4 andphp5

There are several differences between PHP4 and
PHP5










1.Unified constructor and Destructor
2.Exception has been introduced
3.New error level named E_STRICT has been introduced
4.Now we can define full method definitions for a
abstract class
5.Within a class we can define class constants
6.we can use the final keyword to indicate that a method
cannot be overridden by a child
7.public, private and protected method introduced
8.Magic methods has been included
9.we can pass value by reference
How is PHP Used?
 How is PHP used?

 Content Management
 Forums
 Blogging
 Wiki
 CRM
Who Uses PHP?
HTML and CSS
 HTML, which stands for Hyper Text Markup Language, is the predominant markup
language for web pages. It provides a means to create structured documents by denoting
structural semantics for text such as headings, paragraphs, lists etc as well as for links,
quotes, and other items. It allows images and objects to be embedded and can be used to
create interactive forms. It is written in the form of HTML elements consisting of "tags"
surrounded by angle brackets within the web page content. It can include or can
load scripts in languages such as JavaScript which affect the behavior of HTML
processors like Web browsers; and Cascading Style Sheets (CSS) to define the appearance
and layout of text and other material. The W3C, maintainer of both HTML and CSS
standards, encourages the use of CSS over explicit presentational markup
 Hyper Text Markup Language (HTML) is the encoding scheme used to create and format
a web document. A user need not be an expert programmer to make use of HTML for
creating hypertext documents that can be put on the internet.
Example:<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
 a language for describing the content and presentation of a








web page
content: The meaning and structure of the web page
•presentation: How the page is to be presented
HTML pages have a basic hierarchical structure defined by
the tags
<html>, <head>, <body>, and so on
Basic HTML describes a static page
once parsed and rendered, the page doesn’t change
hyper linking was the big step forward in basic HTML
Intro to HTML Forms
 Types of input we can collect via forms:
 Text via text boxes and text areas
 Selections via radio buttons, check boxes, pull down

menus, and select boxes
 Form actions do all of the work
 Usually through button clicks
Basic HTML Form
<form name="input" action="form_action.php"
method="get">
<label for="user">Username</label>
<input type="text" name="user" id="user">
<br/><input type="submit" value="Submit">
</form>
Text Input Types
Text boxes
 <input type="text" size="45" name="fName“/>

Password boxes
 <input type="password" name="pass" id="pass" />

Textareas
- <textarea rows="3" cols="4"></textarea>
Selection Input Types
 Single Selection
 Radio buttons

<input type="radio" name="sex" value="male" /> Male
<br/>
<input type="radio" name="sex" value="female" /> Female
 Pull Down List
<select name="pulldown">
<option value="1">pulldownitem 1</option>
<option value="2">pulldownitem 2</option>
</select>
Selection Input Types
 Multi-Selection
Check boxes
<input type="checkbox" name="bike" />bike owner <br/>
<input type="checkbox" name="car" />car owner
Selection lists (Menus)
<select name="menu" size="3" multiple="multiple">
<option value="1">menu item 1</option>
<option value="2">menu item 2</option>
<option value="3">menu item 3</option>
<option value="4">menu item 4</option>

</select>
Buttons
 Built-in buttons

- <input type="submit" />
- <input type="reset" />
- <input type="file" />
 Custom buttons
- <button type="button" value="Click Me"
onclick="run_javascript()">
Form Actions
<form name="input" action="html_form_action.php“
method="get">
 Action specifies what file the form data will be sent to (on the
server)
 Method specifies by which HTTP protocol
 get
 post
 Method is important on the receiving end
PHP Forms And User Input
 The PHP $_GET and $_POST variables are used to retrieve information

from forms, like user input.

PHP Form Handling
 The most important thing to notice when dealing with HTML forms
and PHP is that any form element in an HTML page will automatically
be available to your PHP scripts.
 Form example:
<html>





<body><form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />

</form></body>
</html>
 The example HTML page above contains two input fields and a submit button. When the
user fills in this form and click on the submit button, the form data is sent to the
"welcome.php" file.
 •The "welcome.php" file looks like this:
 <html>



<body>Welcome <?php echo $_POST["name"]; ?>.<br/>
You are <?php echo $_POST["age"]; ?> years old.</body>

 </html>


A sample output of the above script may be:

 Welcome John.
 You are 28 years old.
Form Validation
 User input should be validated whenever possible. Client side validation is faster, and will
reduce server load.
 However, any site that gets enough traffic to worry about server resources, may also need
to worry about site security. You should always use server side validation if the form
accesses a database.
 A good way to validate a form on the server is to post the form to itself, instead of
jumping to a different page. The user will then get the error messages on the same page as
the form. This makes it easier to discover the error.
PHP $_Get
The $_GET variable is used to collect values from a form with method="get".
The $_GET Variable

• The $_GET variable is an array of variable names and values sent by the HTTP GET
method.
• The $_GET variable is used to collect values from a form with method="get".
Information sent from a form with the GET method is visible to everyone (it will be
displayed in the browser's address bar) and it has limits on the amount of information to
send (max. 100 characters).
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
 </form>
When the user clicks the "Submit" button, the URL sent could look something like this:
http://www.-int.com/welcome.php?name=Peter&age=37
 The "welcome.php" file can now use the $_GET variable to catch the form data (notice
that the names of the form fields will automatically be the ID keys in the $_GET array):
PHP $_Get
Welcome <?php echo $_GET["name"]; ?>.<br/>
You are <?php echo $_GET["age"]; ?> years old!

 Why use $_GET?
Note: When using the $_GET variable all variable names
and values are displayed in the URL. So this method
should not be used when sending passwords or other
sensitive information! However, because the variables
are displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases.

 Note: The HTTP GET method is not suitable on
large variable values; the value cannot exceed 100

characters.
PHP $_Post

 The $_POST variable is used to collect values from a form with method="post".

The $_POST Variable
 The $_POST variable is an array of variable names and values sent by the HTTP POST
method.
 The $_POST variable is used to collect values from a form with method="post".
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
 Example




<form action="welcome.php" method="post">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />

 <input type="submit" />
 </form>
When the user clicks the "Submit" button, the URL will not contain any form data, and will look
something like this:
http://www.-int.com/welcome.php
 The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the
names of the form fields will automatically be the ID keys in the $_POST array):
 Welcome <?php echo $_POST["name"]; ?>.<br/>


 You are <?php echo $_POST["age"]; ?> years old!
PHP $_Post
 Why use $_POST?
 Variables sent with HTTP POST are not shown in the URL
 Variables have no length limit
 However, because the variables are not displayed in the URL, it is
not possible to bookmark the page.
The $_REQUEST Variable
 The PHP $_REQUEST variable contains the contents of both
$_GET, $_POST, and $_COOKIE.
 The PHP $_REQUEST variable can be used to get the result from
form data sent with both the GET and POST methods.

 Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br/>

You are <?php echo $_REQUEST["age"]; ?> years
old!
CSS

Cascading Style Sheet
Introduction
Cascading Style Sheets (CSS).
 With CSS you will be able to:
 Add new looks to your old HTML
 Completely restyle a web site with only a few changes
to your CSS code
 Use the "style" you create on any web page you wish!
CSS Selector
 SELECTOR { PROPERTY: VALUE }
 HTML tag"{ "CSS Property": "Value" ; }

 The selector name creates a direct relationship
with the HTML tag you want to edit. If you wanted
to change the way a paragraph tag behaved, the
CSS code would look like:
 p { PROPERTY: VALUE }
 The above example is a template that you can use
whenever you are manipulating the paragraph

HTML element
Applying CSS
Three methods

1.Internal
2.External
3.Inline
Creating Internal CSS Code
<head>

<style type="text/css">

p {color: white; }
body {background-color: black; }

</style>
</head>
<body>
<p>White text on a black background!</p>

</body>







We chose the HTML element we wanted to manipulate. -p{ : ; }
Then we chose the CSS attribute color. -p { color:; }
Next we choose the font color to be white. -p { color:white; }
Now all text within a paragraph tag will show up as white! Now an explanation of
the CSS code that altered the <body>'s background:
We choose the HTML element Body -body { : ; }
Then we chose the CSS attribute. -body { background-color:; }

•Next we chose the background color to be black. -body { backgroundcolor:black; }
External CSS
 When using CSS it is preferable to keep the CSS

separate from your HTML. Placing CSS in a separate file
allows the web designer to completely differentiate
between content (HTML) and design (CSS). External
CSS is a file that contains only CSS code and is saved
with a ".css" file extension. This CSS file is then
referenced in your HTML using the <link> instead of
<style>.
body{ background-color: gray }
p { color: blue; }
h3{ color: white; }
Save it as .css
HTML

<html>
<head>
<link rel="stylesheet" type="text/css“ href="test.css" />
</head>

<body>
<h3> A White Header </h3>
<p> This paragraph has a blue font. The background color
of this page is gray because we changed it with CSS!

</p>
</body>
</html>
Inline css
 It is possible to place CSS right in the thick of your
HTML code, and this method of CSS usage is

referred to as inline css.
 Inline CSS has the highest priority out of external,
internal, and inline CSS. This means that you can
override styles that are defined in external or
internal by using inline CSS
<p style="background: blue; color: white;">
A new background and font color with inline CSS
</p>
Property value of css
 A value is given to the property following a colon (NOT an 'equals' sign)








and semi-colons separate the properties.
body {font-size: 0.8em;color: navy;}
This will apply the given values to the font-size and color properties to
the body selector.
So basically, when this is applied to an HTML document, text between
the body tags (which is the content of the whole window) will be
0.8emsin size and navy in colour.
em (such as font-size: 2em) is the unit for the calculated size of a font.
So "2em", for example, is two times the current font size.
px(such as font-size: 12px) is the unit for pixels.
pt (such as font-size: 12pt) is the unit for points.
% (such as font-size: 80%) is the unit for... wait for it... percentages.
Text property
 font-family
 This is the font itself, such as Times New Roman, Arial, or Verdana.
 font-family: "Times New Roman".

 font-size
 font-weight
 This states whether the text is bold or not.

 font-style
 This states whether the text is italic or not. It can be font-style: italic or font-style:

normal.

 text-decoration
This states whether the text is underlined or not. This can be:
text-decoration: overline, which places a line above the text.
text-decoration: line-through, strike-through, which puts a line through the text.
text-decoration: underline should only be used for links because users
generally expect underlined text to be links.
 This property is usually used to decorate links, such as specifying no underline with
text-decoration: none.





 Letter Spacing:3px
text-transform
 This will change the case of the text.
 text-transform: capitalize turns the first letter of every

word into uppercase.
 text-transform: uppercase turns everything into
uppercase.
 text-transform: lowercase turns everything into
lowercase.

text-transform: none I'll leave for you to work out.
Margins and Padding
 Margin and padding are the two most commonly used properties for

spacing-out elements. A margin is the space outside of the element,
whereas padding is the space inside the element
 The four sides of an element can also be set individually. margin-top,
margin-right, margin-bottom, margin-left, padding-top,
padding-right, padding-bottom and padding-left are the selfexplanatory properties you can use.
CSS Classes
 It is possible to give an HTML element multiple looks with CSS.
 The Format of Classes
 Using classes is simple. You just need to add an extension to the typical

CSS code and make sure you specify this extension in your HTML. Let's
try this with an example of making two paragraphs that behave
differently. First, we begin with the CSS code, note the red text.
 CSS Code: p. first{ color: blue; } p.second{ color: red; } HTML Code:
<html>
<body>
<p>This is a normal paragraph.</p>
<p class="first">This is a paragraph that uses the p. first CSS code!</p>
<p class="second">This is a paragraph that uses the p. second CSS
code!</p> ...
CSS Background
 The background of website is very important
 With CSS, you are able to set the background color or image of any CSS

element. In addition, you have control over how the background image is
displayed. You may choose to have it repeat horizontally, vertically, or in
neither direction. You may also choose to have the background remain in a
fixed position, or have it scroll as it does normally.

 CSS Background Color

Varying backgrounds were obtained without using tables! Below are a couple
examples of CSS backgrounds.
 CSS Code:

h4 { background-color: white; } p { background-color: #1078E1; } ul {
background-color:rgb( 149, 206, 145); }
CSS Background Image
 Need an image to repeat left-to-right, like the gradient








background
you would like to have an image that remains fixed when
the user scrolls down your page. This can be done quite
easily with CSS and more, including:
choosing if a background will repeat and which directions
to repeat in.
precision positioning scrolling/static images
CSS Code:
p { background-image:url(smallPic.jpg); } h4{ backgroundimage:url(http://www.tizag.com/pics/cssT/smallPic.jpg); }
 CSS Background

Background Image Repeat
 p { background-image:url(smallPic.jpg); backgroundrepeat: repeat; }
 h4 { background-image:url(smallPic.jpg);
 background-repeat: repeat-y;}
 ol{ background-image:url(smallPic.jpg);
 ul{ background-image:url(smallPic.jpg);
 background-repeat: no-repeat;}
CSS Background
 CSS Background Image Positioning
 p { background-image:url(smallPic.jpg);

 background-position: 20px 10px; }
 h4 { background-image:url(smallPic.jpg);
 background-position: 30% 30%; }

 ol{ background-image:url(smallPic.jpg);
 background-position: top center; }
CSS Background
 CSS Gradient Background
 If you would like to create a gradient background like the one that

appears at the top of Tizag.com, you must first create an image inside a
painting program (Photoshop, Draw, etc) like the one you see below.
 p { background-image:url(http://www./gradient.gif);
 background-repeat: repeat-x; }
CSS Links ( Pseudo-classes )

Anchor/Link States

 link-this is a link that has not been used, nor is a mouse pointer

hovering over it
 visited-this is a link that has been used before, but has no mouse on it
 hover-this is a link currently has a mouse pointer hovering over it/on it
 active-this is a link that is in the process of being clicked
Applying CSS to HTML page
Background Color
Font color
Text Decoration
Font Type
Border
With cascading style sheets, there are a number of ways you can apply styles
to text.
1)One way is to use inline style definitions. These allow you to specify
styles in the style attribute of any HTML tag.
2)Second way is to use a style sheet specified in the header of your document.
You can then refer to and reuse these styles throughout your document.
A document style sheet is specified between opening and closing style tags in
the header of your document:
<head>
<style type=”text/css”>
</style>
</head>
 To build your style sheet, just define the styles in the style block. You can define
 three types of style definitions:
 HTML element definitions, which specify a default style for different
HTML elements (in other words, for different HTML tags)
 Class definitions, which can be applied to any HTML tag by using
the class attribute common to all tags
 Identity definitions, which apply to any page elements that have a
matching ID
The following steps show you how to create a style sheet in a document and then
use the styles:
1. In the header of a new document, create a style block:
<style type=”text/css”>
</style>
2. In the style block, create a style definition for the p tag:
P{
font-family: Arial, Helvetica, SANS-SERIF;
color: #ff0000; }
3. Next, create a style definition for the my Class class:
.myClass{
font-size: 24pt;
font-style: italic; }
4. Finally, create a style definition for elements with the my IDID:
#myID{ background-color: #cccccc; }
5. In the body of your document, create a level 1 heading and apply the
My Class class to it:

<h1 class=”myClass”> This is a headline </h1>
CSS Pseudo-classes
css anchor/link states
 You may not know it, but a link has four different states that it can be in. CSS allows you to customize
each state. Please refer to the following keywords that each correspond to one specific state:





link - this is a link that has not been used, nor is a mouse pointer hovering over it
visited - this is a link that has been used before, but has no mouse on it
hover - this is a link currently has a mouse pointer hovering over it/on it
active - this is a link that is in the process of being clicked



Using CSS you can make a different look for each one of these states, but at the end of this lesson we
will suggest a good practice for CSS Links.



CSS Code:
a:link { color: white; background-color: black; text-decoration: none; border: 2px solid white; }



a:visited { color: white; background-color: black; text-decoration: none; border: 2px solid white; }



a:hover { color: black; background-color: white; text-decoration: none; border: 2px solid black; }



Example:-

<html>
<head>
<style>
a:link{ text-decoration: none; color: gray; }
a:visited{ text-decoration: none; color: gray; }
a:hover{ text-decoration: none; color: green; font-weight: bolder; letter-spacing: 2px; }

</style>
</head>
<body>
<h2>CSS Pseudo Classes or Links</h2>
<p>This is a <a href="">link with Pseudo Classes</a> !</p>
</body>
</html>
CSS pseudo –class
 Syntax

The syntax of pseudo-classes:
 selector:pseudo-class {property:value}
CSS classes can also be used with pseudo-classes:
 selector.class:pseudo-class {property:value}
 Example
 Specify the color of links:
 a:link {color:#FF0000}
/* unvisited link */
a:visited {color:#00FF00} /* visited link */
a:hover {color:#FF00FF} /* mouse over link */
a:active {color:#0000FF} /* selected link */
CSS - The :first-child Pseudo-class





Match the first <p> element
In the following example, the selector matches any <p> element that is the first child of any element:
Example
<html>
<head>
<style type="text/css">
p:first-child
{
color:blue
}
</style>
</head>
<body>
<p>I am a strong man.</p>
<p>I am a strong man.</p>
</body>
</html>
Match the first <i> element in all <p>
elements
 Example
 <html>

<head>
<style type="text/css">
p > i:first-child
{
font-weight:bold
}
</style>
</head>
<body>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
</body>
</html>
Match all <i> elements in all first child <p>
elements
 <html>

<head>
<style type="text/css">
p:first-child i
{
color:blue
}
</style>
</head>
<body>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
</body>
</html>
CSS - The :lang Pseudo-class
 <html>

<head>
<style type="text/css">
q:lang(no) {quotes: "~" "~"}
</style>
</head>
<body>
<p>Some text <q lang="no">A quote in a paragraph</q> Some
text.</p>
</body>
</html>
The :first-line/letter Pseudo-element
 Pseudo-elements can be combined with CSS classes:

Example:p.article:first-letter
{color:#ff0000
}

<p class="article">A paragraph in an article</p>

p:first-letter
{
color:#ff0000;
font-size:xx-large;
}
p:first-line
{
color:#0000ff;
font-variant:small-caps;
}
CSS - The :before/After Pseudo-element
 Example:-

h1:before
{
content:url(smiley.gif);
}
h1:after
{
content:url(smiley.gif);
}


<html>
<head>
<style type="text/css">
div.img
{
margin:2px;
border:1px solid #0000ff;
height:auto;
width:auto;
float:left;
text-align:center;
}
div.img img
{
display:inline;
margin:3px;
border:1px solid #ffffff;
}
div.img a:hover img
{
border:1px solid #0000ff;
}
div.desc
{
text-align:center;
font-weight:normal;
width:120px;
margin:2px;
}
</style>
</head>
<body>
<div class="img">
<a target="_blank" href="klematis_big.htm">
<img src="klematis_small.jpg" alt="Klematis" width="110" height="90" />
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="img">
<a target="_blank" href="klematis2_big.htm">
<img src="klematis2_small.jpg" alt="Klematis" width="110" height="90" />
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="img">
<a target="_blank" href="klematis3_big.htm">
<img src="klematis3_small.jpg" alt="Klematis" width="110" height="90" />
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="img">
<a target="_blank" href="klematis4_big.htm">
<img src="klematis4_small.jpg" alt="Klematis" width="110" height="90" />
</a>
<div class="desc">Add a description of the image here</div>
</div>
</body>
</html>
PHP Syntax and Variables
PHP slides
PHP as a Scripting Language
 PHP, or PHP: Hypertext Preprocessor, is a widely used, general-

purpose scripting language that was originally designed for web
development, to produce dynamic web pages. It can be embedded
into HTML and generally runs on a web server, which needs to be
configured to process PHP code and create web page content from it. It
can be deployed on most web servers and on almost every operating
system and platform free of charge. PHP is installed on over 20 million
websites and 1 million web servers
 PHP was originally created by Rasmus Lerdorf in 1995 and has been in

continuous development ever since. The main implementation of PHP
is now produced by The PHP Group and serves as the de
facto standard for PHP as there is no formal specification. PHP is free
software released under the PHP License, which is incompatible with
the GNU General Public License (GPL) because of restrictions on the
use of the term PHP.
PHP Syntax
 Below, we have an example of a simple PHP script which sends the text








"Hello World" to the browser:
<html>
<body><?php
echo "Hello World";
?></body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a
separator and is used to distinguish one set of instructions from
another.
There are two basic statements to output text with PHP: echo and
print. In the example above we have used the echo statement to output
the text "Hello World".
PHP Syntax
Comments in PHP
•In PHP, we use // to
make a single-line
comment or /* and
*/ to make a large
comment block.

<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
PHP Variables

 Variables are used for storing values, such as numbers, strings or

function results, so that they can be used many times in a script.

Variables in PHP
 Variables are used for storing a values, like text strings, numbers or
arrays.
 When a variable is set it can be used over and over again in your script
 All variables in PHP start with a $ sign symbol.
 The correct way of setting a variable in PHP:
 $var_name = value; New PHP programmers often forget the $ sign at
the beginning of the variable. In that case it will not work.
 Let's try creating a variable with a string, and a variable with a number:
<?php
$txt = "Hello World!";

$number = 16;
?>
 Names (also called identifiers)

 Must always begin with a dollar-sign ($)
 generally start with a letter and can contain letters,

numbers, and underscore characters “_”
 Names are case sensitive
 Values can be numbers, strings, boolean, etc
 change as the program executes
PHP is a Loosely Typed Language
 In PHP a variable does not need to be declared before







being set.
In the example above, you see that you do not have to tell
PHP which data type the variable is.
PHP automatically converts the variable to the correct data
type, depending on how they are set.
In a strongly typed programming language, you have to
declare (define) the type and name of the variable before
using it.
In PHP the variable is declared automatically when you use
it.
PHP supports eight primitive types :
 Four scalar types:
 boolean
 integer
Float (floating-point number, aka'double')

 string
•Two compound types:

 array
 object
•And finally two special types:

 resource

 NULL
Variables and Expressions in PHP
 Names (also called identifiers)
 Must always begin with a dollar-sign ($)
 generally start with a letter and can contain letters, numbers, and underscore characters
“_”
 Names are case sensitive
 Values can be numbers, strings, boolean, etc
 change as the program executes

 Expressions are the most important building stones of PHP. In PHP,

almost anything you write is an expression. The simplest yet most
accurate way to define an expression is "anything that has a value".








There is one more expression that may seem odd if you haven't seen it in other languages, the ternary
conditional operator:
<?php
$first ? $second : $third
?>
If the value of the first subexpression is TRUE (non-zero), then the second subexpression is
evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is
evaluated, and that is the value.
The following example should help you understand pre- and post-increment and expressions in
general a bit better:
<?php
function double($i)
{
return $i*2;
}
$b = $a = 5;
/* assign the value five into the variable $a and $b */
$c = $a++;
/* post-increment, assign original value of $a (5) to $c */
$e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */
/* at this point, both $d and $e are equal to 6 */
$f = double($d++); /* assign twice the value of $d before the increment, 2*6 = 12 to $f */
$g = double(++$e); /* assign twice the value of $e after the increment, 2*7 = 14 to $g */
$h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24. the value of the
assignment (24) is then assigned into $h, and $h ends with the value of 24 as
well. */
?>
PHP Operators
 c=a+b
 Assuming a and b are numbers (remember data types? --

the result would be different if they were strings -- more
about that later) this expression would add a and b and put
the sum into c (remember again, that the equals sign here
makes this an assignment instruction.) In the expression a
+ b the plus sign is an arithmetic operator. Here are some
more operators:
 Arithmetic Operators:

 Comparison Operators:


Logical Operators:



Increment and Decrement Operators:



The Concatenate Operator

 Combined Operators:
PHP Operators
 Operators are used to operate on values.
 PHP Operators
 This section lists the different operators used in PHP.
 Arithmetic Operators
ASSIGNMENT OPERATOR
PHP Operator
Conditional Test, Events and Flows in PHP
 PHP If & Else Statements
 The if, elseif and else statements in PHP are used to perform

different actions based on different conditions.
Conditional Statements
 Very often when you write code, you want to perform different
actions for different decisions.
 You can use conditional statements in your code to do this.

 if...else statement -use this statement if you want to

execute a set of code when a condition is true and
another if the condition is not true
 elseif statement -is used with the if...else statement to
execute a set of code if one of several condition are
true
PHP If & Else Statements
The If...Else Statement
 If you want to execute some code if a condition is true and another code if a condition is
false, use the if....else statement.

 Example







The following example will output "Have a nice weekend!" if the current day is Friday, otherwise
it will output "Have a nice day!":

<html>
<body><?php
$d=date("D");
if ($d=="Fri")


echo "Have a nice weekend!";



echo "Have a nice day!";

 else
 ?></body>
 </html>
PHP If & Else Statements
 If more than one line should be executed if a condition is
true/false, the lines should be enclosed within curly braces:
 <html>
 <body><?php
 $d=date("D");
 if ($d=="Fri")
{




echo "Hello!<br/>";
echo "Have a nice weekend!";
echo "See you on Monday!";

}
 ?></body>
 </html>
PHP If & Else Statements
 The ElseIf Statement
 If you want to execute some code if one of several

conditions are true use the elseif statement

Syntax
if (condition)
code to be executed if condition is true;

elseif(condition)
code to be executed if condition is true;

else
code to be executed if condition is false;
PHP If & Else Statements
Example
The following example will output "Have a nice weekend!" if the
current day is Friday, and "Have a nice Sunday!" if the current day is
Sunday. Otherwise it will output "Have a nice day!":

<html>
<body><?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif($d=="Sun")
echo "Have a nice Sunday!";
Else
echo "Have a nice day!";
?></body>
</html>
 PHP Switch Statement
 •The Switch statement in PHP is used to perform one of several different

actions based on one of several different conditions.
 The Switch Statement
 •If you want to select one of many blocks of code to be executed, use the Switch
statement.
 •The switch statement is used to avoid long blocks of if..elseif..else code.






Syntax
switch (expression)
{
case label1:
 code to be executed if expression = label1;

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

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

 }
PHP Switch Statement
Example

 This is how it works:
 A single expression (most often a variable) is evaluated once
 The value of the expression is compared with the values for each case in the
structure
 If there is a match, the code associated with that case is executed
 After a code is executed, break is used to stop the code from running into the next
case
 The default statement is used if none of the cases are true
<html>
<body><?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";

}
?></body>
</html>
Iteration
 Iteration or looping is a way to execute a block of program





statements more than once
we will use the for statement to create loops
The for loop is generally controlled by counting
There is an index variable that you increment or decrement
each time through the loop
When the index reaches some limit condition, then the
looping is done and we continue on in the code
Why do we want loops in our code?
• Do something for a given number of times or for
every object in a collection of objects
 for every radio button in a form, see if it is checked
 for every month of the year, charge $100 against the
balance
 calculate the sum of all the numbers in a list
 Many loops are counting loops
 they do something a certain number of times
PHP slides
PHP slides
PHP slides
PHP Looping
Looping statements in PHP are used to execute the same block of code a
specified number of times.
Looping
 Very often when you write code, you want the same block of code to
run a number of times. You can use looping statements in your code to
perform this.
In PHP we have the following looping statements:
 while -loops through a block of code if and as long as a specified

condition is true

 do...while -loops through a block of code once, and then repeats the

loop as long as a special condition is true

 for -loops through a block of code a specified number of times
 foreach-loops through a block of code for each element in an array
PHP Looping
The while Statement
The while statement will execute a block of code if and as long as a condition is true.

Syntax
 while (condition)
 code to be executed;
 Example
 The following example demonstrates a loop that will continue to run as long as the
variable i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body><?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br/>";
$i++;
}
?></body>
</html>
PHP Looping
The do...while Statement




•The do...while statement will execute a block of code at least once-it then will repeat the loop as long as a
condition is true.

Syntax

do
{
code to be executed;
}
while (condition);
Example
 The following example will increment the value of i at least once, and it will continue incrementing
the variable i as long as it has a value of less than 5:
<html>
<body><?php
$i=0;
do
{
$i++;
echo "The number is " . $i . "<br/>";
}
while ($i<5);
?></body>
</html>
PHP Looping
The for Statement
•The for statement is used when you know how many times you want to execute a statement or a list of statements.



Syntax


for (initialization; condition; increment)

{
code to be executed;
}

Note: The for statement has three parameters. The first parameter initializes variables, the
second parameter holds the condition, and the third parameter contains the increments
required to implement the loop. If more than one variable is included in the initialization
or the increment parameter, they should be separated by commas. The condition must
evaluate to true or false.


Example


The following example prints the text "Hello World!" five times:

<html>
<body><?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br/>";

}
?></body>
</html>
PHP Looping
The foreach Statement
 The for each statement is used to loop through arrays.
 For every loop, the value of the current array element is assigned to $value (and the

array pointer is moved by one) -so on the next loop, you'll be looking at the next
element.

 Syntax
foreach(array as value)
{
code to be executed;
}

 Example
 The following example demonstrates a loop that will print the values of the given

array:

<html>
<body><?php
$arr=array("one", "two", "three");
foreach($arras $value)
{
echo "Value: " . $value . "<br/>";
}
?></body>
</html>
Project Based Lab
 Prepare a flowchart and DFD of the project whichever is assign to you
..
 Flowchart indicate the workflow of the system.
 A data flow diagram (DFD) is a graphical representation of the "flow" of
data through an information system. It differs from the flowchart as it
shows the data flow instead of the control flow of the program.
Difference between echo and print
1. Speed. There is a difference between the two, but speed-wise it
should be irrelevant which one you use. echo is marginally faster
2. Expression. print() behaves like a function in that you can do:
$ret = print "Hello World"; And $ret will be 1. That means that print
can be used as part of a more complex expression where echo
cannot.

An example from the PHP Manual:
$b ? print "true" : print "false";
3. Parameter(s). The grammar is: echo expression [,
expression[,expression] ... ] But echo ( expression, expression ) is not
valid.
This would be valid: echo ("howdy"),("partner"); the same as: echo
"howdy","partner";
So, echo without parentheses can take multiple parameters, which get
concatenated:

echo "and a ", 1, 2, 3; // comma-separated without parentheses
echo ("and a 123"); // just one parameter with parentheses
print() can only take one parameter:
print ("and a 123");
print "and a 123";
Functions and Arrays using PHP
PHP Functions

The real power of PHP comes from its functions.
 In PHP -there are more than 700 built-in functions available.
 Create a PHP Function
 A function is a block of code that can be executed whenever we need it.
Creating PHP functions:
 All functions start with the word "function()"
 Name the function -It should be possible to understand what the
function does by its name. The name can start with a letter or
underscore (not a number)
 Add a "{"-The function code starts after the opening curly brace
 Insert the function code
 Add a "}"-The function is finished by a closing curly brace
PHP Functions

Example
•A simple function that writes my name when it is called:
<html>
<body><?php
Function writeMyName()
{
echo "Kai JimRefsnes";
}
writeMyName();
?></body>
</html>
Use a PHP Function
•Now we will use the function in a PHP script:
<html>
<body><?php
function writeMyName()
{
echo "Kai JimRefsnes";
}
echo "Hello world!<br/>";
echo "My name is ";
writeMyName();
echo ".<br/>That's right, ";
writeMyName();
echo " is my name.";
?></body>
</html>
PHP Functions

The output of the code above will be:
Hello world!
My name is Kai JimRefsnes.
That's right, Kai JimRefsnes is my name.
PHP Functions -Adding parameters
•Our first function (writeMyName()) is a very simple function. It only writes a static string.
•To add more functionality to a function, we can add parameters. A parameter is just like a variable.
•You may have noticed the parentheses after the function name, like: writeMyName(). The parameters
are specified inside the parentheses.
Example 1
•The following example will write different first names, but the same last name:
<html>
<body><?php
function writeMyName($fname)
{
echo $fname. "Refsnes.<br/>";
}
echo "My name is ";
writeMyName("Kai Jim");echo "My name is ";
writeMyName("Hege");echo "My name is ";
writeMyName("Stale");
?></body>
PHP Functions
•The output of the code above will be:
My name is Kai JimRefsnes.
My name is Hege Refsnes.
My name is Stale Refsnes.
Example 2
•The following function has two parameters:
<html>
<body><?php
function writeMyName($fname,$punctuation)
{
echo $fname. "Refsnes" . $punctuation . "<br/>";
}
echo "My name is ";
writeMyName("Kai Jim",".");
echo "My name is ";
writeMyName("Hege","!");
echo "My name is ";
writeMyName("Ståle","...");
?></body>
</html>
PHP Functions
•The output of the code above will be:
My name is Kai Jim Refsnes.
My name is Hege Refsnes!
My name is Ståle Refsnes...

PHP Functions -Return values
•Functions can also be used to return values.
Example
<html>
<body><?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?></body>
</html>
The output of the code above will be:
1 + 16 = 17
PHP slides
PHP slides
PHP slides
PHP slides
PHP Date()
PHP slides
PHP Date()
PHP Date -Format the Date

•The first parameter in the date() function specifies how to format the date/time. It uses
letters to represent date and time formats. Here are some of the letters that can be
used:
•d -The day of the month (01-31)
•m -The current month, as a number (01-12)
•Y -The current year in four digits
 Other characters, like"/", ".", or "-" can also be inserted between the letters to add
additional formatting:
<?php
echo date("Y/m/d");
echo "<br/>";
echo date("Y.m.d");
echo "<br/>";
echo date("Y-m-d");
?>
The output of the code above could be something like this:
2009/07/11
2009.07.11
2009-07-11
PHP Date()
 PHP Date -Adding a Timestamp
•The second parameter in the date() function specifies a timestamp. This
parameter is optional. If you do not supply a timestamp, the current time
will be used.
•In our next example we will use the mktime() function to create a timestamp
for tomorrow.
•The mktime() function returns the Unix timestamp for a specified date.

 Syntax
•mktime(hour,minute,second,month,day,year,is_dst)
•To go one day in the future we simply add one to the day argument of
mktime():

<?php
$tomorrow =mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>
 The output of the code above could be something like this:
 Tomorrow is 2006/07/12
PHP Arrays

• An array can store one or more values in a single variable name.
What is an array?
• When working with PHP, sooner or later, you might want to create many similar
variables.
• Instead of having many similar variables, you can store the data as elements in
an array.
• Each element in the array has its own ID so that it can be easily accessed.
• There are three different kind of arrays:
• Numeric array -An array with a numeric ID key
• Associative array -An array where each ID key is associated with a value
• Multidimensional array -An array containing one or more arrays

Numeric Arrays
• A numeric array stores each element with a numeric ID key.
• There are different ways to create a numeric array.

Example 1
• In this example the ID key is automatically assigned:

$names = array("Peter","Quagmire","Joe");
PHP Arrays
Example 2
• In this example we assign the ID key manually:
$names[0] = "Peter";
$names[1] = "Quagmire";

$names[2] = "Joe";
•The ID keys can be used in a script:
<?php
$names[0] = "Peter";
$names[1] = "Quagmire";

$names[2] = "Joe";
echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";

?>
•The code above will output:
Quagmire and Joe are Peter's neighbors
PHP Arrays
Associative Arrays
•An associative array, each ID key is associated with a value.
•When storing data about specific named values, a numerical array is not always the best way to do
it.
•With associative arrays we can use the values as keys and assign values to them.

Example 1
•In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

Example 2
This example is the same as example 1, but shows a different way of creating the array:

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>
The code above will output:

Peter is 32 years old.
PHP Arrays
Multidimensional Arrays
•In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array
can be an array, and so on.
Example
•In this example we create a multidimensional array, with automatically assigned ID keys:

$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
PHP Arrays
•The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
Commonly used Array Functions
 array_combine --Creates an array by using one array for keys and













another for its values
array_count_values --Counts all the values of an array
Array_diff -Computes the difference of arrays
Array_merge -Merge one or more arrays
Array_merge_recursive -Merge two or more arrays recursively
Array_reverse -Return an array with elements in reverse order
Array_search -Searches the array for a given value and returns the
corresponding key if successful
Array_sum -Calculate the sum of values in an array
Arsort-Sort an array in reverse order and maintain index association
Asort-Sort an array and maintain index association
Krsort-Sort an array by key in reverse order
Ksort-Sort an array by key
sizeof-
Array Functions
Example:<?php
$a1=array("a","b","c","d");
$a2=array("Cat","Dog","Horse","Cow");
print_r(array_combine($a1,$a2));
?>
o/p:- Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow )

<?php
$a=array("Cat","Dog","Cat","Dog");
print_r(array_count_values($a));
?>
o/p:-Array ( [Cat] => 2 [Dog] => 2 )
<?php
$a1=array(0=>"Cat",1=>"Dog",2=>"Horse");
$a2=array(3=>"Horse",4=>"Dog",5=>"Fish");
print_r(array_diff($a1,$a2));
?>
<br />
<br />
<?php
$a1=array("a"=>"Horse","b"=>"Dog");
$a2=array("c"=>"Cow","b"=>"Cat");
print_r(array_merge($a1,$a2));
?>
o/p:- Array ( [0] => Cat )
Array ( [a] => Horse [b] => Cat [c] => Cow )
<?php
$a1=array("a"=>"Horse","b"=>"Dog");
$a2=array("c"=>"Cow","b"=>"Cat");
print_r(array_merge_recursive($a1,$a2));
?>
<br />
<br />
<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
print_r(array_reverse($a));
?>
Output:Array ( [a] => Horse [b] => Array ( [0] => Dog [1] => Cat ) [c] => Cow )
Array ( [c] => Horse [b] => Cat [a] => Dog )
<?php
$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);
?>
<br />
<br />
<?php
$a=array(0=>"5",1=>"15",2=>"25");
echo array_sum($a);
?>
b
45
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = sizeof($people);
echo $result;
?> Output:-

4
PHP slides
PHP slides
PHP slides
PHP slides
PHP Arrays
 Example 2
Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";
The code above will output:


 Is Megan a part of the Griffin family?
PHP Include File

• Server Side Includes (SSI) are used to create functions, headers, s, or elements
that will be reused on multiple pages.
Server Side Includes
•You can insert the content of a file into a PHP file before the server executes it,
with the include() or require() function. The two functions are identical in
every way, except how they handle errors. The include() function generates a
warning (but the script will continue execution) while the require() function
generates a fatal error (and the script execution will stop after the error).
•These two functions are used to create functions, headers, s, or elements that can
be reused on multiple pages.
•This can save the developer a considerable amount of time. This means that you
can create a standard header or menu file that you want all your web pages to
include. When the header needs to be updated, you can only update this one
include file, or when you add a new page to your site, you can simply change the
menu file (instead of updating the links on all web pages).
• Include_once and require_once is also use for include any file into your code.
• But the difference between include and include_once is in include if there is any
error in include file there is no effect on the code where it is included but in
include_once there is effect in the code if there is any error.
PHP Include File
The include() Function
•The include() function takes all the text in a specified file and copies it into the file that uses the include function.

Example 1
•Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function, like this:

<html>
<body>
<?phpinclude("header.php"); ?>
<h1>Welcome to my home page</h1>

<p>Some text</p>
</body>
</html>
Example 2
Now, let's assume we have a standard menu file that should be used on all pages (include files usually have a ".php" extension). Look at the
"menu.php" file below:

<html>
<body>
<ahref="http://www.example.com/default.php">Home</a> |
<ahref="http://www. example.com/about.php">About Us</a> |
<ahref="http://www. example.com/contact.php">Contact Us</a>
The three files, "default.php", "about.php", and "contact.php" should all include the "menu.php" file. Here is the code in "default.php":
<?phpinclude("menu.php"); ?>
<h1>Welcome to my home page</h1>

<p>Some text</p>
</body>
</html>
PHP Include File
If you look at the source code of the "default.php" in a browser, it will look
something like this:
<html>
<body>
<ahref="default.php">Home</a> |
<ahref="about.php">About Us</a> |
<ahref="contact.php">Contact Us</a>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>
• And, of course, we would have to do the same thing for "about.php"
and "contact.php". By using include files, you simply have to update
the text in the "menu.php" file if you decide to rename or change the
order of the links or add another web page to the site.
PHP Include File
The require() Function
•The require() function is identical to include(), except that it handles errors differently.
•The include() function generates a warning (but the script will continue execution) while the require() function
generates a fatal error (and the script execution will stop after the error).
•If you include a file with the include() function and an error occurs, you might get an error message like the one
below.
PHP code:
•<html>
•<body>
•<?php
•include("wrongFile.php");
•echo "Hello World!";
•?>
•</body>
•</html>
Error message:
Warning:include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:homewebsitetest.phpon line 5
Warning:include() [function.include]:
Failed opening'wrongFile.php'for inclusion
(include_path='.;C:php5pear')
in C:homewebsitetest.phpon line 5
Hello World!
PHP Include File
• The echo statement was not executed because the script
execution stopped after the fatal error.
• It is recommended to use the require() function instead of
include(), because scripts should not continue executing if
files are missing or misnamed.
 HTTP Overview
 HTTP is the protocol (the set of 'rules') for transferring data (e.g.

HTML in web pages, pictures, files) between web servers and client
browsers, and usually takes place on port80. This is where the 'http://'
in website URLs comes from.

 Headers can be separated into two broad types: Request the headers

that your browser sends to the server when you request a file, and
Response headers that the server sends to the browser when it serves
the file.

 PHP header(): The Basics

 Using this function, you can make your scripts send headers of

your choosing to the browser, and create some very useful and
dynamic results. However, the first thing you need to know about
the header() function is that you have to use it before PHP has
sent any output (and therefore its default headers).
PHP slides


PHP header(): Some Examples

 header('Location:http://www.mysite.com/new_location.html');



While you can sometimes get away with supplying a relative URL for the value, according to
the HTTP specification, you should really use an absolute URL.
One mistake that is easy to make with the Location header is not calling exit directly
afterwards (you may not always want to do this, but usually you do). The reason this is a
mistake is that the PHP code of the page continues to execute even though the user has gone
to a new location. In the best case, this uses system resources unnecessarily. In the worst
case, you may perform tasks that you never meant to.





<?php
header('Refresh:10;url=http://www.mysite.com/otherpage.php');
echo'Youwillberedirectedin10seconds';
?>



Redirecting with the Refresh header



The Refresh redirects users like the Location header does, but you can add a delay before the
user is redirected. For example, the following code would redirect the user to a new page after
displaying the current one for 10 seconds
Serving different types of files and generating dynamic
content using the Content-Type header
 The Content-Type header tells the browser what type of data the server is about
to send. Using this header, you can have your PHP scripts output anything from
plaintext files to images or zip files. The table below lists frequently-used

MIME types:
<?php
header'Connt-Type:text/plain');
Echo $lain_text_content;
?>

 You can do several interesting things with this. For example, perhaps you want
to send the user a pre-formatted text file rather than HTML:
<?php
header('Content-Type:application/octet-stream'); // name of the File Name
header('Content-Disposition: attachment; '.'filename="plain_text_file.txt"'); // given name and with MIME type.
echo $plain_text_content;
?>

 Or perhaps you'd like to prompt the user to download the file, rather

than viewing it in the browser. With the help of the ContentDisposition header, it's easy to do, and you can even suggest a file name
for the user to use:
PHP String









A string variable is used to store and manipulate a piece of text.
Strings in PHP
String variables are used for values that contains character strings.
In this tutorial we are going to look at some of the most common
functions and operators used to manipulate strings in PHP.
After we create a string we can manipulate it. A string can be used
directly in a function or it can be stored in a variable.
Below, the PHP script assigns the string "Hello World" to a string
variable called $txt:
<?php$txt="Hello World"; echo $txt; ?>The output of the code above
will be:
HelloWorld Now, lets try to use some different functions and operators
to manipulate our string.
PHP String
• The Concatenation Operator
 There is only one string operator in PHP.
 The concatenation operator (.)is used to put two string values together.
 To concatenate two variables together, use the dot (.) operator:
<?php
$txt1="Hello World";

$txt2="1234";
echo $txt1 . " " . $txt2;

?>
 The output of the code above will be:
 Hello World 1234
 If we look at the code above you see that we used the concatenation

operator two times. This is because we had to insert a third string.
 Between the two string variables we added a string with a single
character, an empty space, to separate the two variables.
PHP String
Using the strlen() function
•The strlen() function is used to find the length of a string.
•Let's find the length of our string "Hello world!":

<?php
echo strlen("Hello world!");
?>
•The output of the code above will be:12
•The length of a string is often used in loops or other functions, when it is important to know when the string ends.
(i.e. in a loop, we would want to stop the loop after the last character in the string)

Using the strpos() function
•The strpos() function is used to search for a string or character within a string.
•If a match is found in the string, this function will return the position of the first match. If no match is found, it will
return FALSE.
•Let's see if we can find the string "world" in our string:

<?php
echo strpos("Hello world!","world");
?>
•The output of the code above will be:6

•As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7,
is that the first position in the string is 0, and not 1.
Commonly used String Functions














addslashes—Quote string with slashes
explode —Split a string by string
implode —Join array elements with a string
join —Alias of implode()
md5 —Calculate the md5 hash of a string
nl2br —Inserts HTML line breaks before all new lines in
a string
str_split —Convert a string to an array
strcmp—Binary safe string comparison
print —Output a string
strlen—Get string length
strtolower—Make a string lowercase
strtoupper—Make a string uppercase
trim —Strip whitespace(or other characters) from the
beginning and end of a string
 Other String Functions














number_format —Format a number with grouped thousands
rtrim—Strip whitespace (or other characters) from the end of a string
str_ireplace—Case-insensitive version of str_replace().
str_repeat —Repeat a string
str_replace —Replace all occurrences of the search string with the
replacement string
str_shuffle —Randomly shuffles a string
str_word_count —Return information about words used in a string
strcasecmp—Binary safe case-insensitive string comparison
strchr—Alias ofstrstr()
strcspn—Find length of initial segment not matching mask
stripos—Find position of first occurrence of a case-insensitive string
stripslashes—Un-quote string quoted with addslashes()
stristr—Case-insensitive strstr()
 Other String Functions (contd…)
 strnatcasecmp—Case insensitive string comparisons using a "natural order"














algorithm
strnatcmp—String comparisons using a "natural order" algorithm
strncasecmp—Binary safe case-insensitive string comparison of the first n characters
strncmp—Binary safe string comparison of the first n characters
strpbrk—Search a string for any of a set of characters
strpos—Find position of first occurrence of a string
strrchr—Find the last occurrence of a character in a string
strrev—Reverse a string
strripos—Find position of last occurrence of a case-insensitive string in a string
strrpos—Find position of last occurrence of a char in a string
strspn—Find length of initial segment matching mask
strstr—Find first occurrence of a string
substr_compare —Binary safe comparison of 2 strings from an offset, up to length
characters
substr_count —Count the number of substring occurrences
 Other String Functions (contd…)
 substr_replace —Replace text within a portion of a string
 substr—Return part of a string
 ucfirst—Make a string's first character uppercase
 ucwords—Uppercase the first character of each word in a string
 wordwrap—Wraps a string to a given number of characters
String Function Example
<?php
$str = "Hello, my name is Kai Jim.";
echo $str."<br />";
echo addcslashes($str,'m')."<br />";
echo addcslashes($str,'K')."<br />";
?>
Hello, my name is Kai Jim.
Hello, my name is Kai Jim.
Hello, my name is Kai Jim.
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
Hello World! Beautiful Day!
String Function Example
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo join(" ",$arr);
?>
Hello World! Beautiful Day!

<?php
$str = "Hello";
echo md5($str);
?>
8b1a9953c4611296a827abf8c47804d7 32
<?php
echo nl2br("One line.nAnother line.");
?>
One line.
Another line.
print_r(str_split("Hello",3));

$str = "Who's Kai Jim?";
print $str;
print "<br />";
print $str."<br />I don't know!";

Array ( [0] => Hel [1] => lo )
String Function Example
<?php
$str = "Hello";
$number = 123;
printf("%s world. Day number %u",$str,$number);
?> Hello world. Day number 123

<?php
echo strtolower("Hello WORLD.");
?>
<?php
echo strlen("Hello world!");
?>
DBMS&RDBS
PHP And MySQL
What is MySQL?
•MySQL is a database server
•MySQL is ideal for both small and large applications
•MySQL supports standard SQL
•MySQL compiles on a number of platforms
•MySQL is free to download and use

PHP + MySQL
•PHP combined with MySQL are cross-platform (means that you can
develop in Windows and serve on a Unix platform)

Where to Start?
•Install an Apache server on a Windows or Linux machine
•Install PHP on a Windows or Linux machine

•Install MySQL on a Windows or Linux machine
DBMS
•A database management system (DBMS) is a system, usually automated and
computerized, used to manage any collection of compatible, and ideally
normalized data.
•The DBMS manages storage and access to the data, and provides a query
language to specify actions associated with the data. The standard query
language is SQL.
•A DBMS generally provides a client application that can be used to directly
manipulate the data, as well as a programmable interface. MySQL provides a
set of command line clients, as well as a program interface.
Relational Databases
 Information is stored in tables. Tables store information

about entities
 Entities have characteristics called attributes
 Each row in a table represents a single entity Each row is a

set of attribute values Every row must be unique, identified
by a key
 Relationships --associations among the data values are

stored
PHP slides
MYSQL database and queries
Connecting to a MySQL Database
•Before you can access and work with data in a database, you must create a connection to the
database.
•In PHP, this is done with themysql_connect() function.
Syntax
•mysql_connect(servername,username,password);
•Example
mysql_connect(‘localhost’,root’,’’);

Closing a Connection
 The connection will be closed as soon as the script ends. To close the connection before, use
themysql_close() function.
PHP slides
PHP MySQL Create Database and Tables
• A database holds one or multiple tables.
Create a Database
• The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
CREATE DATABASE database_name
• To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example:- mysql_query(‘send’)
• In the following example we create a database called "my_db":
PHP MySQL Create Database and Tables
Create a Table
The CREATE TABLE statement is used to create a database table in MySQL.

Syntax
CREATE TABLE table_name

(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
.......
)
We must add the CREATE TABLE statement to the mysql_query() function to execute
the command.

Example
The following example shows how you can create a table named "person", with three
columns. The column names will be "First Name", "Last Name" and "Age"
Important: A database must be selected before a table can be created. The database is
selected with the mysql_select_db() function.

Note: When you create a database field of type varchar, you must specify the
maximum length of the field, e.g.varchar(15).
MySQL Data Types
 Below are the different MySQL data types that can be used:
MySQL Data Types
Database Terminology
 Primary Key:





Always Integer
Unique
Never Null
Auto-increment

 Foreign Key:




Foreign Key is a linking pin between two tables.
A key used in the one table to represent the value of the primary key in a
related table.
While primary key must contains unique values, foreign key must have
duplicates.


Ex: If we use student_id as a primary key in the student table (each student has
a unique id), we could use student id as a foreign key in a source table as each
student may do more than one course.
 Compound Key
 Compound key is a key that consists of 2 or more attributes that uniquely

identifies an entity occurrences.
 Each attribute that makes up the compound key is a simple key on its own.
Primary Keys and Auto Increment Fields
 Each table should have a primary key field.

 A primary key is used to uniquely identify the rows in a table. Each primary key
value must be unique within the table. Furthermore, the primary key field
cannot be null because the database engine requires a value to locate the

record.

 The primary key field is always indexed. There is no exception to this rule! You
must index the primary key field so the database engine can quickly locate rows
based on the key's value.
 The following example sets the person ID field as the primary key field. The
primary key field is often an ID number, and is often used with the
AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the
value of the field by1 each time a new record is added. To ensure that the
primary key field cannot be null, we must add the NOT NULL setting to the
field.
Normalization
The process of structuring data to minimize duplication and
inconsistencies.
•The process usually involves breaking down the single table into two or
more tables and defining relationships between those tables.
•Normalization is usually done in stages.
•Most people in creating database, never need to go to beyond the third
level of normalization.
 1. First Normal Form:
 2. Second Normal Form
 3. Third Normal Form
 First Normal Form:
 Eliminate duplicative columns from the same table.

 Create separate tables for each group related data and identify each row

with a unique columns.
 When a table is decomposed into two-dimensional tables with all
repeating groups of data eliminated ,the table data is said to be in it’s
1NF.
Field
Key
Type
 Example:Project number
-Project Name

--

Employee Number

--

1-n

Employee Name

--

1-n

Rate Category

--

1-n

Hourly rate

--

1-n

 N-1 indicates that there are many occurrences of this field – it is a

repeating group.
Project number

Project Name

Employee Number

Employee Name

Rate Category

Hourly rate

P001

PHP

E001

Taher

A

7000

P001

PHP

E002

Mohit

B

6500

P001

PHP

E006

Hansel

C

4500

P002

PHP(joomla)

E001

Taher

A

7000

P002

PHP(Joomla)

E007

Nitesh

B

4000
2ndNormal Form:
 A 1NF is in 2NF if and only if its non-prime attributes are functionally

dependent on a part of the candidate key.
 A table is said to be in it’s second normal form when each record in the
table is in the First normal form and each column in the record is fully
dependent on it’s primary key.
 Step: Find and Remove Fields that are related to the only part of the key.
 Group the removed items in the another table.
 Assign the new table with the key i.e part of a whole composite key.
2nd NF Example

Field

Key

Project Number

Primary Key

Employee Number

Primary Key

Field

Key

Employee Number

Primary key

Employee Name

--

Rate category

--

Hourly Rate

--

Project Number

Primary Key

Project Name

--

Table: Emproj

Table:- Emp

Table:- proj
3rdNormal Form
 If and only if
 The Relation is in second NF

 Every Non-prime attribute of R is non-transitively dependent on every

key of R.
 Table data is said to be in third normal format when all transitive
dependencies are removed from this data.
 A general case of transitive dependencies is follow: A,B,C are three columns in Table.
 If C is related to B
 If B is related to A
 Then C is indirectly related to A

 This is when transitive dependency exists.
3rd NF Example
Table :EmpProj
Project Number

Table: Emp
Primary Key

Employee Number

Primary Key

Primary Key

Hourly rate

--

Primary Key

Employee Name

--

Rate Category
Table:Rate
Rate Category

Employee Number

--

Table:proj
Project Number

Primary key

Project Name

There are another normal Forms such as
Boyce-Codd NF
4th Normal Form
But this are very rarely used for business application. In most case ,table that
are in 3rd NF are already conform to these type of table formats anyway.
PHP MySQL Insert Into


The INSERT INTO statement is used to insert new records into a database table
Insert Data Into a Database Table



The INSERT INTO statement is used to add new records to a database table .

Syntax


You can also specify the columns where you want to insert the data:
 INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

Note: SQL statements are not case sensitive. INSERT INTO is the same as insert into.
To get PHP to execute the statements above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.
Example:
$ins = insert into (id,unm,upass) values(‘’,’Taher’,’Taher’);
mysql_query($ins);
PHP MySQL Insert Into

Insert Data From a Form Into a Database
 Now we will create an HTML form that can be used to add new records

to the "Person" table.
 Here is the HTML form:
PHP MySQL Insert Into Query
•

When a user clicks the submit button in the HTML form in the example
above, the form data is sent to "insert.php". The "insert.php" file connects to a
database, and retrieves the values from the form with the PHP $_POST
variables. Then, the mysql_query() function executes the INSERT INTO
statement, and a new record will be added to the database table.

 Example of the code in the "insert.php" page
 If(isset($_request[‘’]))

{
$ins = “ insert into values(‘$_request[‘name’],$_request[‘age’]);
mysql_query(‘$ins’);
}
PHP MySQL Select

• The SELECT statement is used to select data from a database.
Select Data From a Database Table
• The SELECT statement is used to select data from a database.
 Syntax
SELECT column_name(s) FROM table_name
Note: SQL statements are not case sensitive. SELECT is the same as select.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.

The example above stores the data returned by the mysql_query() function in
the $result variable. Next, we use the mysql_fetch_array() function to return
the first row from the record set as an array. Each subsequent call to
mysql_fetch_array() returns the next row in the recordset. The while loop loops
through all the records in the recordset. To print the value of each row, we use
the PHP $row variable ($row['FirstName'] and $row['LastName']).
PHP MySQL Select
 The following example selects the same data as the example above, but

will display the data in an HTML table:
 The output of the code above will be:
PHP MySQL The Where Clause
• To select only data that matches a specified criteria, add a WHERE
clause to the SELECT statement.
The WHERE clause
 To select only data that matches a specific criteria, add a WHERE
clause to the SELECT statement.
 Syntax
PHP slides
PHP MySQL Order By Keyword
 The ORDER BY keyword is used to sort the data in are cordset.The

ORDER BY Keyword
 The ORDER BY keyword is used to sort the data in are cordset.
 Example:-

 SELECT column_name(s)FROM table_nameORDER BY

column_name
Diff Between Group by and order by

• The Group by can be specified after the select * from table
name and we can also use the where clause or having clause
for it, but in the case for order by we have to use the where
clause and after which the Order by should come
Example:-( for Group By)
select * from books group by book_name having book_rate > 10;

example for Order By
select * from books where book_rate > 10 order by book_name;
Example of Order by :Below simle tabel:

SELECT * FROM `registraton` ORDER BY user_name
LIMIT 0 , 30
Example of Group by

 SELECT count(*) "Total Indian Man" ,sum(pass)"sum of password"

FROM `registraton` group by contry
JOINS
 Different SQLJOINs
 Before we continue with examples, we will list the types of JOIN you can use, and

 the differences between them.
 JOIN: Return rows when there is at least one match in both tables
 LEFT JOIN: Return all rows from the left table, even if there are no matches in the

right table
 RIGHT JOIN: Return all rows from the right table, even if there are no matches in
the left table
 SQL INNER JOIN Keyword



The INNER JOIN keyword return rows when there is at least one match in both tables.
SQL INNER JOIN Syntax

Example:- SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name

 Note: INNER JOIN is the same as JOIN.
Join(inner)
Consider the following SQL statement:
SELECT Customers.FirstName, Customers.LastName,
SUM(Sales.SaleAmount) AS
SalesPerCustomer
FROM Customers, Sales
WHERE Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName
The SQL expression above will select all distinct customers (their first
and last names) and the total respective amount of dollars they have
spent.
The SQL JOIN condition has been specified after the SQL WHERE
clause and says that the 2 tables have to be matched by their respective
CustomerID columns.
Joins (contd…)
 There are 2 types of SQL JOINS –INNER JOINS and OUTER JOINS. If

you don't put INNER or OUTER keywords in front of the SQL JOIN
keyword, then INNER JOIN is used. In short "INNER JOIN" = "JOIN"
(note that different databases have different syntax for their JOIN
clauses).
 The INNER JOIN will select all rows from both tables as long as there
is a match between the columns we are matching on. In case we have a
customer in the Customers table, which still hasn't made any orders
(there are no entries for this customer in the Sales table), this customer
will not be listed in the result of our SQL query above.
Outer Join
 The second type of SQL JOIN is called SQL OUTER JOIN and it has 2

sub-types called LEFT OUTER JOIN and RIGHT OUTER JOIN.
 The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the

OUTER keyword in most databases), selects all the rows from the first
table listed after the FROM clause, no matter if they have matches in
the second table.
PHP MySQL Order By Keyword
Sort Ascending or Descending
• If you use the ORDER BY keyword, the sort-order of there cordset is ascending by default (1 before 9
and "a" before "p").
• Use the DESC keyword to specify a descending sort-order (9 before 1 and "p" before "a"):

Order by Two Columns
•It is possible to order by more than one column. When ordering by more than one column, the second
column is only used if the values in the first column are identical:
PHP slides
PHP slides
Sessions and Cookies in PHP
PHP Cookies
A message given to a Web browser by a Web server. The browser stores the message in a text
file. The message is then sent back to the server each time the browser requests a page
from the server.
•A cookie is often used to identify a user
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on
the user's computer. Each time the same computer requests a page with a browser, it will
send the cookie too. With PHP, you can both create and retrieve cookie values.
How to Create a Cookie?
•The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
•setcookie(name, value, expire, path, domain);
Example Cookies
Set Cookies:<?php
setcookie("user","tom",time()+3660);
echo "cookie is set";
?>
Retrieve Cookies:<?php
echo "Cookie value is ".$_COOKIE['user'];
?>
• In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We
also specify that the cookie should expire after one hour

<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
<body>
</body>
</html>
Note: The value of the cookie is automatically URL encoded when sending the cookie, and automatically
decoded when received (to prevent URLencoding, use set raw cookie() instead).
PHP slides
PHP Cookies
How to Delete a Cookie?
•When deleting a cookie you should assure that the expiration date is in the past.
•Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
The form below passes the user input to "welcome.php" when the user clicks on the
"Submit" button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
Retrieve the values in the "welcome.php" file like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br/>
You are <?php echo $_POST["age"]; ?> years old.
</body>
PHP Sessions
•A PHP session variable is used to store information about, or change
settings for a user session. Session variables hold information about
one single user, and are available to all pages in one application.
PHP Session Variables
•When you are working with an application, you open it, do some changes
and then you close it. This is much like a Session. The computer knows
who you are. It knows when you start the application and when you
end. But on the internet there is one problem: the web server does not
know who you are and what you do because the HTTP address doesn't
maintain state.
•A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping items,
etc). However, session information is temporary and will be deleted
after the user has left the website. If you need a permanent storage you
may want to store the data in a database.
•Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.
 PHP Sessions – Overview
 A PHP session solves this problem by allowing you to store user

information on the server for later use (i.e. username, shopping cart
items, etc). However, this session information is temporary and is
usually deleted very quickly after the user has left the website that uses
sessions.

 It is important to ponder if the sessions' temporary storage is applicable

to your website. If you require a more permanent storage you will need
to find another solution, like a MySQL database.
 Sessions work by creating a unique identification (UID) number for
each visitor and storing variables based on this ID. This helps to
prevent two users' data from getting confused with one another when
visiting the same webpage.
 Note: If you are not experienced with session programming it is not

recommended that you use sessions on a website that requires highsecurity, as there are security holes that take some advanced techniques
to plug.
Starting a PHP Session
 Before you can begin storing user information in your PHP session, you

must first start the session. When you start a session, it must be at the
very beginning of your code, before any HTML or text is sent.
 Below is a simple script that you should place at the beginning of your
PHP code to start up a PHP session.
 PHP Code:



This tiny piece of code will register the user's session with the server, allow you to start saving
user information and assign a UID (unique identification number) for that user's session.
PHP Sessions
Starting a PHP Session
• Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>
<html>
<body>
</body>
</html>
• The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.
Storing a Session Variable
•The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
PHP Sessions
Output:
•Pageviews=1
•In the example below, we create a simple page-views counter. The isset()
function checks if the "views" variable has already been set. If "views" has
been set, we can increment our counter. If "views" doesn't exist, we create a
"views" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
PHP Sessions
Destroying a Session
• If you wish to delete some session data, you can use the unset()or the
session_destroy() function.
• The unset() function is used to free the specified session variable:

<?php
unset($_SESSION['views']);
?>
•You can also completely destroy the session by calling the session_destroy()
function:

<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your
stored session data.
Understanding session
 This piece of code does one of two things. If the user does not already

have a session, it creates a new session -or -if the user does already have
a session it connects to the existing session file. When a new session is
created, PHP session management generates a session identifier that
consists of a random 32 hex digit string and creates an empty session
file on the server with the name sess_ followed by the session
identifier. It also includes a set-cookie in the response and a session
cookie in the browser with the value of the session identifier. This
means that any subsequent request to the server will include this
session identifier allowing PHP to connect to the appropriate session
file.

 <?php session_start(); ?>
Session Example: Create Login.php
Session Example
 Create Welcome.php
Session Example
 Make Logout.php
Files and Directory Access
PHP File Upload
Restrictions on Upload
•In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files
and the file size must be under 20 kb:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br/>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br/>";
echo "Type: " . $_FILES["file"]["type"] . "<br/>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br/>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
Note: For IE to recognize jpg files the type must be p jpeg, for Fire Fox it must be jpeg.
PHP File Upload

Saving the Uploaded File
•The examples above create a temporary copy of the uploaded filesin the PHP temp folder on the server.
•The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br/>";
echo "Type: " . $_FILES["file"]["type"] . "<br/>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br/>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br/>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
•The script above checks if the file already exists, if it does not, it copies the file to the specified folder.
Note:This example saves the file to a new folder called "upload"
PHP slides
Multiple File Upload
 Example:-imgck.php
 Example:- img.php
Also Make a Folder:- upimg
Another Example
<form action="" method="post“ enctype="multipart/form-data">
<p>Pictures: <input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach($_FILES["pictures"]["error"]as$key=>$error){
if($error==UPLOAD_ERR_OK){
$tmp_name=$_FILES["pictures"]["tmp_name"][$key];
$name=$_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name,"data/$name");
}
}
?>
PHP File Handling
PHP File Handling
•The fopen() function is used to open files in PHP.
 Opening a File

•
The fopen() function is used to open files in PHP.
•The first parameter of this function contains the name of the file to be opened and the
second parameter specifies in which mode the file should be opened:
<html>
<body>
<?php $file=fopen("welcome.txt","r");?>
</body>
</html>
•The file may be opened in one of the following modes:
PHP File Handling
•Note: If the fopen() function is unable to open the specified file, it returns 0
(false).
Example
•The following example generates a message if the fopen() function is unable to
open the specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>

</body>
</html>
Closing a File
•The fclose() function is used to close an open file:
<?php
$file =fopen("test.txt","r");//some code to beexecutedfclose($file);

?>
PHP File Handling
Check End-of-file
•The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
Note: You cannot read from files opened in w, a, and x mode!

•if (feof($file)) echo "End of file";
Reading a File Line by Line
•The fgets() function is used to read a single line from a file.
Note :After a call to this function the file pointer has moved to the next line.

Example
•The example below reads a file line by line, until the end of file is reached:

<?php
$file =fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))

{
echofgets($file). "<br/>";

}
fclose($file);
?>
PHP File Handling
Reading a File Character by Character
•The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer moves to the next
character.
Example
•The example below reads a file character by character, until the end of file is
reached:

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
Example Of File Handling
php - file write: fwrite function
 PHP Code:
 $myFile = "testFile.txt"; $fh = fopen($myFile, 'w');
 We can use php to write to a text file. The fwrite function allows data to be written to any
type of file. Fwrite's first parameter is the file handle and its second parameter is the
string of data that is to be written. Just give the function those two bits of information
and you're good to go!

$myFile = "testFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Boppern";
fwrite($fh, $stringData);
$stringData = "Tracy Tannern";
fwrite($fh, $stringData);
fclose($fh);
 The $fh variable contains the file handle for testFile.txt. The file handle knows the

current file pointer, which for writing, starts out at the beginning of the file.
 We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the
string $stringData that first contained Bobby Bopper and second contained Tracy
Tanner. After we finished writing we closed the file using the fclose function.
Handling e-mail
PHP Sending E-Mails
•PHP allows you to send e-mails directly from a script.
The PHP mail() Function
•The PHP mail() function is used to send emails from inside a script.
Syntax
•mail(to,subject,message,headers,parameters)
•Note:
For the mail functions to be available, PHP requires an installed and working email
system. The program to be used is defined by the configuration settings in the php.ini
file.
PHP Sending E-Mails
PHP Simple E-Mail
• The simplest way to send an email with PHP is to send a text email.
• In the example below we first declare the variables ($to, $subject,
$message, $from, $headers), then we use the variables in the mail()
function to send an e-mail:

<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";

?>
PHP Sending E-Mails
•With PHP, you can create a feedback-form on your website. The example below sends a text message to a specified e-mail
address:
<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail( "someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br/>
Subject: <input name='subject' type='text' /><br/>
Message:<br/>
<textareaname='message' rows='15' cols='40'>
</textarea><br/>
<input type='submit' />
</form>";
}
?>
</body>
</html>
PHP Secure E-mails
• There is a weakness in the PHP e-mail script in the previous chapter.
• PHP E-mail Injections
• First, look at the PHP code from the previous chapter:
<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br/>
Subject: <input name='subject' type='text' /><br/>
Message:<br/>
<textareaname='message' rows='15' cols='40'>
</textarea><br/>
<input type='submit' />
</form>";
}
?>
</body>
</html>
PHP Secure E-mails
The problem with the code above is that unauthorized users can insert data into
the mail headers via the input form.
• What happens if the user adds the following text to the email input field in the form?

someone@example.com%0ACc:person2@example.com
%0ABcc:person3@example.com,person3@example.com,
anotherperson4@example.com,person5@example.com
%0ABTo:person6@example.com
•The mail() function puts the text above into the mail headers as usual, and now the
header has an extra Cc:, Bcc:, and To: field. When the user clicks the submit button,
the e-mail will be sent to all of the addresses above!

PHP Stopping E-mail Injections
•The best way to stop e-mail injections is to validate the input.

•The code below is the same as in the previous chapter, but now we have added an
input valuator that checks the email field in the form:
<html>
<body>
<?php
{

function spamcheck($field)
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))

{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck=spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
}
else
{//if "email" is not filled out, display the form
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br/>
Subject: <input name='subject' type='text' /><br/>
Message:<br/>
<textarea name='message' rows='15' cols='40'>
</textarea><br/>
<input type='submit' />
</form>";
}
?>
</body>
</html>
<form action="" method="post">
<?php
function spamcheck($fld)
// Othe Example:{
$field=filter_var($fld,FILTER_SANITIZE_EMAIL);
if(filter_var($field,FILTER_VALIDATE_EMAIL))
{
return true;
}
else
{
return false;
}

}
if(isset($_REQUEST['email']))
{
$mailcheck=spamcheck($_REQUEST['email']);
if($mailcheck==false)
{
echo "Invalid email address";
}
else
{
$email=$_REQUEST['email'];
$sub=$_REQUEST['sub'];
$msg=$_REQUEST['msg'];
mail(“taher@gmail.com",$sub,$msg,"From: $email")or die("ERROR");
echo "Thank you for using services";
}
}
else
{
?>
Your email add: <input type="text" name="email" /><br /><br />
Subject : <input type="text" name="sub" /><br /><br />
Message : <input type="text" name="msg" /><br /><br />
<input type="submit" value="send" />
<?php
}
?>
</form>
PHP slides
JAVA Script
Introduction
 JavaScript is a cross-platform, object-oriented scripting language

invented in web browsers to make web pages more dynamic and give
feedback to your user. Adding JavaScript to your HTML code allows you
to change completely the document appearance, from changing text, to
changing colors, or changing the options available in a drop-down list,
or switching one image with another when you roll your mouse over it
and much more.

 JavaScript is mainly used as a client side scripting language. This means

that all the action occurs on the client's side of things. When a user
requests an HTML page with JavaScript in it, the script is sent to the
browser and it's up to the browser to do something with it.
What can JavaScript do?


Here are a few things you can do with JavaScript:
 Display information based on the time of the day
 JavaScript can check the computer's clock and pull the appropriate data based on the clock
information.
 Detect the visitor's browser
 JavaScript can be used to detect the visitor's browser, and load another page specifically
designed for that browser.
 Control Browsers
 JavaScript can open pages in customized windows, where you specify if the browser's buttons,
menu line, status line or whatever should be present.
 Validate forms data
 JavaScript can be used to validate form data at the client-side saving both the precious server
resources and time.
 Create Cookies
 JavaScript can store information on the visitor's computer and retrieve it automatically next
time the user visits your page.
 Add interactivity to your website
 JavaScript can be set to execute when something happens, like when a page has finished
loading or when a user clicks on a button.
 Change page contents dynamically
 JavaScript can randomly display content without the involvement of server programs .It can
read and change the content of an HTML elements or move them around
How to implement JavaScript to an HTML page
•You can link to outside files (with the file extension .js), or write blocks of code
right into your HTML documents with the <script> tag. So, the <script
type="text/javascript"> and </script> tells where the JavaScript starts and ends.
<html>
<head>
<title>My First Script</title>
</head>
<body>
<script type="text/javascript">
<!-//-->
</script>
</body>
</html>
Functions
• Defining
<script type="text/javascript">
function function_name (argument_1, ... , argument_n)
{statement_1;
statement_2;
statement_m;
return return_value;

}
</script>
Example
<html>
<head>
<script type="text/javascript">
function showmessage() {
alert(“JavaScript !");
}
</script>
</head>
<body>
<form name="myform">
<input type="button" value="Click me!“ onclick="showmessage()">
</form>
</body>
</html>
PHP slides
Form Validation
 Any interactive web site has form input -a place where the users input

different kind of information. This data is passed to script, or some
other technology and if the data contains an error, there will be a delay
before the information travels over the Internet to the server, is
examined on the server, and then returns to the user along with an
error message.
 If you run a validation of the user’s form input before the form is
submitted, there will be no wait time and redundant load on the server.
"Bad data" are already filtered out when input is passed to the serverbased program.
 Client side form validation usually done with JavaScript. For the
majority of your users, JavaScript form validation will save a lot of time
up front, but double-checking the data on the server remains
necessary, in case the user has turned JavaScript off.
Events
•Events
•By using JavaScript, we have the ability to create dynamic web pages.
Events are actions that can be detected by JavaScript.
•Every element on a web page has certain events which can trigger
JavaScript. For example, we can use the onClickevent of a button
element to indicate that a function will run when a user clicks on
the button. We define the events in the HTML tags.
•Examples of events:
•* A mouse click
• * A web page or an image loading
• *Mousing over a hot spot on the web page
• * Selecting an input field in an HTML form
• * Submitting an HTML form
•* A keystroke
Events
• Note: Events are normally used in combination with functions, and the
function will not be executed before the event occurs!
• For a complete reference of the events recognized by JavaScript, go to
our complete Event reference.
• onLoad and onUnload
• The onLoad and onUnload events are triggered when the user enters or
leaves the page.
• The onLoad event is often used to check the visitor's browser type and
browser version, and load the proper version of the web page based on
the information.
• Both the onLoad and onUnload events are also often used to deal with
cookies that should be set when a user enters or leaves a page. For
example, you could have a popup asking for the user's name upon his
first arrival to your page. The name is then stored in a cookie. Next time
the visitor arrives at your page, you could have another popup saying
something like: "Welcome John Doe!".
• onFocus, onBlur and onChange
Events
• The onFocus,onBlurandonChangeevents are often used
in combination with validation of form fields.
• Below is an example of how to use the onChange event.
The checkEmail() function will be called whenever the
user changes the content of the field:
• <input type="text" size="30" id="email“
onchange="checkEmail()">
• onSubmit
Events
• onMouseOver and onMouseOut
• onMouseOver and onMouseOut are often used to create "animated"
buttons.
• Below is an example of an onMouseOver event. An alert box appears
when an event is detected:onMouseOver
<ahref="http://www.w3schools.com"onmouseover="alert('onMouseOv
erevent');return false"><img src="w3s.gif" alt="W3Schools" /></a>
Example:<A HREF="jmouse.htm" onMouseover="window.status='Hi there!'; return
true"
onMouseout="window.status=' '; return true">Place your mouse here!</A>
PHP slides
example
<html>
<head>
<title>JavascriptForm Validation</title>
<script language='JavaScript' type='text/JavaScript'>
<!-function validate() {
if(document.form1.textinput.value=='')
{
alert('Fill the Input box before submitting');
return false;
}
else{
return true;
}
}
//-->
</script>
</head>
<body>
<form name='form1' action='javascript_validation.php‘ method='post'
onSubmit='return validate();'>
Input :<input type=text name=textinput value=''>
<input type=submit value=submit>
</form>
</body>
</html>
Form data that typically are checked by a JavaScript
could be:
 Required fields
 Valid user name
 Valid password
 Valid e-mail address
 Valid phone number
Regular Expression
•The RegExpobject is used to specify what to search for in a text
•RegExp, is short for regular expression.
•When you search in a text, you can use a pattern to describe what you are
searching for.RegExpIS this pattern.
A simple pattern can be a single character.
•A more complicated pattern consists of more characters, and can be used
for parsing, format checking, substitution and more.
•Methods of the RegExpObject
•The RegExpObject has 3 methods: test(), exec(), and compile().
•test()
•The test() method searches a string for a specified value. Returns true or
false
•Example:
•varpatt1=newRegExp("e"); document.write(patt1.test("The best things in
life are free"));
Validate FormOnSubmit( )
•This is a main function that calls a series of subfunctions, each of which checks a single
form element for compliance. If the element complies than subfunction returns an
empty string. Otherwise it returns a message describing the error and highlight
appropriate element with yellow.

Function validateFormOnSubmit(theForm)
{
varreason = "";
reason +=validateUsername(theForm.username);
reason +=validatePassword(theForm.pwd);
reason +=validatePhone(theForm.phone);
if (reason != "") {
alert("Some fields need correction:n" + reason);
return false;
}
return true;
}
validateEmpty( )
•The function below checks if a required field has been left
empty. If the required field is blank, we return the error
string to the main function. If it’s not blank, the function
returns an empty string.
Function validateEmpty(fld){
var error = "";
if (fld.value.length == 0) {
error = "The required field has not been filled in.n"
}
return error;

}
ValidateUsername( )
• The function below checks if the user entered anything at all in the username field. If
it’s not blank, we check the length of the string and permit only usernames that are
between5 and 15 characters. Next, we use the JavaScript regular expression /W/ to
forbid illegal characters from appearing in usernames. We want to allow only letters,
numbers and underscores.

functionvalidateUsername(fld){
Var error = "";
var illegalChars= /W/; // allow letters, numbers, and underscores
if (fld.value == "") {
error = "You didn't enter a username.n";
} else if ((fld.value.length < 5) || (fld.value.length > 15)) {
error = "The username is the wrong length.n";
} else if (illegalChars.test(fld.value)) {
error = "The username contains illegal characters.n";
} else {
}
return error;
}
validatePassword( )
•The function below checks the password field for blankness and allow only letters and numbers –
no underscopes this time. So we should use a new regular expression to forbid underscopes. This
one /[W_]/ allow only letters and numbers. Next, we want to permit only passwords that
contain letters and at least one numeral. For that we use the search() method and two more
regular expressions: /(a-z)+/ and /(0-9)/.

functionvalidatePassword(fld){
varerror = "";
var illegalChars= /[W_]/; // allow only letters and numbers
if (fld.value == "") {
error = "You didn't enter a password.n";
} else if ((fld.value.length < 7) || (fld.value.length > 15)) {
error = "The password is the wrong length. n";
} else if (illegalChars.test(fld.value)) {
error = "The password contains illegal characters.n";
} else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
error = "The password must contain at least one numeral.n";
} else {
}
return error;
}
PHP slides
 JavaScript Form Submit Example

The code:
<form name="myform" action="handle-data.php">
Search: <input type='text' name='query'>
<A href="javascript: submitform()">Search</A>
</form>
<SCRIPT language="JavaScript">
function submitform()
{
document.myform.submit();
}
</SCRIPT>
<html>
<head>
<title>JavascriptForm Validation</title>
<script language='JavaScript' type='text/JavaScript'>

<!-function validate() {
if(document.form1.textinput.value=='')

{
alert('Fill the Input box before submitting');

return false;
}
else{
return true;
}
}
//-->
</script>
</head>
<body>
<form name='form1' action='javascript_validation.php‘ method='post'
onSubmit='return validate();'>
Input :<input type=text name=textinput value=''>
<input type=submit value=submit>

</form>
</body>
<form name="demo“ onsubmit="returnvalidateFormOnSubmit(this)" action="test.htm">
<table summary="Demonstration form">
<tbody>
<tr>
<td><label for="username">Your user name:</label></td>
<td><input name="username" size="35"maxlength="50" type="text"></td>
</tr>
<tr>
<td><label for="pwd">Your password</label></td>
<td><input name="pwd" size="35"maxlength="25" type="password"></td>
</tr>
<tr>
<td><label for="email">Your email:</label></td>
<td><input name="email" size="35"maxlength="30" type="text"></td>
</tr>
<tr>
<td><label for="phone">Your telephone number:</label></td>
<td><input name="phone" size="35"maxlength="25" type="text"></td>
</tr>
<tr>
<td>
<label for="from">Where are you :</label></td>
<td><input name="from" size="35"maxlength="50" type="text"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input name="Submit" value="Send" type="submit" ></td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
</form>
PHP slides
PHP slides
PHP slides
PHP slides
PHP slides
PHP slides
PHP And AJAX
Ajax (programming)
 Ajax (shorthand for asynchronous JavaScript + XML) is a group of interrelated web
development techniques used on the client-side to create interactive web applications.
With Ajax, web applications can retrieve data from the server asynchronously in the
background without interfering with the display and behavior of the existing page. The
use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web
pages and better quality of Web services due to the asynchronous mode. Data is usually
retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not
actually required, nor do the requests need to be asynchronous.
 XMLHttpRequest (XHR) is a DOM API that can be used inside a web browser scripting
language, such as JavaScript, to send an HTTP or an HTTPS request directly to a web
server and load the server response data directly back into the scripting language.[1] Once
the data is within the scripting language, it is available as both an XML document, if the
response was valid XML markup, and as plain text. The XML data can be used to
manipulate the currently active document in the browser window without the need of the
client loading a new web page document. Plain text data can be evaluated within the
scripting language to manipulate the document, too; in the example of JavaScript, the
plain text may be formatted as JSON by the web server and evaluated within JavaScript to
create an object of data for use on the current DOM.
 XMLHttpRequest has an important role in the AJAX web development technique. It is
currently used by many websites to implement responsive and dynamic web applications.
Examples of these web applications include Gmail, Google Maps, Bing Maps,
the MapQuest dynamic map interface, Facebook, and others.
PHP And AJAX
AJAX = Asynchronous JavaScript And XML
•AJAX is an acronym for Asynchronous JavaScript And XML.
•AJAX is not a new programming language, but simply a new technique for
creating better, faster, and more interactive web applications.
•AJAX uses JavaScript to send and receive data between a web browser and a
web server.
•The AJAX technique makes web pages more responsive by exchanging data
with the web server behind the scenes, instead of reloading an entire web
page each time a user makes a change.

AJAX Is Based On Open Standards
•AJAX is based on the following open standards:

•JavaScript
•XML
•HTML
•CSS
• The open standards used in AJAX are well defined, and supported by
all major browsers. AJAX applications are browser and platform
independent. (Cross-Platform, Cross-Browser technology)
PHP And AJAX

AJAX Is About Better Internet Applications
•Web applications have many benefits over desktop applications:
•they can reach a larger audience
•they are easier to install and support
•they are easier to develop
•However, Internet applications are not always as "rich" and userfriendly as traditional desktop applications.
•With AJAX, Internet applications can be made richer (smaller, faster,
and easier to use).

You Can Start Using AJAX Today
•There is nothing new to learn.
•AJAX is based on open standards. These standards have been used by
most developers for several years.

•Most existing web applications can be rewritten to use AJAX
technology instead of traditional HTML forms.
PHP And AJAX

AJAX Uses XML And HTTP Requests
 A traditional web application will submit input (using an HTML form)
to a web server. After the web server has processed the data, it will
return a completely new web page to the user.
 Because the server returns a new web page each time the user submits

input, traditional web applications often run slowly and tend to be less
user friendly.

 With AJAX, web applications can send and retrieve data without

reloading the whole web page. This is done by sending HTTP requests
to the server (behind the scenes), and by modifying only parts of the
web page using JavaScript when the server returns data.

 XML is commonly used as the format for receiving server data,

although any format, including plain text, can be used.
PHP And AJAX
PHP and AJAX
•There is no such thing as an AJAX server.
•AJAX is a technology that runs in your browser. It uses
asynchronous data transfer (HTTP requests) between
the browser and the web server, allowing web pages to
request small bits of information from the server instead
of whole pages.
•AJAX is a web browser technology independent of web
server software.

•However, in this tutorial we will focus more on
actual examples running on a PHP server, and less
on how AJAX works.
AJAX XMLHttpRequest
• The XMLHttpRequestobject makes AJAX possible.
The XMLHttpRequest
•The XMLHttpRequestobject is the key to AJAX.
•It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully
discovered before people started to talk about AJAX and Web 2.0 in 2005.
Creating An XMLHttpRequestObject
•Different browsers use different methods to create an XMLHttpRequest object.
•Internet Explorer uses an ActiveXObject.
•Other browsers uses a built in JavaScript object called XMLHttpRequest.
•Here is the simplest code you can use to overcome this problem:
AJAX XMLHttpRequest

• First create a variable XMLHttpto use as your XMLHttpRequestobject. Set the
value to null.
• Then test if the object window.XMLHttpRequestis available. This object is
available in newer versions ofFirefox,Mozilla, Opera, and Safari.
• If it's available, use it to create a new object:XMLHttp=newXMLHttpRequest()
• If it's not available, test if an object window.ActiveXObjectis available. This object
is available in Internet Explorer version 5.5 and later.
• If it is available, use it to create a new object:XMLHttp=newActiveXObject()
function disp_state()
{
var xmlhtp=null;
try
{
xmlhtp = new XMLHttpRequest();
alert("You are using mozilla");
}
catch(e)
{
try
{
xmlhtp = new ActiveXObject("Microsoft.XMLHTTP");
alert("You are using IE");
}
catch(e)
{
try
{
xmlhtp=new ActiveXObject("Msxml2.XMLHTTP");
alert("You are using IE");
}
catch(e)
{
alert("Your Browser Does Not Support Javascript");
}
}
}
cat=document.getElementById('txtb_userid').value;
xmlhtp.open("GET","get_state.php?cate="+cat,true);
xmlhtp.send(null);
xmlhtp.onreadystatechange=function()
{
if(xmlhtp.readyState==4)
{
document.getElementById('div_state').innerHTML=xmlhtp.responseText;
//
document.getElementById('div_product_photo_upload').innerHTML="<input type='file' name='f1' id='f1' onchange='show_image()' />";
}
}
}
 AJAX - More about the XMLHttpRequest object
 Before sending data off to a server, we will look at three important properties of the
XMLHttpRequest object.
 The onreadystatechange property
 After a request to a server, we need a function to receive the data returned from the
server.
 The onreadystatechange property stores the function that will process the response from
a server. The function is stored in the property to be called automatically.
 The following code sets the onreadystatechange property and stores an empty function
inside it:
PHP slides
PHP And AJAX Suggest
AJAX Suggest

•In the AJAX example below we will demonstrate how a
web page can communicate with a web server online as a
user enters data into a web form.

Type a Name in the Box Below

Suggestions:
This example consists of three pages:
•a simple HTML form
•a JavaScript
•a PHP page
PHP And AJAX Suggest
The HTML Form

•This is the HTML page. It contains a simple HTML form and a linkto a
JavaScript:

•HTML Form
<html>
<head>
<scriptsrc="clienthint.js"></script>

</head>
<body>
<form>
First Name: <input type="text" id="txt1"onkeyup="showHint(this.value)">

</form>
<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>
var xmlHttp
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML=""

return
}
xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")

return
}
var url="gethint.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)

xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 ||xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
functionGetXmlHttpObject()
{
var xmlHttp=null;
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp=newXMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=newActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=newActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
PHP slides
OOPS Concepts
Class
Every class definition begins with the keyword class, followed by a class
name, which can be any name that isn't a reserved word in PHP.
Followed by a pair of curly braces, which contains the definition of the
classes members and methods. A pseudo-variable, $this is
available
when a method is called from within an object context. $this is a
reference to the calling object (usually the object to which the method
belongs, but can be another object, if the method is called statically
from the context of a secondary object). This is illustrated in the
following examples
Example 19.2. Simple Class definition
<?php
class SimpleClass
{
// member declaration
public $var = 'a default value';
// method declaration
public function displayVar()
{
echo $this->var;
}
}
<?php
class A
{
function foo()
{
if (isset($this))
{
echo '$this is defined (';
echo get_class($this);
echo ")n";
} else {
echo "$this is not defined.n";
}
}
}
class B
{
function bar()
{
A::foo();
}
}
$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>
//The above example will output:
$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.
Example 19.5. Object Assignment
<?php
$instance->var = '$assigned will have this value';
$assigned = $instance;
$reference =& $instance;
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
The above example will output:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=> string(30) "$assigned will have this value“
}
Extends
A class can inherit methods and members of another class by using the extends
keyword in the declaration. It is not possible to extend multiple classes, a
class can only inherit one base class.
The inherited methods and members can be overridden, unless the parent class
has defined a method as final by redeclaring them with the same name
defined in the parent class. It is possible to access the overridden methods or
static members by referencing them with parent:: .
Visibility
The visibility of a property or method can be defined by prefixing the declaration
with the keywords: public, protected or private. Public Declared items can be
accessed everywhere. Protected limits access to inherited and parent classes
(and to the class that defines the item). Private limits visibility only to the class
that defines the item.

Members Visibility
Class members must be defined with public, private, or protected.
 Member Variable declaration (Example of extends)
<?php
/**
* Define MyClass
*/
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


Member function declaration (Example of extends)

<?php
/**
* Define MyClass
*/
class MyClass
{
// Contructors must be public
public function __construct() { }
// Declare a public method
public function MyPublic() { }
// Declare a protected method
protected function MyProtected() { }
// Declare a private method
private function MyPrivate() { }
// This is public
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work
 access parent class methods
class MyClass2 extends MyClass
{
// This is public
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // Fatal Error
}
}
$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private
 Example of extends
class Bar
{
public function test()
{
$this->testPrivate();
$this->testPublic();
}
public function testPublic()
{
echo "Bar::testPublicn";
}
private function testPrivate()
{
echo "Bar::testPrivaten";
}
}
class Foo extends Bar
{
public function testPublic()
{
echo "Foo::testPublicn";
}
private function testPrivate()
{
echo "Foo::testPrivaten";
}
}
$myFoo = new foo();
$myFoo->test();
//Output……………
Bar::testPrivate
Foo::testPublic
Constructor
void __construct

( [mixed $args [, $...]] )
PHP 5 allows developers to declare constructor methods for classes.
Classes which have a constructor method call this method on each
newly-created object, so it is suitable for any initialization that the
object may need before it is used.
Note: Parent constructors are not called implicitly if the child class
defines a constructor. In order to run a parent constructor, a call to

parent::__construct()
within the child constructor is required.
Example 19.8. using new unified constructors
<?php
class BaseClass
{
function __construct()
{
print "In BaseClass constructorn";
}
}
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructorn";
}
}
$obj = new BaseClass();
$obj = new SubClass();
?>
For backwards compatibility, if PHP 5 cannot find a __construct()
function for a given class, it will search for the old-style constructor
function, by the name of the class.

Destructor
void __destruct( void )

PHP 5 introduces a destructor concept similar to that of
other object-oriented languages, such as C++. The
destructor method will be called as soon as all references to
a particular object are removed or when the object is
explicitly destroyed or in any order in shutdown sequence.
<?php
class MyDestructableClass
{
function __construct()
{
print "In constructorn";
$this->name = "MyDestructableClass";
}
function __destruct()
{
print "Destroying " . $this->name . "n";
}
}
$obj = new MyDestructableClass();
?>
Scope Resolution Operator (::)
The Scope Resolution Operator (also called Paamayim Nekudotayim)or
in simpler terms, the double colon, is a token that allows access to
static, constant, and overridden members or methods of a class.
When referencing these items from outside the class definition, use the name
of the class.
Example : from outside the class definition
<?php
Class MyClass
{
const CONST_VALUE = 'A constant value';
}
echo MyClass:: CONST_VALUE;
?>
Example : from inside the class definition
<?php
class OtherClass extends MyClass
{
public static $my_static = 'static var';
public static function doubleColon()
{
echo parent::CONST_VALUE . "n";
echo self::$my_static . "n";
}
}
$classname = 'OtherClass';
echo $classname::doubleColon();
OtherClass::doubleColon();
?>
When an extending class overrides the parents definition of a method,
PHP will not call the parent's method. It's up to the extended class on
whether or not the parent's method is called. This also applies to
Constructors and Destructors, Overloading,and Magic method
definitions.
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()n";
}
}
class OtherClass extends MyClass
{
// Override parent's definition
public function myFunc()
{
// But still call the parent function
parent::myFunc();
echo "OtherClass::myFunc()n";
}
}
$class = new OtherClass();
$class->myFunc();
Static Keyword
Declaring class members or methods as static makes them
accessible without needing an instantiation of the class.
A member declared as static can not be accessed with an
instantiated class object (though a static method can).
For compatibility with PHP 4, if no as if it was declared as public. visibility
declaration is used, then the member or method will be treated
Because static methods are callable without an instance of the object
created, the pseudo variable not available inside the method declared
as static.
Static properties cannot be accessed through the object using the
arrow operator ->.
class Foo
{
public static $my_static = 'foo';
public function staticValue()
{
return self::$my_static;
}
}
class Bar extends Foo
{
public function fooStatic()
{
return parent::$my_static;
}
}
print Foo::$my_static . "n";
$foo = new Foo();
print $foo->staticValue() . "n";
print $foo->my_static . "n";
// Undefined "Property" my_static
print Bar::$my_static . "n";
$bar = new Bar();
print $bar->fooStatic() . "n";
Class Constants
It is possible to define constant values on a per-class basis remaining the same
and unchangeable. Constants differ from normal variables in that you don't use
the $ symbol to declare or use them.

Class Abstraction
PHP 5 introduces abstract classes and methods. It is not allowed to create an
instance of a class that has been defined as abstract. Any class that contains at
least one abstract method must also be abstract. Methods defined as abstract
simply declare the method's signature they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the
parent's class declaration must be defined by the child; additionally, these
methods must be defined with the same (or a less restricted) visibility .
For example,
if the abstract method is defined as protected, the function implementation
must be defined as either protected or public, but not private.

Example 19.18. Abstract class example
<?php
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method
public function printOut() {
print $this->getValue() . "n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
class ConcreteClass2 extends AbstractClass
{
public function getValue() {
return "ConcreteClass2";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass2";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."n";
$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."n";
?>
The above example will output:
ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2
Object Interfaces
Object interfaces allow you to create code which specifies which
methods a class must implement, without having to define how these
methods are handled.
Interfaces are defined using the interface keyword, in the same way as
a standard class, but without any of the methods having their contents
defined. All methods declared in an interface must be public, this is the
nature of an interface.

Implements
To implement an interface, the implements operator is used. All
methods in the interface must be implemented within a class; failure to do so
will result in a fatal error. Classes may implement more than one interface if
desired by separating each interface with a comma.

Note: A class cannot implement two interfaces that share function names, since it
would cause ambiguity.
// Declare the interface 'iTemplate'
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// Implement the interface
// This will work
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
Overloading
Both method calls and member accesses can be overloaded via the
__call, __get and __set methods. These methods will only be triggered
when your object or inherited object doesn't contain the member or
method you're trying to access. All overloading methods must not be
defined as static. All overloading methods must be defined as public.
 Member overloading
void __set ( string $name, mixed $value )
mixed __get ( string $name )

Class members can be overloaded to run custom code defined in your class by defining these specially
named methods.
The __set() method's
$name
$value

parameter used is the name of the variable that should be set or retrieved.
parameter specifies the value that the object should set the $name.

Note: The __set()

method cannot take arguments by reference.
<?php
class myclass
{
function __set($data,$value)
{
echo "__set is called<br>";
echo "Variable= ".$data." ";
echo "Value= ".$value;
}
}
$myclassobj = new myclass();
$myclassobj->x=30;
class myget
{
function __get($data)
{
//note: variable 'x' is not defined in myclass
$data = "<br>__get is called<br>undefined attributes ";
return $data;
}
}
$mygetobj = new myget();
echo $mygetobj->getdata;
//note: variable 'getdata' is not defined in myclass
 Method overloading

mixed __call ( string $name, array $arguments )
The magic method __call() allows to capture invocation of non existing
methods. That way __call() can be used to implement user defined
method handling that depends on the name of the actual method
being called.
This is for instance useful for proxy implementations. The arguments
that were passed in the function will be defined as an array in the
$arguments
parameter. The value returned from the __call()
method will be returned to the caller of the method.
Example 19.21. overloading with __call example
The above example will output:
<?php
class
Caller
{
Private $x = array(1 , 2 ,3 );
public function
__call ($m ,
{
print "Method $m called:n"
var_dump
($a );
return $this -> x ;
}
}
$foo
= new Caller ();
$a =
$foo -> test
(1 ,
"2",
var_dump
($a );
?>

$a )
;

3.4 , true

);
Method test called(output):
array(4) {
[0]=>
int(1)
[1]=>
string(1) "2"
[2]=>
float(3.4)
[3]=>
bool(true)
}
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
Autoloading Objects
Many developers writing object-oriented applications create one PHP source file
per-class definition. One of the biggest annoyances is having to write a long list
of needed includes at the beginning of each script (one for each class).
<?php
function __autoload($class_name)
{
require_once $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
Object Iteration
PHP 5 provides a way for objects to be defined so it is possible to
iterate through a list of items, with, for Example a foreach
statement. By default, all visible properties will be used for the
iteration.

Example 19.22. Simple Object Iteration
class MyClass
{

public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';
protected $protected = 'protected var';
private $private = 'private var';
function iterateVisible() {
echo "MyClass::iterateVisible:n";
foreach($this as $key => $value) {
print "$key => $valuen";
}

}
}
$class = new MyClass();
foreach($class as $key => $value)
{
print "$key => $valuen";
}
echo "n";
$class->iterateVisible();
?>
The above example will output:
var1 => value 1
var2 => value 2
var3 => value 3
MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var
Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from
overriding a method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
Example 19.29. Final methods example
<?php
class BaseClass
{
public function test() {
echo "BaseClass::test() calledn";
}
final public function moreTesting() {
echo "BaseClass::moreTesting() calledn";
}
}
class ChildClass extends BaseClass
{
public function moreTesting() {
echo "ChildClass::moreTesting() calledn";
}
}
Example Final class example
<?php
final class BaseClass
{
public function test() {
echo "BaseClass::test() calledn";
}
// Here it doesn't matter if you specify the function as final or not
final public function moreTesting() {
echo "BaseClass::moreTesting() calledn";
}
}
class ChildClass extends BaseClass
{
}
// Results in Fatal error: Class ChildClass may not inherit from final class
(BaseClass)

?>
Type Hinting
PHP 5 introduces Type Hinting. Functions are now able to force
parameters to be objects (by specifying the name of the class in the
function prototype) or arrays (since PHP 5.1).
Example 19.41. Type Hinting examples

<?php
// An example class
class MyClass
{
/*
A test function
First parameter must be an object of type OtherClass

*/
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
/*

Another test function
First parameter must be an array
*/
public function test_array(array $input_array)
{
print_r($input_array);
}
}

// Another example class
class OtherClass {
public $var = 'Hel o World';
}
?>
Failing to satisfy the type hint results in a catchable fatal error.
<?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;
// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');
// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);
// Fatal Error: Argument 1 must not be null
$myclass->test(null);
// Works: Prints Hello World
$myclass->test($otherclass);
// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');
// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));
?>
Overview of MVC Architecture
Understanding MVC
 MVC stands for Model-View-Controller.

• It is a type of architecture for developing software, recently pretty
popular in web applications development.
• Model is what interacts with the database, it would be the backend
class code for an object-oriented language like PHP, Ruby on Rails, or
C++.
• View is basically the user interface.

• Controller is the logic that operates everything in between
Model

View

Client

Dispatcher
Controller

DataBase
Model
The MVC structure is meant for reasonably-sized applications, using
object-oriented coding. The Model part, in a PHP app, would usually
be a class (or multiple classes). Fairly often, the class is a
representation of a table you store in the database — member
variables are the data columns, and member methods are operations
that can be done. As an example, you might have a User class, having
variables such as username, password, email address, and other
things. Some of its methods might be a new user creation function, a
login function, an authentication function, and a logout function.
Model (Example of creating Model Code)
class User
{
var $username;
var $password;
var $email;
function User($u, $p, $e) // constructor
{
$this->username = $u;
$this->password = $p;
$this->email = $e;
}
function create()
{
// creates user in the db
}
function login()
{
// checks against db, does login procedures
}
static function authenticate($u, $p)
{
// checks against db
}
function logout()
{
// does logout procedures
}
}
The View, in the simplest words, is the user interface.
<?php
require_once('User.php');
// makes sure user isn't already logged in
if (User::authenticate($_COOKIE['username'], $_COOKIE['password']))
{
header(”Location:/main.php”);
exit();
}
?>
<html>
<head><title>Please login</title></head>
<body>
<h1>Login</h1>
<?
if ($_GET['error'] == 1)
{
echo ‘Login incorrect. Please try again.<br />’;
}
?>
<form action=”login_action.php” method=”post”>
User: <input type=”text” name=”username” /><br />
Pass: <input type=”password” name=”password” /><br />
<input type=”submit” value=”Login” />
</form>
</body>
</html>
Controller
<?php
require_once('User.php');
// in reality, a lot more error checking needs to be done.
$currentuser = new User($_POST['username'], $_POST['password'], ”);
if ($currentuser->login())
{
// set cookies for login info
header(”Location:/main.php”);
exit();
}
else
{
header(”Location:/login.php?error=1 ″);
exit();
}
?>

More Related Content

What's hot (20)

PDF
Php tutorial(w3schools)
Arjun Shanka
 
PDF
Introduction to CSS3
Doris Chen
 
PPTX
Php
Shyam Khant
 
PPT
Introduction to PHP
Kengatharaiyer Sarveswaran
 
PPT
Java Servlets
BG Java EE Course
 
PDF
Php array
Nikul Shah
 
PDF
Basics of JavaScript
Bala Narayanan
 
PDF
Php introduction
krishnapriya Tadepalli
 
PPTX
Event In JavaScript
ShahDhruv21
 
PPTX
ppt of web designing and development
47ishu
 
PPTX
Introduction to JAVA
ParminderKundu
 
PPT
C program
AJAL A J
 
PPT
Scripting languages
teach4uin
 
PPT
javaScript.ppt
sentayehu
 
PPT
PHP variables
Siddique Ibrahim
 
PDF
Web Development with Python and Django
Michael Pirnat
 
PPTX
jQuery
Dileep Mishra
 
PPSX
Php and MySQL
Tiji Thomas
 
PPTX
PHP
Steve Fort
 
Php tutorial(w3schools)
Arjun Shanka
 
Introduction to CSS3
Doris Chen
 
Introduction to PHP
Kengatharaiyer Sarveswaran
 
Java Servlets
BG Java EE Course
 
Php array
Nikul Shah
 
Basics of JavaScript
Bala Narayanan
 
Php introduction
krishnapriya Tadepalli
 
Event In JavaScript
ShahDhruv21
 
ppt of web designing and development
47ishu
 
Introduction to JAVA
ParminderKundu
 
C program
AJAL A J
 
Scripting languages
teach4uin
 
javaScript.ppt
sentayehu
 
PHP variables
Siddique Ibrahim
 
Web Development with Python and Django
Michael Pirnat
 
Php and MySQL
Tiji Thomas
 

Similar to PHP slides (20)

PPTX
C Programming with oops Concept and Pointer
Jeyarajs7
 
PPTX
C language (1).pptxC language (1C language (1).pptx).pptx
RutviBaraiya
 
PPTX
C language
Robo India
 
PPTX
1 introduction to c program
NishmaNJ
 
PPT
c-programming
Zulhazmi Harith
 
PDF
Workbook_2_Problem_Solving_and_programming.pdf
DrDineshenScientist
 
PPTX
C programming language
Abin Rimal
 
PPT
C_Language_PS&PC_Notes.ppt
ganeshkarthy
 
PPTX
C programming language:- Introduction to C Programming - Overview and Importa...
SebastianFrancis13
 
ODP
Programming basics
Bipin Adhikari
 
PPTX
Programming in C
Nishant Munjal
 
PPTX
Programming Fundamentals
umar78600
 
PPTX
Introduction to c
Ajeet Kumar
 
PPT
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
yatakonakiran2
 
PPTX
Microcontroller lec 3
Ibrahim Reda
 
PDF
learn basic to advance C Programming Notes
bhagadeakshay97
 
PDF
3.Loops_conditionals.pdf
NoumanSiddiqui12
 
PPTX
Fundamentals of computer programming by Dr. A. Charan Kumari
THE NORTHCAP UNIVERSITY
 
PPTX
Review of C programming language.pptx...
SthitaprajnaLenka1
 
C Programming with oops Concept and Pointer
Jeyarajs7
 
C language (1).pptxC language (1C language (1).pptx).pptx
RutviBaraiya
 
C language
Robo India
 
1 introduction to c program
NishmaNJ
 
c-programming
Zulhazmi Harith
 
Workbook_2_Problem_Solving_and_programming.pdf
DrDineshenScientist
 
C programming language
Abin Rimal
 
C_Language_PS&PC_Notes.ppt
ganeshkarthy
 
C programming language:- Introduction to C Programming - Overview and Importa...
SebastianFrancis13
 
Programming basics
Bipin Adhikari
 
Programming in C
Nishant Munjal
 
Programming Fundamentals
umar78600
 
Introduction to c
Ajeet Kumar
 
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
yatakonakiran2
 
Microcontroller lec 3
Ibrahim Reda
 
learn basic to advance C Programming Notes
bhagadeakshay97
 
3.Loops_conditionals.pdf
NoumanSiddiqui12
 
Fundamentals of computer programming by Dr. A. Charan Kumari
THE NORTHCAP UNIVERSITY
 
Review of C programming language.pptx...
SthitaprajnaLenka1
 
Ad

Recently uploaded (20)

PPTX
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PDF
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
PDF
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
PDF
Cooperative wireless communications 1st Edition Yan Zhang
jsphyftmkb123
 
PDF
IMPORTANT GUIDELINES FOR M.Sc.ZOOLOGY DISSERTATION
raviralanaresh2
 
PPTX
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
PPTX
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
PDF
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
PDF
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
PDF
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
PDF
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PDF
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
PDF
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
PPTX
How to Configure Refusal of Applicants in Odoo 18 Recruitment
Celine George
 
PDF
Lean IP - Lecture by Dr Oliver Baldus at the MIPLM 2025
MIPLM
 
PDF
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PPTX
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
Cooperative wireless communications 1st Edition Yan Zhang
jsphyftmkb123
 
IMPORTANT GUIDELINES FOR M.Sc.ZOOLOGY DISSERTATION
raviralanaresh2
 
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
How to Configure Refusal of Applicants in Odoo 18 Recruitment
Celine George
 
Lean IP - Lecture by Dr Oliver Baldus at the MIPLM 2025
MIPLM
 
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
Ad

PHP slides

  • 2. Agenda Core PHP · Software Engineering · Web Programming · Introduction to PHP · HTML and CSS · PHP as a Scripting Language · Variables and Expressions in PHP · PHP Operators · Conditional Test, Events and Flows in PHP · Functions and Arrays using PHP · PHP Syntax and Variables · String functions · DBMS&RDBS · MYSQL database and queries · Sessions and Cookies in PHP · Files and Directory Access · Handling e-mail · Use of JavaScript, AJAX and XML
  • 3. Program..  Sequence of instructions written for specific purpose  Like program to find out factorial of number  Can be written in higher level programming languages that human can understand  Those programs are translated to computer understandable languages  Task will be done by special tool called compiler
  • 4.  Compiler will convert higher level language code to lower language code like binary code  Most prior programming language was ‘C’  Rules & format that should be followed while writing program are called syntax  Consider program to print “Hello!” on screen
  • 5. void main() { printf(“Hello!”); }  Void main(), function and entry point of compilation  Part within two curly brackets, is body of function  Printf(), function to print sequence of characters on screen
  • 6.  Any programming language having three part Data types 2. Keywords 3. Operators  Data types are like int, float, double  Keyword are like printf, main, if, else  The words that are pre-defined for compiler are keyword  Keywords can not be used to define variable 1.
  • 7.  We can define variable of data type  Like int a; then ‘a’ will hold value of type int and is called variable  Programs can have different type of statements like conditional statements and looping statements  Conditional statements are for checking some condition
  • 8. Conditional Statements…  Conditional statements controls the sequence of statements, depending on the condition  Relational operators allow comparing two values. 1. == is equal to 2. != not equal to 3. < less than 4. > greater than 5. <= less than or equal to 6. >= greater than or equal to
  • 9. SIMPLE IF STATEMENT  It execute if condition is TRUE  Syntax: if(condition) { Statement1; ..... Statement n; }
  • 10. main() { int a,b; printf(“Enter a,b values:”); scanf(“%d %d”,&a,&b); if(a>b) { printf(“n a is greater than b”); } }  OUTPUT: Enter a,b values:20 10 a is greater than b
  • 11. IF-ELSE STATEMENT  It execute IF condition is TRUE.IF condition is FLASE it execute ELSE part  Syntax: if(condition) { Statement1; ..... Statement n; } else { Statement1; ..... Statement n; }
  • 12. main() { int a,b; printf(“Enter a,b values:”); scanf(“%d %d”,&a,&b); if(a>b) { printf(“n a is greater than b”); } else { printf(“nb is greater than b”); } }  OUTPUT: Enter a,b values:10 20 b is greater than a
  • 13. IF-ELSE IF STATEMENT:  It execute IF condition is TRUE.IF condition is FLASE it checks ELSE IF part .ELSE IF is true then execute ELSE IF PART. This is also false it goes to ELSE part.  Syntax: if(condition) { Statementn; } else if { Statementn; } else { Statement n; }
  • 14. main() { int a,b; printf(“Enter a,b values:”); scanf(“%d %d”,&a,&b); if(a>b) { printf(“n a is greater than b”); } else if(b>a) { printf(“nb is greater than b”); } else { printf(“n a is equal to b”); } }  OUTPUT: Enter a,b values:10 10 a is equal to b
  • 15. NESTED IF STATEMENT  To check one conditoin within another.  Take care of brace brackets within the conditions.  Synatax: if(condition) { if(condition) { Statement n; } } else { Statement n; }
  • 16. main() { } int a,b; printf(“n Enter a and b values:”); scanf(“%d %d ”,&a,&b); if(a>b) { if((a!=0) && (b!=0)) { printf(“na and b both are +ve and a >b); else { printf(“n a is greater than b only”) ; } } else { printf(“ na is less than b”); } }  Output: Enter a and b values:30 20 a and b both are +ve and a > b
  • 17. Switch..case  The switch statement is much like a nested if .. else statement.  switch statement can be slightly more efficient and easier to read.  Syntax : switch( expression ) { case constant-expression1: statements1; case constant-expression2: statements2; default : statements4; }
  • 18. main() { char Grade = ‘B’; switch( Grade ) { case 'A' : printf( "Excellentn" ); break; case 'B' : printf( "Goodn" ); break; case 'C' : printf( "OKn" ); break; case 'D' : printf( "Mmmmm....n" ); break; default : printf( "What is your grade anyway?" ); break; } }
  • 19. Looping…  Loops provide a way to repeat commands and control how        many times they are repeated. C provides a number of looping way. while loop A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statements get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again. This cycle repeats until the test condition evaluates to false.
  • 20.  Basic syntax of while loop is as follows: while ( expression ) { Single statement or Block of statements; }  Will check for expression, until its true when it gets false execution will be stop
  • 21. main() { int i = 5; while ( i > 0 ) { printf("Hello %dn", i ); i = i -1; } }  Output Hello 5 Hello 4 Hello 3 Hello 2 Hello 1
  • 22. Do..While  do ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start.  This has the effect that the content of the loop are always executed at least once.  Basic syntax of do...while loop is as follows: do { Single statement or Block of statements; } while(expression); Version 1.4
  • 23. main() { int i = 5; do{ printf("Hello %dn", i ); i = i -1; } while ( i > 0 ); }  Output Hello 5 Hello 4 Hello 3 Hello 2 Hello 1
  • 24. For Loop…  for loop is similar to while, it's just written differently. for statements are often used to proccess lists such a range of numbers:  Basic syntax of for loop is as follows: for( initialization; condition; increment) { Single statement or Block of statements; }
  • 25. main() { int i; int j = 5; for( i = 0; i <= j; i ++ ) { printf("Hello %dn", i ); } }  Output Hello 0 Hello 1 Hello 2 Hello 3 Hello 4 Hello 5
  • 26. Break & Continue…  C provides two commands to control how we loop:  break -- exit form loop or switch.  continue -- skip 1 iteration of loop.  Break is used with switch case
  • 27. main() { int i; int j = 5; for( i = 0; i <= j; i ++ ) { if( i == 3 ) { break; } printf("Hello %dn", i ); } }  Output Hello 0 Hello 1 Hello 2 Version 1.4
  • 28. Continue Example.. main() { int i; int j = 5; for( i = 0; i <= j; i ++ ) { if( i == 3 ) { continue; } printf("Hello %dn", i ); } }  Output Hello 0 Hello 1 Hello 2 Hello 4 Hello 5 Version 1.4
  • 29. Functions…  A function is a module or block of program code which deals with a particular task.  Making functions is a way of isolating one block of code from other independent blocks of code.  Functions serve two purposes. 1. 2. They allow a programmer to say: `this piece of code does a specific job which stands by itself and should not be mixed up with anything else', Second they make a block of code reusable since a function can be reused in many different contexts without repeating parts of the program text. Version 1.4
  • 30. int add( int p1, int p2 ); //function declaration void main() { int a = 10; int b = 20, c; c = add(a,b); //call to function printf(“Addition is : %d”, c); } int add( int p1, int p2 ) //function definition { return (p1+p2); } Version 1.4
  • 31. Exercise… 1. 2. 3. 4. 5. Find out factorial of given number Check whether given number is prime number or not Check whether given number is Armstrong number or not Calculate some of first 100 even numbers Prepare calculator using switch Version 1.4
  • 32. OOPS Fundamentals…  Class – group of data members & member functions  Like person can be class having data members height and weight and member functions as get_details() and put_details() to manipulate on details  Class is nothing until you create it’s object  Object – instantiates class allocates memory Version 1.4
  • 33. OOPS Fundamentals…  Access to data members & member functions can be done using object only (if they are not static!)  OOPS features are 1. 2. 3. 4. 5. Encapsulation Data hiding Data reusability Overloading (polymorphism) Overriding Version 1.4
  • 34. OOPS Features…  Encapsulation – making one group of data members & member functions  Can be done through class  Then group of data members & Member functions will be available just by creating object. Version 1.4
  • 35. OOPS Features…  Data Hiding – can be done through access modifiers  Access modifiers are private, public, protected and internal  Private members or member function won’t be available outside class  Public – available all over in program outside class also Version 1.4
  • 36. OOPS Features…  Protected – members that are available in class as well as in it’s child class  Private for another class  Protected access modifier comes only when inheritance is in picture  Internal is used with assembly creation Version 1.4
  • 37. class employee //Class Declaration { private: char empname[50]; int empno; public: void getvalue() { cout<<"INPUT Employee Name:"; cin>>empname; cout<<"INPUT Employee Number:"; cin>>empno; } void displayvalue() { cout<<"Employee Name:"<<empname<<endl; cout<<"Employee Number:"<<empno<<endl; }; main() { employee e1; e1.getvalue(); e1.displayvalue(); //Creation of Object } Version 1.4 }
  • 38. OOPS Features…  Overloading – taking different output of one method or operator based on parameters and return types  Like add() method performs addition and add(int a,int b) performs addition of ‘a’ and ‘b’ passed when calling  Also, + operator performs addition of two numbers as well as concatenation of strings Version 1.4
  • 39. class arith { public: void calc(int num1) { cout<<"Square of a given number: " <<num1*num1 <<endl; } }; void calc(int num1, int num2 ) { cout<<"Product of two whole numbers: " <<num1*num2 <<endl; } int main() //begin of main function { arith a; a.calc(5); a.calc(6,7); }  This is example of method overloading, output will be Square of given number : 25 Product of two whole numbers : 42 Version 1.4
  • 40. OOPS Features…  Data Reusability – helps in saving developers time  You can use already created class to crate new one  Called inheritance  Already existing class is base class and new created is derived class  Base class members can be available in derived class and to access them create object of derived class  Like from parent to child Version 1.4
  • 41. class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} }; class CRectangle: public CPolygon { public: int area () { return (width * height); } }; class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; } Version 1.4
  • 42. OOPS Features…  In C++, overriding is a concept used in inheritance which involves a base class implementation of a method.  Then in a subclass, you would make another implementation of the method. This is overriding. Here is a simple example. class Base { public: virtual void DoSomething() {x = x + 5;} private: int x; }; class Derived : public Base { public: virtual void DoSomething() { y = y + 5; Base::DoSomething(); } private: int y; }; Version 1.4
  • 43. What is Website?  Website – Everyday you visit on internet  Follows some rules & regulations i.e. client-server architecture standard  Websites – providing information from anywhere in world Version 1.4
  • 45. Client-Server…  Client – end user’s computer that runs software or website  Server – area in host or remote computer to which client communicates  Network – means of communication  Can be HTTP(for www), FTP(machine to machine transfer),SMTP(mail transfer) Version 1.4
  • 46. Website – basic parts  Websites are consist of three parts  GUI – web pages that you visit  Coding – logic that provides functionality or makes website dynamic  Database – manages data provided by end user  For GUI building HTML is used from long time Version 1.4
  • 47. HTML…  HTML is the "mother tongue" of your browser.  HTML – Hypertext Markup Language  HTML is a language, which makes it possible to present information on the Internet.  What you see when you view a page on the Internet is your browser's interpretation of HTML.  To see the HTML code of a page on the Internet, simply click "View" in the top menu of your browser and choose "Source". Version 1.4
  • 48. HTML…  HTML documents are defined by HTML elements.  An HTML element starts with a start tag / opening tag  An HTML element ends with an end tag / closing tag  The element content is everything between the start and the end tag  Some HTML elements have empty content  Empty elements are closed in the start tag  Most HTML elements can have attributes  Ex : <p>This is paragraph</p> Version 1.4
  • 49. HTML…  Attributes provide additional information about HTML elements.  Attributes provide additional information about an element  Attributes are always specified in the start tag  Attributes come in name/value pairs like: name="value“  For ex: <p id=“p1”>This is paragraph</p> Version 1.4
  • 51. Explanation…  Content between <html> and </html> is considered as html content  Content between <head> and </head> will be considered as head part  <title> and </title> is title of page that will be shown in browser  <body> and </body> is part of page that will be filled with controls Version 1.4
  • 52. Database…  Back end part of website  Used to maintain information provided by users  Built up with list of tables, tables having rows and columns  Data in cells are records  When tables are connected in database system it is RDBMS. Version 1.4
  • 53. Database…  A DBMS that follows rules of Dr.E.F.Codd is RDBMS  RDBMS stores data in form of tables and relation ship between those tables in form of tables  Ideally there is no DBMS exist that follows all rules of E.F.Codd! Version 1.4
  • 55. Database…  Queries – sentences executed on database for data manipulation  Will be handled by database engines and will perform action on data that are stored on database server  Ex are create, alter, insert, update, delete etc  SQL – structured query language is used for this Version 1.4
  • 56. SQL  DDL – data definition Language  Commands are : create, alter, truncate, drop  Syntax : create table table_name(col_name datatype(size)…);  Example : Create table Person_Master(name nvarchar(50)); Version 1.4
  • 57. SQL  DML – data manipulation language  Like insert, update, delete  Syntax: insert into table_name(col1,col2,..coln) values(val1,val2,..valn);  Example: insert into Person_Master(name) values(‘name1’); Version 1.4
  • 58. SQL  Update Syntax: update table_name set col1=val1, col2=val2 where col = val;  Ex : update Person_Master set name = ‘name1’ where ID=1;  It will set name to ‘name1’ for which ID is 1 Version 1.4
  • 59. SQL  Delete syntax : delete from table_name where condition;  Example : delete from Person_Master where ID=1;  It will delete whole row for which ID is 1  It is conditional delete operation  To delete all rows simply omit the condition Version 1.4
  • 60. SQL  Select syntax : select * from table_name;  It will select all rows from specified table  To select particular row select * from table_name where condition;  To select particular column select col1,col2 from table_name; Version 1.4
  • 61. Database…  Constrains – terms that needs to be satisfied on data  For ex all students must have unique roll number  Can be defined as primary key, foreign key, unique key etc.  Primary key – column of table whose value can be used to uniquely identify records Version 1.4
  • 62. Database…  Foreign key – column inside table that is primary key of another table  Unique key – like primary key can be used to uniquely identify a record  Difference between primary key and unique key is primary key will never allow null where as unique key will allow it for once Version 1.4
  • 63. Normalization…  The process of structuring data to minimize duplication and inconsistencies.  The process usually involves breaking down the single table into two or more tables and defining relationships between those tables.  Normalization is usually done in stages.  Most people in creating database, never need to go to beyond the third level of normalization. Version 1.4
  • 64. 1NF  Eliminate duplicative columns from the same table.  Create separate tables for each group related data and identify each row with a unique columns.  In this, one table will be divided in two tables with relevant contents Version 1.4
  • 65. 2NF  Once 1NF has been done then and only then 2NF can be done  In this, provide key constrains to the columns of tables based on uniqueness  Like assign primary key to one table column and refer this as foreign key in another table Version 1.4
  • 66. 3NF  Only after 2NF, third normalization can be done  In this, further more analyze tables and divide them for data uniqueness Version 1.4
  • 67. SDLC…  For project development rules & regulation need to be followed for best quality output at defined time limit  Rules are Software Development Life Cycle – SDLC  It’s part of software engineering  Six rules to be followed… Version 1.4
  • 68. 1. 2. 3. 4. 5. 6. Requirement Gathering Analysis & SRS Designing Implementation (Coding) Testing Maintenance
  • 69. SDLC… 1. Requirement collection    Phase of collecting requirements from client Will be done by business analyst of company He will create questioner, in which put answers from client 2. Analysis & SRS (Software Requirement Specification)    Collected requirements will be analyzed for time limit, budget and market trade Will be filtered and SRS will be created as result Will be discussed with client Version 1.4
  • 70. SDLC…     1.   Based on requirements users, their activities and flow of data, modules will be defined Will be done by system analyst Based on diagrams all will be done Main diagrams are use-case, DFD and flow charts USE-CASE Have to define users and their tasks Like website is college management system Version 1.4
  • 71. SDLC…  User is student having activities registration, login, view & download assignments, view fees details, view time table etc.  Can be shown in use-case as given below Version 1.4
  • 72. Registration Login View & Download Assignment View Result Student View Timetable Version 1.4
  • 73. SDLC…  Once actions are defined, need to divide project in modules  DFD is used for this  DFD – Data Flow Diagrams  Graphical representation of flow of data inside application can also be used for visualization and data processing Version 1.4
  • 74. SDLC…  DFD elements are.. External Entity 2. Process 3. Data Flow 4. Data Store 1. Version 1.4
  • 75. SDLC… 1.    External entity Can be user or external system that performs some process or activity in project Symbolized with rectangle Like, we have entity ‘admin’ then symbol will be Admin Version 1.4
  • 76. SDLC… 2. Process  Work or action taken on incoming data to produce output  Each process must have input and output  Symbolized as 1. Login output input Version 1.4
  • 77. SDLC… 3. Data Flow  Can be used to show input and output of data  Should be named uniquely and don’t include word ‘data’  Names can be ‘payment’, ‘order’, ’complaint’ etc  Symbolized as Payment Version 1.4
  • 78. SDLC…. 4. Data Store  Can be used to show database tables  Only process may connect data stores  There can be two or more process sharing same data store  Symbolized as Registration_Master Version 1.4
  • 79. DFD Rules…  6 rules to follow  Consider data flow diagram as given below Version 1.4
  • 81. Rule 1  Each process must have data flowing into it and coming out from it Version 1.4
  • 82. Rule 2  Each data store must have data going inside and data coming outside Version 1.4
  • 83. Rule 3  A data flow out of a process should have some relevance to one or more of the data flows into a process Version 1.4
  • 84. Rule 3  In process 3 all data flows are connected to process claim.  The claim decision can not be made until the claim form has been submitted and the assessor makes a recommendation Version 1.4
  • 85. Rule 4  Data stored in system must go through a process Version 1.4
  • 86. Rule 5  Two data stores can’t communicate with each other unless process is involved in between Version 1.4
  • 87. Rule 6  The Process in DFD must be linked to either another process or a data store  A process can’t be exist by itself, unconnected to rest of the system Version 1.4
  • 89. Types of DFD…  Physical DFD  An implementation-dependent view of the current system, showing what tasks are carried out and how they are performed. Physical characteristics can include:      Names of people Form and document names or numbers Equipment and devices used Locations Names of procedures Version 1.4
  • 90. Types Of DFD…  Logical Data Flow Diagrams  An implementation-independent view of the a system, focusing on the flow of data between processes without regard for the specific devices, storage locations or people in the system. The physical characteristics listed above for physical data flow diagrams will not be specified. Version 1.4
  • 91. DFD Levels…  DFD level-0  It’s also context level DFD  Context level diagrams show all external entities.  They do not show any data stores.  The context diagram always has only one process labeled 0. Version 1.4
  • 92. DFD Level-1(or 2)  include all entities and data stores that are directly connected by data flow to the one process you are breaking down  show all other data stores that are shared by the processes in this breakdown  Like login process will linked to users & database in further leveling Version 1.4
  • 94. Example (logical – 0)… Version 1.4
  • 97. Flow Charts…  Used to show algorithm or process  Can give step by step solution to the problem  The first flow chart was made by John Von Newman in 1945  Pictorial view of process  Helpful for beginner and programmers Version 1.4
  • 98. Flow Chart…  Flowcharts are generally drawn in the early stages of formulating computer solutions.  Flowcharts facilitate communication between programmers and business people.  These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Version 1.4
  • 99. Flow Chart…  Once the flowchart is drawn, it becomes easy to write the program in any high level language.  Often we see how flowcharts are helpful in explaining the program to others.  Hence, it is correct to say that a flowchart is a must for the better documentation of a complex program. Version 1.4
  • 100. Flow Chart…  Symbols are.. 1.   Start Or End Show starting or ending of any flow chart Symbolized as OR Start End Version 1.4
  • 101. Flow Charts… 2. Process  Defines a process like defining variables or initializing variable or performing any computation  Symbolized as res = num1 + num2 Version 1.4
  • 102. Flow Charts… 3. Input or Output  Used when user have to get or initialize any variable  Like get num1 and num2 from user  Symbolized as Int num1,num2 Version 1.4
  • 103. Flow Charts… 4. Decision Making  For checking condition this symbols can be used  Like if num1 is greater than num2  Can be symbolized as If num1>num2 Version 1.4
  • 104. Flow Charts… 5. Flow lines  Lines showing flow of data and process  Showing flow of instructions also  Can be symbolized as Version 1.4
  • 105. Flow chart  Any program can be in three format Linear or sequence 2. Branching 3. Looping  Following are notations can be used to show this format 1. Version 1.4
  • 108. Looping Program Structure…. Start Process-1 Process-2 Yes No Process-3 End Version 1.4
  • 109. Sum of 1-50 numbers.. Version 1.4
  • 110. Max among three numbers… Version 1.4
  • 112. SDLC… 3. Designing    The Design document should reference what you are going to build to meet the requirements, and not how it can include pseudo code but shouldn’t contain actual code functionality. Design elements describe the desired software features in detail, and generally include functional hierarchy diagrams, screen layout diagrams, tables of business rules, business process diagrams, pseudo code, and a complete entityrelationship diagram with a full data dictionary. These design elements are intended to describe the software in sufficient detail that skilled programmers may develop the software with minimal additional input. At this phase the test plans are developed.
  • 113. SDLC… 4. Implementation (Coding)   To launch the coding phase, develop a shell program that is then put under some form of version control. This phase includes the set up of a development environment, and use of an enhanced editor for syntax checking.
  • 114. SDLC… 5. Testing    Each developer insures that their code runs without warnings or errors and produces the expected results. The code is tested at various levels in software testing. Unit, system and user acceptance tasting’s are often performed. This is a grey area as many different opinions exist as to what the stages of testing are and how much if any iteration occurs. Types of testing: Defect testing, Path testing, Data set testing, Unit testing, System testing, Integration testing, Black box testing, White box testing, Regression testing, Automation testing, User acceptance testing, Performance testing, etc.
  • 115. SDLC… 6. Maintenance     User’s guides and training are developed to reflect any new functionality and changes which need to be identified to the production staff. Any changes needed to operations and/or maintenance need to be addressed. Every run in production needs to be verified. Any problems with production need to be addressed immediately. A Change Request system may be set up to allow for feedback for enhancements.
  • 118. What is Software Engineering? The term software engineering first appeared in the 1968 NATO Software Engineering Conference and was meant to provoke thought regarding the current "software crisis" at the time. Definition:“state of the art of developing quality software on time and within budget” •Trade-off between perfection and physical constraints •SE has to deal with real-world issues •State of the art! •Community decides on “best practice”+ life-long education
  • 120. Requirements Collection Establish Customer Needs Analysis Model And Specify the requirements-“What” Design Model And Specify a Solution –“Why” Implementation Construct a Solution In Software Testing Validate the solution against the requirements Maintenance Repair defects and adapt the solution to the new requirements
  • 121. Web Programming  WWW (World Wide Web)    Web addresses are URL (uniform resource locator) A server address and a path to a particular file URLs are often redirected to other places http://students. -int.com/classes/PHP&MYSQL/index.html       protocol= http:// web server= students domain= . -int.com path= /classes/PHP&MYSQL/ (dirs(folders)) file= index.html file extension= .html(hypertext markup language)
  • 122. CLIENTS AND SERVERS  Web programming languages are usually classified as server-side or client-side. Some languages, such as JavaScript, can be used as both client-side and server-side languages, but most Web programming languages are server-side languages.  The client is the Web browser, so client-side scripting uses a Web browser to run scripts. The same script may produce different effects when different browsers run it.  A Web server is a combination of software and hardware that outputs Web pages after receiving a request from a client. Server-side scripting takes place on the server. If you look at the source of a page created from a server-side script, you'll see only the HTML code the script has generated. The source code for the script is on the server and doesn't need to be downloaded with the page that's sent back to the client.      Web Programming Languages PHP ASP Perl JAVA
  • 123. Client/Server Interaction For Web pages, the client requests a page the server returns it: there’s no permanent connection, just a short conversation •Details of the conversation are specified by HTTP
  • 124. Server-Side  PHP is a Server-side language  Even though it is embedded in HTML files much like the client-side JavaScript language, PHP is server-side and all PHP tags will be replaced by the server before anything is sent to the web browser. •So if the HTML file contains: <html> <?php echo "Hello World"?> </html> •What the end user would see with a "view source" in the browser would be: <html> Hello World </html>
  • 125. PHP Introduction  PHP can be installed on any web server: Apache, IIS, Netscape, etc…  PHP can be installed on any OS: Unix, Linux, Windows, MacOS, etc…  XAMPP is a free and open source cross-platform web server package, consisting mainly of the Apache HTTP Server, MySQL database, and interpreters for scripts written in the PHP and Perl programming languages.  It is used as a development tool, to allow website designers and programmers to test their work on their own computers without any access to the Internet. .  XAMPP's name is an acronym for:      X (meaning cross-platform) Apache HTTP Server MySQL PHP Perl  LAMP package is used for Linux OS  WAMP package is used for Windows OS
  • 126.  PHP is a powerful server-side scripting language for creating dynamic and interactive websites.  PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP. PHP is perfectly suited for Web development and can be embedded directly into the HTML code.  The PHP syntax is very similar to Perl and C. PHP is often used together with Apache (web server) on various operating systems. It also supports ISAPI and can be used with Microsoft's IIS on Windows.  A PHP file may contain text, HTML tags and scripts. Scripts in a PHP file are executed on the server.  What is a PHP File?  •PHP files may contain text, HTML tags and scripts  •PHP files are returned to the browser as plain HTML  •PHP files have a file extension of ".php", ".php3", or ".phtml"
  • 127. What is PHP?          PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, Postgre SQL, Generic ODBC, etc.) PHP is an open source software (OSS) PHP is free to download and use Created in 1994 Syntax inherited from C, Java and Perl Powerful, yet easy to learn Why PHP?     PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side
  • 128. Diff Between php4 andphp5 There are several differences between PHP4 and PHP5          1.Unified constructor and Destructor 2.Exception has been introduced 3.New error level named E_STRICT has been introduced 4.Now we can define full method definitions for a abstract class 5.Within a class we can define class constants 6.we can use the final keyword to indicate that a method cannot be overridden by a child 7.public, private and protected method introduced 8.Magic methods has been included 9.we can pass value by reference
  • 129. How is PHP Used?  How is PHP used?  Content Management  Forums  Blogging  Wiki  CRM
  • 131. HTML and CSS  HTML, which stands for Hyper Text Markup Language, is the predominant markup language for web pages. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists etc as well as for links, quotes, and other items. It allows images and objects to be embedded and can be used to create interactive forms. It is written in the form of HTML elements consisting of "tags" surrounded by angle brackets within the web page content. It can include or can load scripts in languages such as JavaScript which affect the behavior of HTML processors like Web browsers; and Cascading Style Sheets (CSS) to define the appearance and layout of text and other material. The W3C, maintainer of both HTML and CSS standards, encourages the use of CSS over explicit presentational markup  Hyper Text Markup Language (HTML) is the encoding scheme used to create and format a web document. A user need not be an expert programmer to make use of HTML for creating hypertext documents that can be put on the internet. Example:<html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>
  • 132.  a language for describing the content and presentation of a        web page content: The meaning and structure of the web page •presentation: How the page is to be presented HTML pages have a basic hierarchical structure defined by the tags <html>, <head>, <body>, and so on Basic HTML describes a static page once parsed and rendered, the page doesn’t change hyper linking was the big step forward in basic HTML
  • 133. Intro to HTML Forms  Types of input we can collect via forms:  Text via text boxes and text areas  Selections via radio buttons, check boxes, pull down menus, and select boxes  Form actions do all of the work  Usually through button clicks
  • 134. Basic HTML Form <form name="input" action="form_action.php" method="get"> <label for="user">Username</label> <input type="text" name="user" id="user"> <br/><input type="submit" value="Submit"> </form>
  • 135. Text Input Types Text boxes  <input type="text" size="45" name="fName“/> Password boxes  <input type="password" name="pass" id="pass" /> Textareas - <textarea rows="3" cols="4"></textarea>
  • 136. Selection Input Types  Single Selection  Radio buttons <input type="radio" name="sex" value="male" /> Male <br/> <input type="radio" name="sex" value="female" /> Female  Pull Down List <select name="pulldown"> <option value="1">pulldownitem 1</option> <option value="2">pulldownitem 2</option> </select>
  • 137. Selection Input Types  Multi-Selection Check boxes <input type="checkbox" name="bike" />bike owner <br/> <input type="checkbox" name="car" />car owner Selection lists (Menus) <select name="menu" size="3" multiple="multiple"> <option value="1">menu item 1</option> <option value="2">menu item 2</option> <option value="3">menu item 3</option> <option value="4">menu item 4</option> </select>
  • 138. Buttons  Built-in buttons - <input type="submit" /> - <input type="reset" /> - <input type="file" />  Custom buttons - <button type="button" value="Click Me" onclick="run_javascript()">
  • 139. Form Actions <form name="input" action="html_form_action.php“ method="get">  Action specifies what file the form data will be sent to (on the server)  Method specifies by which HTTP protocol  get  post  Method is important on the receiving end
  • 140. PHP Forms And User Input  The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. PHP Form Handling  The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.  Form example: <html>     <body><form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form></body> </html>
  • 141.  The example HTML page above contains two input fields and a submit button. When the user fills in this form and click on the submit button, the form data is sent to the "welcome.php" file.  •The "welcome.php" file looks like this:  <html>   <body>Welcome <?php echo $_POST["name"]; ?>.<br/> You are <?php echo $_POST["age"]; ?> years old.</body>  </html>  A sample output of the above script may be:  Welcome John.  You are 28 years old. Form Validation  User input should be validated whenever possible. Client side validation is faster, and will reduce server load.  However, any site that gets enough traffic to worry about server resources, may also need to worry about site security. You should always use server side validation if the form accesses a database.  A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.
  • 142. PHP $_Get The $_GET variable is used to collect values from a form with method="get". The $_GET Variable • The $_GET variable is an array of variable names and values sent by the HTTP GET method. • The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters). Example <form action="welcome.php" method="get"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" />  </form> When the user clicks the "Submit" button, the URL sent could look something like this: http://www.-int.com/welcome.php?name=Peter&age=37  The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_GET array):
  • 143. PHP $_Get Welcome <?php echo $_GET["name"]; ?>.<br/> You are <?php echo $_GET["age"]; ?> years old!  Why use $_GET? Note: When using the $_GET variable all variable names and values are displayed in the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.  Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed 100 characters.
  • 144. PHP $_Post  The $_POST variable is used to collect values from a form with method="post". The $_POST Variable  The $_POST variable is an array of variable names and values sent by the HTTP POST method.  The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.  Example    <form action="welcome.php" method="post"> Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" />  <input type="submit" />  </form> When the user clicks the "Submit" button, the URL will not contain any form data, and will look something like this: http://www.-int.com/welcome.php  The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array):  Welcome <?php echo $_POST["name"]; ?>.<br/>   You are <?php echo $_POST["age"]; ?> years old!
  • 145. PHP $_Post  Why use $_POST?  Variables sent with HTTP POST are not shown in the URL  Variables have no length limit  However, because the variables are not displayed in the URL, it is not possible to bookmark the page. The $_REQUEST Variable  The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.  The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.  Example Welcome <?php echo $_REQUEST["name"]; ?>.<br/> You are <?php echo $_REQUEST["age"]; ?> years old!
  • 147. Introduction Cascading Style Sheets (CSS).  With CSS you will be able to:  Add new looks to your old HTML  Completely restyle a web site with only a few changes to your CSS code  Use the "style" you create on any web page you wish!
  • 148. CSS Selector  SELECTOR { PROPERTY: VALUE }  HTML tag"{ "CSS Property": "Value" ; }  The selector name creates a direct relationship with the HTML tag you want to edit. If you wanted to change the way a paragraph tag behaved, the CSS code would look like:  p { PROPERTY: VALUE }  The above example is a template that you can use whenever you are manipulating the paragraph HTML element
  • 150. Creating Internal CSS Code <head> <style type="text/css"> p {color: white; } body {background-color: black; } </style> </head> <body> <p>White text on a black background!</p> </body>       We chose the HTML element we wanted to manipulate. -p{ : ; } Then we chose the CSS attribute color. -p { color:; } Next we choose the font color to be white. -p { color:white; } Now all text within a paragraph tag will show up as white! Now an explanation of the CSS code that altered the <body>'s background: We choose the HTML element Body -body { : ; } Then we chose the CSS attribute. -body { background-color:; } •Next we chose the background color to be black. -body { backgroundcolor:black; }
  • 151. External CSS  When using CSS it is preferable to keep the CSS separate from your HTML. Placing CSS in a separate file allows the web designer to completely differentiate between content (HTML) and design (CSS). External CSS is a file that contains only CSS code and is saved with a ".css" file extension. This CSS file is then referenced in your HTML using the <link> instead of <style>. body{ background-color: gray } p { color: blue; } h3{ color: white; } Save it as .css
  • 152. HTML <html> <head> <link rel="stylesheet" type="text/css“ href="test.css" /> </head> <body> <h3> A White Header </h3> <p> This paragraph has a blue font. The background color of this page is gray because we changed it with CSS! </p> </body> </html>
  • 153. Inline css  It is possible to place CSS right in the thick of your HTML code, and this method of CSS usage is referred to as inline css.  Inline CSS has the highest priority out of external, internal, and inline CSS. This means that you can override styles that are defined in external or internal by using inline CSS <p style="background: blue; color: white;"> A new background and font color with inline CSS </p>
  • 154. Property value of css  A value is given to the property following a colon (NOT an 'equals' sign)        and semi-colons separate the properties. body {font-size: 0.8em;color: navy;} This will apply the given values to the font-size and color properties to the body selector. So basically, when this is applied to an HTML document, text between the body tags (which is the content of the whole window) will be 0.8emsin size and navy in colour. em (such as font-size: 2em) is the unit for the calculated size of a font. So "2em", for example, is two times the current font size. px(such as font-size: 12px) is the unit for pixels. pt (such as font-size: 12pt) is the unit for points. % (such as font-size: 80%) is the unit for... wait for it... percentages.
  • 155. Text property  font-family  This is the font itself, such as Times New Roman, Arial, or Verdana.  font-family: "Times New Roman".  font-size  font-weight  This states whether the text is bold or not.  font-style  This states whether the text is italic or not. It can be font-style: italic or font-style: normal.  text-decoration This states whether the text is underlined or not. This can be: text-decoration: overline, which places a line above the text. text-decoration: line-through, strike-through, which puts a line through the text. text-decoration: underline should only be used for links because users generally expect underlined text to be links.  This property is usually used to decorate links, such as specifying no underline with text-decoration: none.      Letter Spacing:3px
  • 156. text-transform  This will change the case of the text.  text-transform: capitalize turns the first letter of every word into uppercase.  text-transform: uppercase turns everything into uppercase.  text-transform: lowercase turns everything into lowercase. text-transform: none I'll leave for you to work out.
  • 157. Margins and Padding  Margin and padding are the two most commonly used properties for spacing-out elements. A margin is the space outside of the element, whereas padding is the space inside the element  The four sides of an element can also be set individually. margin-top, margin-right, margin-bottom, margin-left, padding-top, padding-right, padding-bottom and padding-left are the selfexplanatory properties you can use.
  • 158. CSS Classes  It is possible to give an HTML element multiple looks with CSS.  The Format of Classes  Using classes is simple. You just need to add an extension to the typical CSS code and make sure you specify this extension in your HTML. Let's try this with an example of making two paragraphs that behave differently. First, we begin with the CSS code, note the red text.  CSS Code: p. first{ color: blue; } p.second{ color: red; } HTML Code: <html> <body> <p>This is a normal paragraph.</p> <p class="first">This is a paragraph that uses the p. first CSS code!</p> <p class="second">This is a paragraph that uses the p. second CSS code!</p> ...
  • 159. CSS Background  The background of website is very important  With CSS, you are able to set the background color or image of any CSS element. In addition, you have control over how the background image is displayed. You may choose to have it repeat horizontally, vertically, or in neither direction. You may also choose to have the background remain in a fixed position, or have it scroll as it does normally.  CSS Background Color Varying backgrounds were obtained without using tables! Below are a couple examples of CSS backgrounds.  CSS Code: h4 { background-color: white; } p { background-color: #1078E1; } ul { background-color:rgb( 149, 206, 145); }
  • 160. CSS Background Image  Need an image to repeat left-to-right, like the gradient      background you would like to have an image that remains fixed when the user scrolls down your page. This can be done quite easily with CSS and more, including: choosing if a background will repeat and which directions to repeat in. precision positioning scrolling/static images CSS Code: p { background-image:url(smallPic.jpg); } h4{ backgroundimage:url(http://www.tizag.com/pics/cssT/smallPic.jpg); }
  • 161.  CSS Background Background Image Repeat  p { background-image:url(smallPic.jpg); backgroundrepeat: repeat; }  h4 { background-image:url(smallPic.jpg);  background-repeat: repeat-y;}  ol{ background-image:url(smallPic.jpg);  ul{ background-image:url(smallPic.jpg);  background-repeat: no-repeat;}
  • 162. CSS Background  CSS Background Image Positioning  p { background-image:url(smallPic.jpg);  background-position: 20px 10px; }  h4 { background-image:url(smallPic.jpg);  background-position: 30% 30%; }  ol{ background-image:url(smallPic.jpg);  background-position: top center; }
  • 163. CSS Background  CSS Gradient Background  If you would like to create a gradient background like the one that appears at the top of Tizag.com, you must first create an image inside a painting program (Photoshop, Draw, etc) like the one you see below.  p { background-image:url(http://www./gradient.gif);  background-repeat: repeat-x; }
  • 164. CSS Links ( Pseudo-classes ) Anchor/Link States  link-this is a link that has not been used, nor is a mouse pointer hovering over it  visited-this is a link that has been used before, but has no mouse on it  hover-this is a link currently has a mouse pointer hovering over it/on it  active-this is a link that is in the process of being clicked
  • 165. Applying CSS to HTML page Background Color
  • 169. Border
  • 170. With cascading style sheets, there are a number of ways you can apply styles to text. 1)One way is to use inline style definitions. These allow you to specify styles in the style attribute of any HTML tag. 2)Second way is to use a style sheet specified in the header of your document. You can then refer to and reuse these styles throughout your document. A document style sheet is specified between opening and closing style tags in the header of your document: <head> <style type=”text/css”> </style> </head>  To build your style sheet, just define the styles in the style block. You can define  three types of style definitions:  HTML element definitions, which specify a default style for different HTML elements (in other words, for different HTML tags)  Class definitions, which can be applied to any HTML tag by using the class attribute common to all tags  Identity definitions, which apply to any page elements that have a matching ID
  • 171. The following steps show you how to create a style sheet in a document and then use the styles: 1. In the header of a new document, create a style block: <style type=”text/css”> </style> 2. In the style block, create a style definition for the p tag: P{ font-family: Arial, Helvetica, SANS-SERIF; color: #ff0000; } 3. Next, create a style definition for the my Class class: .myClass{ font-size: 24pt; font-style: italic; } 4. Finally, create a style definition for elements with the my IDID: #myID{ background-color: #cccccc; } 5. In the body of your document, create a level 1 heading and apply the My Class class to it: <h1 class=”myClass”> This is a headline </h1>
  • 172. CSS Pseudo-classes css anchor/link states  You may not know it, but a link has four different states that it can be in. CSS allows you to customize each state. Please refer to the following keywords that each correspond to one specific state:     link - this is a link that has not been used, nor is a mouse pointer hovering over it visited - this is a link that has been used before, but has no mouse on it hover - this is a link currently has a mouse pointer hovering over it/on it active - this is a link that is in the process of being clicked  Using CSS you can make a different look for each one of these states, but at the end of this lesson we will suggest a good practice for CSS Links.
  • 173.   CSS Code: a:link { color: white; background-color: black; text-decoration: none; border: 2px solid white; }  a:visited { color: white; background-color: black; text-decoration: none; border: 2px solid white; }  a:hover { color: black; background-color: white; text-decoration: none; border: 2px solid black; }  Example:- <html> <head> <style> a:link{ text-decoration: none; color: gray; } a:visited{ text-decoration: none; color: gray; } a:hover{ text-decoration: none; color: green; font-weight: bolder; letter-spacing: 2px; } </style> </head> <body> <h2>CSS Pseudo Classes or Links</h2> <p>This is a <a href="">link with Pseudo Classes</a> !</p> </body> </html>
  • 174. CSS pseudo –class  Syntax The syntax of pseudo-classes:  selector:pseudo-class {property:value} CSS classes can also be used with pseudo-classes:  selector.class:pseudo-class {property:value}  Example  Specify the color of links:  a:link {color:#FF0000} /* unvisited link */ a:visited {color:#00FF00} /* visited link */ a:hover {color:#FF00FF} /* mouse over link */ a:active {color:#0000FF} /* selected link */
  • 175. CSS - The :first-child Pseudo-class     Match the first <p> element In the following example, the selector matches any <p> element that is the first child of any element: Example <html> <head> <style type="text/css"> p:first-child { color:blue } </style> </head> <body> <p>I am a strong man.</p> <p>I am a strong man.</p> </body> </html>
  • 176. Match the first <i> element in all <p> elements  Example  <html> <head> <style type="text/css"> p > i:first-child { font-weight:bold } </style> </head> <body> <p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p> <p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p> </body> </html>
  • 177. Match all <i> elements in all first child <p> elements  <html> <head> <style type="text/css"> p:first-child i { color:blue } </style> </head> <body> <p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p> <p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p> </body> </html>
  • 178. CSS - The :lang Pseudo-class  <html> <head> <style type="text/css"> q:lang(no) {quotes: "~" "~"} </style> </head> <body> <p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p> </body> </html>
  • 179. The :first-line/letter Pseudo-element  Pseudo-elements can be combined with CSS classes: Example:p.article:first-letter {color:#ff0000 } <p class="article">A paragraph in an article</p> p:first-letter { color:#ff0000; font-size:xx-large; } p:first-line { color:#0000ff; font-variant:small-caps; }
  • 180. CSS - The :before/After Pseudo-element  Example:- h1:before { content:url(smiley.gif); } h1:after { content:url(smiley.gif); }
  • 181.  <html> <head> <style type="text/css"> div.img { margin:2px; border:1px solid #0000ff; height:auto; width:auto; float:left; text-align:center; } div.img img { display:inline; margin:3px; border:1px solid #ffffff; } div.img a:hover img { border:1px solid #0000ff; } div.desc { text-align:center; font-weight:normal; width:120px; margin:2px; } </style> </head> <body> <div class="img"> <a target="_blank" href="klematis_big.htm"> <img src="klematis_small.jpg" alt="Klematis" width="110" height="90" /> </a> <div class="desc">Add a description of the image here</div> </div> <div class="img"> <a target="_blank" href="klematis2_big.htm"> <img src="klematis2_small.jpg" alt="Klematis" width="110" height="90" /> </a> <div class="desc">Add a description of the image here</div> </div> <div class="img"> <a target="_blank" href="klematis3_big.htm"> <img src="klematis3_small.jpg" alt="Klematis" width="110" height="90" /> </a> <div class="desc">Add a description of the image here</div> </div> <div class="img"> <a target="_blank" href="klematis4_big.htm"> <img src="klematis4_small.jpg" alt="Klematis" width="110" height="90" /> </a> <div class="desc">Add a description of the image here</div> </div> </body> </html>
  • 182. PHP Syntax and Variables
  • 184. PHP as a Scripting Language  PHP, or PHP: Hypertext Preprocessor, is a widely used, general- purpose scripting language that was originally designed for web development, to produce dynamic web pages. It can be embedded into HTML and generally runs on a web server, which needs to be configured to process PHP code and create web page content from it. It can be deployed on most web servers and on almost every operating system and platform free of charge. PHP is installed on over 20 million websites and 1 million web servers  PHP was originally created by Rasmus Lerdorf in 1995 and has been in continuous development ever since. The main implementation of PHP is now produced by The PHP Group and serves as the de facto standard for PHP as there is no formal specification. PHP is free software released under the PHP License, which is incompatible with the GNU General Public License (GPL) because of restrictions on the use of the term PHP.
  • 185. PHP Syntax  Below, we have an example of a simple PHP script which sends the text        "Hello World" to the browser: <html> <body><?php echo "Hello World"; ?></body> </html> Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World".
  • 186. PHP Syntax Comments in PHP •In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. <html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html>
  • 187. PHP Variables  Variables are used for storing values, such as numbers, strings or function results, so that they can be used many times in a script. Variables in PHP  Variables are used for storing a values, like text strings, numbers or arrays.  When a variable is set it can be used over and over again in your script  All variables in PHP start with a $ sign symbol.  The correct way of setting a variable in PHP:  $var_name = value; New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work.  Let's try creating a variable with a string, and a variable with a number: <?php $txt = "Hello World!"; $number = 16; ?>
  • 188.  Names (also called identifiers)  Must always begin with a dollar-sign ($)  generally start with a letter and can contain letters, numbers, and underscore characters “_”  Names are case sensitive  Values can be numbers, strings, boolean, etc  change as the program executes
  • 189. PHP is a Loosely Typed Language  In PHP a variable does not need to be declared before     being set. In the example above, you see that you do not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on how they are set. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. In PHP the variable is declared automatically when you use it.
  • 190. PHP supports eight primitive types :  Four scalar types:  boolean  integer Float (floating-point number, aka'double')  string •Two compound types:  array  object •And finally two special types:  resource  NULL
  • 191. Variables and Expressions in PHP  Names (also called identifiers)  Must always begin with a dollar-sign ($)  generally start with a letter and can contain letters, numbers, and underscore characters “_”  Names are case sensitive  Values can be numbers, strings, boolean, etc  change as the program executes  Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".
  • 192.      There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator: <?php $first ? $second : $third ?> If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value. The following example should help you understand pre- and post-increment and expressions in general a bit better: <?php function double($i) { return $i*2; } $b = $a = 5; /* assign the value five into the variable $a and $b */ $c = $a++; /* post-increment, assign original value of $a (5) to $c */ $e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */ /* at this point, both $d and $e are equal to 6 */ $f = double($d++); /* assign twice the value of $d before the increment, 2*6 = 12 to $f */ $g = double(++$e); /* assign twice the value of $e after the increment, 2*7 = 14 to $g */ $h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24. the value of the assignment (24) is then assigned into $h, and $h ends with the value of 24 as well. */ ?>
  • 193. PHP Operators  c=a+b  Assuming a and b are numbers (remember data types? -- the result would be different if they were strings -- more about that later) this expression would add a and b and put the sum into c (remember again, that the equals sign here makes this an assignment instruction.) In the expression a + b the plus sign is an arithmetic operator. Here are some more operators:  Arithmetic Operators:  Comparison Operators:  Logical Operators:  Increment and Decrement Operators:  The Concatenate Operator  Combined Operators:
  • 194. PHP Operators  Operators are used to operate on values.  PHP Operators  This section lists the different operators used in PHP.  Arithmetic Operators
  • 197. Conditional Test, Events and Flows in PHP  PHP If & Else Statements  The if, elseif and else statements in PHP are used to perform different actions based on different conditions. Conditional Statements  Very often when you write code, you want to perform different actions for different decisions.  You can use conditional statements in your code to do this.  if...else statement -use this statement if you want to execute a set of code when a condition is true and another if the condition is not true  elseif statement -is used with the if...else statement to execute a set of code if one of several condition are true
  • 198. PHP If & Else Statements The If...Else Statement  If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.  Example      The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body><?php $d=date("D"); if ($d=="Fri")  echo "Have a nice weekend!";  echo "Have a nice day!";  else  ?></body>  </html>
  • 199. PHP If & Else Statements  If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:  <html>  <body><?php  $d=date("D");  if ($d=="Fri") {    echo "Hello!<br/>"; echo "Have a nice weekend!"; echo "See you on Monday!"; }  ?></body>  </html>
  • 200. PHP If & Else Statements  The ElseIf Statement  If you want to execute some code if one of several conditions are true use the elseif statement Syntax if (condition) code to be executed if condition is true; elseif(condition) code to be executed if condition is true; else code to be executed if condition is false;
  • 201. PHP If & Else Statements Example The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!": <html> <body><?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif($d=="Sun") echo "Have a nice Sunday!"; Else echo "Have a nice day!"; ?></body> </html>
  • 202.  PHP Switch Statement  •The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions.  The Switch Statement  •If you want to select one of many blocks of code to be executed, use the Switch statement.  •The switch statement is used to avoid long blocks of if..elseif..else code.     Syntax switch (expression) { case label1:  code to be executed if expression = label1;  break;  case label2:  code to be executed if expression = label2;  break;  default:  code to be executed  if expression is different  from both label1 and label2;  }
  • 203. PHP Switch Statement Example  This is how it works:  A single expression (most often a variable) is evaluated once  The value of the expression is compared with the values for each case in the structure  If there is a match, the code associated with that case is executed  After a code is executed, break is used to stop the code from running into the next case  The default statement is used if none of the cases are true <html> <body><?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?></body> </html>
  • 204. Iteration  Iteration or looping is a way to execute a block of program     statements more than once we will use the for statement to create loops The for loop is generally controlled by counting There is an index variable that you increment or decrement each time through the loop When the index reaches some limit condition, then the looping is done and we continue on in the code
  • 205. Why do we want loops in our code? • Do something for a given number of times or for every object in a collection of objects  for every radio button in a form, see if it is checked  for every month of the year, charge $100 against the balance  calculate the sum of all the numbers in a list  Many loops are counting loops  they do something a certain number of times
  • 209. PHP Looping Looping statements in PHP are used to execute the same block of code a specified number of times. Looping  Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this. In PHP we have the following looping statements:  while -loops through a block of code if and as long as a specified condition is true  do...while -loops through a block of code once, and then repeats the loop as long as a special condition is true  for -loops through a block of code a specified number of times  foreach-loops through a block of code for each element in an array
  • 210. PHP Looping The while Statement The while statement will execute a block of code if and as long as a condition is true. Syntax  while (condition)  code to be executed;  Example  The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body><?php $i=1; while($i<=5) { echo "The number is " . $i . "<br/>"; $i++; } ?></body> </html>
  • 211. PHP Looping The do...while Statement   •The do...while statement will execute a block of code at least once-it then will repeat the loop as long as a condition is true. Syntax do { code to be executed; } while (condition); Example  The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 5: <html> <body><?php $i=0; do { $i++; echo "The number is " . $i . "<br/>"; } while ($i<5); ?></body> </html>
  • 212. PHP Looping The for Statement •The for statement is used when you know how many times you want to execute a statement or a list of statements.  Syntax  for (initialization; condition; increment) { code to be executed; } Note: The for statement has three parameters. The first parameter initializes variables, the second parameter holds the condition, and the third parameter contains the increments required to implement the loop. If more than one variable is included in the initialization or the increment parameter, they should be separated by commas. The condition must evaluate to true or false.  Example  The following example prints the text "Hello World!" five times: <html> <body><?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br/>"; } ?></body> </html>
  • 213. PHP Looping The foreach Statement  The for each statement is used to loop through arrays.  For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) -so on the next loop, you'll be looking at the next element.  Syntax foreach(array as value) { code to be executed; }  Example  The following example demonstrates a loop that will print the values of the given array: <html> <body><?php $arr=array("one", "two", "three"); foreach($arras $value) { echo "Value: " . $value . "<br/>"; } ?></body> </html>
  • 214. Project Based Lab  Prepare a flowchart and DFD of the project whichever is assign to you ..  Flowchart indicate the workflow of the system.  A data flow diagram (DFD) is a graphical representation of the "flow" of data through an information system. It differs from the flowchart as it shows the data flow instead of the control flow of the program.
  • 215. Difference between echo and print 1. Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster 2. Expression. print() behaves like a function in that you can do: $ret = print "Hello World"; And $ret will be 1. That means that print can be used as part of a more complex expression where echo cannot. An example from the PHP Manual: $b ? print "true" : print "false";
  • 216. 3. Parameter(s). The grammar is: echo expression [, expression[,expression] ... ] But echo ( expression, expression ) is not valid. This would be valid: echo ("howdy"),("partner"); the same as: echo "howdy","partner"; So, echo without parentheses can take multiple parameters, which get concatenated: echo "and a ", 1, 2, 3; // comma-separated without parentheses echo ("and a 123"); // just one parameter with parentheses print() can only take one parameter: print ("and a 123"); print "and a 123";
  • 217. Functions and Arrays using PHP
  • 218. PHP Functions The real power of PHP comes from its functions.  In PHP -there are more than 700 built-in functions available.  Create a PHP Function  A function is a block of code that can be executed whenever we need it. Creating PHP functions:  All functions start with the word "function()"  Name the function -It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number)  Add a "{"-The function code starts after the opening curly brace  Insert the function code  Add a "}"-The function is finished by a closing curly brace
  • 219. PHP Functions Example •A simple function that writes my name when it is called: <html> <body><?php Function writeMyName() { echo "Kai JimRefsnes"; } writeMyName(); ?></body> </html> Use a PHP Function •Now we will use the function in a PHP script: <html> <body><?php function writeMyName() { echo "Kai JimRefsnes"; } echo "Hello world!<br/>"; echo "My name is "; writeMyName(); echo ".<br/>That's right, "; writeMyName(); echo " is my name."; ?></body> </html>
  • 220. PHP Functions The output of the code above will be: Hello world! My name is Kai JimRefsnes. That's right, Kai JimRefsnes is my name. PHP Functions -Adding parameters •Our first function (writeMyName()) is a very simple function. It only writes a static string. •To add more functionality to a function, we can add parameters. A parameter is just like a variable. •You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are specified inside the parentheses. Example 1 •The following example will write different first names, but the same last name: <html> <body><?php function writeMyName($fname) { echo $fname. "Refsnes.<br/>"; } echo "My name is "; writeMyName("Kai Jim");echo "My name is "; writeMyName("Hege");echo "My name is "; writeMyName("Stale"); ?></body>
  • 221. PHP Functions •The output of the code above will be: My name is Kai JimRefsnes. My name is Hege Refsnes. My name is Stale Refsnes. Example 2 •The following function has two parameters: <html> <body><?php function writeMyName($fname,$punctuation) { echo $fname. "Refsnes" . $punctuation . "<br/>"; } echo "My name is "; writeMyName("Kai Jim","."); echo "My name is "; writeMyName("Hege","!"); echo "My name is "; writeMyName("Ståle","..."); ?></body> </html>
  • 222. PHP Functions •The output of the code above will be: My name is Kai Jim Refsnes. My name is Hege Refsnes! My name is Ståle Refsnes... PHP Functions -Return values •Functions can also be used to return values. Example <html> <body><?php function add($x,$y) { $total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16); ?></body> </html> The output of the code above will be: 1 + 16 = 17
  • 229. PHP Date() PHP Date -Format the Date •The first parameter in the date() function specifies how to format the date/time. It uses letters to represent date and time formats. Here are some of the letters that can be used: •d -The day of the month (01-31) •m -The current month, as a number (01-12) •Y -The current year in four digits  Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting: <?php echo date("Y/m/d"); echo "<br/>"; echo date("Y.m.d"); echo "<br/>"; echo date("Y-m-d"); ?> The output of the code above could be something like this: 2009/07/11 2009.07.11 2009-07-11
  • 230. PHP Date()  PHP Date -Adding a Timestamp •The second parameter in the date() function specifies a timestamp. This parameter is optional. If you do not supply a timestamp, the current time will be used. •In our next example we will use the mktime() function to create a timestamp for tomorrow. •The mktime() function returns the Unix timestamp for a specified date.  Syntax •mktime(hour,minute,second,month,day,year,is_dst) •To go one day in the future we simply add one to the day argument of mktime(): <?php $tomorrow =mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?>  The output of the code above could be something like this:  Tomorrow is 2006/07/12
  • 231. PHP Arrays • An array can store one or more values in a single variable name. What is an array? • When working with PHP, sooner or later, you might want to create many similar variables. • Instead of having many similar variables, you can store the data as elements in an array. • Each element in the array has its own ID so that it can be easily accessed. • There are three different kind of arrays: • Numeric array -An array with a numeric ID key • Associative array -An array where each ID key is associated with a value • Multidimensional array -An array containing one or more arrays Numeric Arrays • A numeric array stores each element with a numeric ID key. • There are different ways to create a numeric array. Example 1 • In this example the ID key is automatically assigned: $names = array("Peter","Quagmire","Joe");
  • 232. PHP Arrays Example 2 • In this example we assign the ID key manually: $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; •The ID keys can be used in a script: <?php $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors"; ?> •The code above will output: Quagmire and Joe are Peter's neighbors
  • 233. PHP Arrays Associative Arrays •An associative array, each ID key is associated with a value. •When storing data about specific named values, a numerical array is not always the best way to do it. •With associative arrays we can use the values as keys and assign values to them. Example 1 •In this example we use an array to assign ages to the different persons: $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); Example 2 This example is the same as example 1, but shows a different way of creating the array: $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?> The code above will output: Peter is 32 years old.
  • 234. PHP Arrays Multidimensional Arrays •In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Example •In this example we create a multidimensional array, with automatically assigned ID keys: $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
  • 235. PHP Arrays •The array above would look like this if written to the output: Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) )
  • 236. Commonly used Array Functions  array_combine --Creates an array by using one array for keys and             another for its values array_count_values --Counts all the values of an array Array_diff -Computes the difference of arrays Array_merge -Merge one or more arrays Array_merge_recursive -Merge two or more arrays recursively Array_reverse -Return an array with elements in reverse order Array_search -Searches the array for a given value and returns the corresponding key if successful Array_sum -Calculate the sum of values in an array Arsort-Sort an array in reverse order and maintain index association Asort-Sort an array and maintain index association Krsort-Sort an array by key in reverse order Ksort-Sort an array by key sizeof-
  • 237. Array Functions Example:<?php $a1=array("a","b","c","d"); $a2=array("Cat","Dog","Horse","Cow"); print_r(array_combine($a1,$a2)); ?> o/p:- Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow ) <?php $a=array("Cat","Dog","Cat","Dog"); print_r(array_count_values($a)); ?> o/p:-Array ( [Cat] => 2 [Dog] => 2 ) <?php $a1=array(0=>"Cat",1=>"Dog",2=>"Horse"); $a2=array(3=>"Horse",4=>"Dog",5=>"Fish"); print_r(array_diff($a1,$a2)); ?> <br /> <br /> <?php $a1=array("a"=>"Horse","b"=>"Dog"); $a2=array("c"=>"Cow","b"=>"Cat"); print_r(array_merge($a1,$a2)); ?> o/p:- Array ( [0] => Cat ) Array ( [a] => Horse [b] => Cat [c] => Cow )
  • 238. <?php $a1=array("a"=>"Horse","b"=>"Dog"); $a2=array("c"=>"Cow","b"=>"Cat"); print_r(array_merge_recursive($a1,$a2)); ?> <br /> <br /> <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); print_r(array_reverse($a)); ?> Output:Array ( [a] => Horse [b] => Array ( [0] => Dog [1] => Cat ) [c] => Cow ) Array ( [c] => Horse [b] => Cat [a] => Dog ) <?php $a=array("a"=>"5","b"=>5,"c"=>"5"); echo array_search(5,$a,true); ?> <br /> <br /> <?php $a=array(0=>"5",1=>"15",2=>"25"); echo array_sum($a); ?> b 45
  • 239. <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); $result = sizeof($people); echo $result; ?> Output:- 4
  • 244. PHP Arrays  Example 2 Lets try displaying a single value from the array above: echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?"; The code above will output:   Is Megan a part of the Griffin family?
  • 245. PHP Include File • Server Side Includes (SSI) are used to create functions, headers, s, or elements that will be reused on multiple pages. Server Side Includes •You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except how they handle errors. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error). •These two functions are used to create functions, headers, s, or elements that can be reused on multiple pages. •This can save the developer a considerable amount of time. This means that you can create a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all web pages).
  • 246. • Include_once and require_once is also use for include any file into your code. • But the difference between include and include_once is in include if there is any error in include file there is no effect on the code where it is included but in include_once there is effect in the code if there is any error.
  • 247. PHP Include File The include() Function •The include() function takes all the text in a specified file and copies it into the file that uses the include function. Example 1 •Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function, like this: <html> <body> <?phpinclude("header.php"); ?> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> Example 2 Now, let's assume we have a standard menu file that should be used on all pages (include files usually have a ".php" extension). Look at the "menu.php" file below: <html> <body> <ahref="http://www.example.com/default.php">Home</a> | <ahref="http://www. example.com/about.php">About Us</a> | <ahref="http://www. example.com/contact.php">Contact Us</a> The three files, "default.php", "about.php", and "contact.php" should all include the "menu.php" file. Here is the code in "default.php": <?phpinclude("menu.php"); ?> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html>
  • 248. PHP Include File If you look at the source code of the "default.php" in a browser, it will look something like this: <html> <body> <ahref="default.php">Home</a> | <ahref="about.php">About Us</a> | <ahref="contact.php">Contact Us</a> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> • And, of course, we would have to do the same thing for "about.php" and "contact.php". By using include files, you simply have to update the text in the "menu.php" file if you decide to rename or change the order of the links or add another web page to the site.
  • 249. PHP Include File The require() Function •The require() function is identical to include(), except that it handles errors differently. •The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error). •If you include a file with the include() function and an error occurs, you might get an error message like the one below. PHP code: •<html> •<body> •<?php •include("wrongFile.php"); •echo "Hello World!"; •?> •</body> •</html> Error message: Warning:include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:homewebsitetest.phpon line 5 Warning:include() [function.include]: Failed opening'wrongFile.php'for inclusion (include_path='.;C:php5pear') in C:homewebsitetest.phpon line 5 Hello World!
  • 250. PHP Include File • The echo statement was not executed because the script execution stopped after the fatal error. • It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
  • 251.  HTTP Overview  HTTP is the protocol (the set of 'rules') for transferring data (e.g. HTML in web pages, pictures, files) between web servers and client browsers, and usually takes place on port80. This is where the 'http://' in website URLs comes from.  Headers can be separated into two broad types: Request the headers that your browser sends to the server when you request a file, and Response headers that the server sends to the browser when it serves the file.  PHP header(): The Basics  Using this function, you can make your scripts send headers of your choosing to the browser, and create some very useful and dynamic results. However, the first thing you need to know about the header() function is that you have to use it before PHP has sent any output (and therefore its default headers).
  • 253.  PHP header(): Some Examples  header('Location:http://www.mysite.com/new_location.html');   While you can sometimes get away with supplying a relative URL for the value, according to the HTTP specification, you should really use an absolute URL. One mistake that is easy to make with the Location header is not calling exit directly afterwards (you may not always want to do this, but usually you do). The reason this is a mistake is that the PHP code of the page continues to execute even though the user has gone to a new location. In the best case, this uses system resources unnecessarily. In the worst case, you may perform tasks that you never meant to.     <?php header('Refresh:10;url=http://www.mysite.com/otherpage.php'); echo'Youwillberedirectedin10seconds'; ?>  Redirecting with the Refresh header  The Refresh redirects users like the Location header does, but you can add a delay before the user is redirected. For example, the following code would redirect the user to a new page after displaying the current one for 10 seconds
  • 254. Serving different types of files and generating dynamic content using the Content-Type header  The Content-Type header tells the browser what type of data the server is about to send. Using this header, you can have your PHP scripts output anything from plaintext files to images or zip files. The table below lists frequently-used MIME types: <?php header'Connt-Type:text/plain'); Echo $lain_text_content; ?>  You can do several interesting things with this. For example, perhaps you want to send the user a pre-formatted text file rather than HTML: <?php header('Content-Type:application/octet-stream'); // name of the File Name header('Content-Disposition: attachment; '.'filename="plain_text_file.txt"'); // given name and with MIME type. echo $plain_text_content; ?>  Or perhaps you'd like to prompt the user to download the file, rather than viewing it in the browser. With the help of the ContentDisposition header, it's easy to do, and you can even suggest a file name for the user to use:
  • 255. PHP String         A string variable is used to store and manipulate a piece of text. Strings in PHP String variables are used for values that contains character strings. In this tutorial we are going to look at some of the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the string "Hello World" to a string variable called $txt: <?php$txt="Hello World"; echo $txt; ?>The output of the code above will be: HelloWorld Now, lets try to use some different functions and operators to manipulate our string.
  • 256. PHP String • The Concatenation Operator  There is only one string operator in PHP.  The concatenation operator (.)is used to put two string values together.  To concatenate two variables together, use the dot (.) operator: <?php $txt1="Hello World"; $txt2="1234"; echo $txt1 . " " . $txt2; ?>  The output of the code above will be:  Hello World 1234  If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.  Between the two string variables we added a string with a single character, an empty space, to separate the two variables.
  • 257. PHP String Using the strlen() function •The strlen() function is used to find the length of a string. •Let's find the length of our string "Hello world!": <?php echo strlen("Hello world!"); ?> •The output of the code above will be:12 •The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string) Using the strpos() function •The strpos() function is used to search for a string or character within a string. •If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. •Let's see if we can find the string "world" in our string: <?php echo strpos("Hello world!","world"); ?> •The output of the code above will be:6 •As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.
  • 258. Commonly used String Functions              addslashes—Quote string with slashes explode —Split a string by string implode —Join array elements with a string join —Alias of implode() md5 —Calculate the md5 hash of a string nl2br —Inserts HTML line breaks before all new lines in a string str_split —Convert a string to an array strcmp—Binary safe string comparison print —Output a string strlen—Get string length strtolower—Make a string lowercase strtoupper—Make a string uppercase trim —Strip whitespace(or other characters) from the beginning and end of a string
  • 259.  Other String Functions              number_format —Format a number with grouped thousands rtrim—Strip whitespace (or other characters) from the end of a string str_ireplace—Case-insensitive version of str_replace(). str_repeat —Repeat a string str_replace —Replace all occurrences of the search string with the replacement string str_shuffle —Randomly shuffles a string str_word_count —Return information about words used in a string strcasecmp—Binary safe case-insensitive string comparison strchr—Alias ofstrstr() strcspn—Find length of initial segment not matching mask stripos—Find position of first occurrence of a case-insensitive string stripslashes—Un-quote string quoted with addslashes() stristr—Case-insensitive strstr()
  • 260.  Other String Functions (contd…)  strnatcasecmp—Case insensitive string comparisons using a "natural order"              algorithm strnatcmp—String comparisons using a "natural order" algorithm strncasecmp—Binary safe case-insensitive string comparison of the first n characters strncmp—Binary safe string comparison of the first n characters strpbrk—Search a string for any of a set of characters strpos—Find position of first occurrence of a string strrchr—Find the last occurrence of a character in a string strrev—Reverse a string strripos—Find position of last occurrence of a case-insensitive string in a string strrpos—Find position of last occurrence of a char in a string strspn—Find length of initial segment matching mask strstr—Find first occurrence of a string substr_compare —Binary safe comparison of 2 strings from an offset, up to length characters substr_count —Count the number of substring occurrences
  • 261.  Other String Functions (contd…)  substr_replace —Replace text within a portion of a string  substr—Return part of a string  ucfirst—Make a string's first character uppercase  ucwords—Uppercase the first character of each word in a string  wordwrap—Wraps a string to a given number of characters
  • 262. String Function Example <?php $str = "Hello, my name is Kai Jim."; echo $str."<br />"; echo addcslashes($str,'m')."<br />"; echo addcslashes($str,'K')."<br />"; ?> Hello, my name is Kai Jim. Hello, my name is Kai Jim. Hello, my name is Kai Jim. <?php $str = "Hello world. It's a beautiful day."; print_r (explode(" ",$str)); ?> Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. ) <?php $arr = array('Hello','World!','Beautiful','Day!'); echo implode(" ",$arr); ?> Hello World! Beautiful Day!
  • 263. String Function Example <?php $arr = array('Hello','World!','Beautiful','Day!'); echo join(" ",$arr); ?> Hello World! Beautiful Day! <?php $str = "Hello"; echo md5($str); ?> 8b1a9953c4611296a827abf8c47804d7 32 <?php echo nl2br("One line.nAnother line."); ?> One line. Another line. print_r(str_split("Hello",3)); $str = "Who's Kai Jim?"; print $str; print "<br />"; print $str."<br />I don't know!"; Array ( [0] => Hel [1] => lo )
  • 264. String Function Example <?php $str = "Hello"; $number = 123; printf("%s world. Day number %u",$str,$number); ?> Hello world. Day number 123 <?php echo strtolower("Hello WORLD."); ?> <?php echo strlen("Hello world!"); ?>
  • 266. PHP And MySQL What is MySQL? •MySQL is a database server •MySQL is ideal for both small and large applications •MySQL supports standard SQL •MySQL compiles on a number of platforms •MySQL is free to download and use PHP + MySQL •PHP combined with MySQL are cross-platform (means that you can develop in Windows and serve on a Unix platform) Where to Start? •Install an Apache server on a Windows or Linux machine •Install PHP on a Windows or Linux machine •Install MySQL on a Windows or Linux machine
  • 267. DBMS •A database management system (DBMS) is a system, usually automated and computerized, used to manage any collection of compatible, and ideally normalized data. •The DBMS manages storage and access to the data, and provides a query language to specify actions associated with the data. The standard query language is SQL. •A DBMS generally provides a client application that can be used to directly manipulate the data, as well as a programmable interface. MySQL provides a set of command line clients, as well as a program interface.
  • 268. Relational Databases  Information is stored in tables. Tables store information about entities  Entities have characteristics called attributes  Each row in a table represents a single entity Each row is a set of attribute values Every row must be unique, identified by a key  Relationships --associations among the data values are stored
  • 270. MYSQL database and queries Connecting to a MySQL Database •Before you can access and work with data in a database, you must create a connection to the database. •In PHP, this is done with themysql_connect() function. Syntax •mysql_connect(servername,username,password); •Example mysql_connect(‘localhost’,root’,’’); Closing a Connection  The connection will be closed as soon as the script ends. To close the connection before, use themysql_close() function.
  • 272. PHP MySQL Create Database and Tables • A database holds one or multiple tables. Create a Database • The CREATE DATABASE statement is used to create a database in MySQL. Syntax CREATE DATABASE database_name • To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example:- mysql_query(‘send’) • In the following example we create a database called "my_db":
  • 273. PHP MySQL Create Database and Tables Create a Table The CREATE TABLE statement is used to create a database table in MySQL. Syntax CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, ....... ) We must add the CREATE TABLE statement to the mysql_query() function to execute the command. Example The following example shows how you can create a table named "person", with three columns. The column names will be "First Name", "Last Name" and "Age" Important: A database must be selected before a table can be created. The database is selected with the mysql_select_db() function. Note: When you create a database field of type varchar, you must specify the maximum length of the field, e.g.varchar(15).
  • 274. MySQL Data Types  Below are the different MySQL data types that can be used:
  • 276. Database Terminology  Primary Key:     Always Integer Unique Never Null Auto-increment  Foreign Key:    Foreign Key is a linking pin between two tables. A key used in the one table to represent the value of the primary key in a related table. While primary key must contains unique values, foreign key must have duplicates.  Ex: If we use student_id as a primary key in the student table (each student has a unique id), we could use student id as a foreign key in a source table as each student may do more than one course.
  • 277.  Compound Key  Compound key is a key that consists of 2 or more attributes that uniquely identifies an entity occurrences.  Each attribute that makes up the compound key is a simple key on its own.
  • 278. Primary Keys and Auto Increment Fields  Each table should have a primary key field.  A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique within the table. Furthermore, the primary key field cannot be null because the database engine requires a value to locate the record.  The primary key field is always indexed. There is no exception to this rule! You must index the primary key field so the database engine can quickly locate rows based on the key's value.  The following example sets the person ID field as the primary key field. The primary key field is often an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the value of the field by1 each time a new record is added. To ensure that the primary key field cannot be null, we must add the NOT NULL setting to the field.
  • 279. Normalization The process of structuring data to minimize duplication and inconsistencies. •The process usually involves breaking down the single table into two or more tables and defining relationships between those tables. •Normalization is usually done in stages. •Most people in creating database, never need to go to beyond the third level of normalization.  1. First Normal Form:  2. Second Normal Form  3. Third Normal Form
  • 280.  First Normal Form:  Eliminate duplicative columns from the same table.  Create separate tables for each group related data and identify each row with a unique columns.  When a table is decomposed into two-dimensional tables with all repeating groups of data eliminated ,the table data is said to be in it’s 1NF. Field Key Type  Example:Project number -Project Name -- Employee Number -- 1-n Employee Name -- 1-n Rate Category -- 1-n Hourly rate -- 1-n  N-1 indicates that there are many occurrences of this field – it is a repeating group.
  • 281. Project number Project Name Employee Number Employee Name Rate Category Hourly rate P001 PHP E001 Taher A 7000 P001 PHP E002 Mohit B 6500 P001 PHP E006 Hansel C 4500 P002 PHP(joomla) E001 Taher A 7000 P002 PHP(Joomla) E007 Nitesh B 4000
  • 282. 2ndNormal Form:  A 1NF is in 2NF if and only if its non-prime attributes are functionally dependent on a part of the candidate key.  A table is said to be in it’s second normal form when each record in the table is in the First normal form and each column in the record is fully dependent on it’s primary key.  Step: Find and Remove Fields that are related to the only part of the key.  Group the removed items in the another table.  Assign the new table with the key i.e part of a whole composite key.
  • 283. 2nd NF Example Field Key Project Number Primary Key Employee Number Primary Key Field Key Employee Number Primary key Employee Name -- Rate category -- Hourly Rate -- Project Number Primary Key Project Name -- Table: Emproj Table:- Emp Table:- proj
  • 284. 3rdNormal Form  If and only if  The Relation is in second NF  Every Non-prime attribute of R is non-transitively dependent on every key of R.  Table data is said to be in third normal format when all transitive dependencies are removed from this data.  A general case of transitive dependencies is follow: A,B,C are three columns in Table.  If C is related to B  If B is related to A  Then C is indirectly related to A  This is when transitive dependency exists.
  • 285. 3rd NF Example Table :EmpProj Project Number Table: Emp Primary Key Employee Number Primary Key Primary Key Hourly rate -- Primary Key Employee Name -- Rate Category Table:Rate Rate Category Employee Number -- Table:proj Project Number Primary key Project Name There are another normal Forms such as Boyce-Codd NF 4th Normal Form But this are very rarely used for business application. In most case ,table that are in 3rd NF are already conform to these type of table formats anyway.
  • 286. PHP MySQL Insert Into  The INSERT INTO statement is used to insert new records into a database table Insert Data Into a Database Table  The INSERT INTO statement is used to add new records to a database table . Syntax  You can also specify the columns where you want to insert the data:  INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....) Note: SQL statements are not case sensitive. INSERT INTO is the same as insert into. To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example: $ins = insert into (id,unm,upass) values(‘’,’Taher’,’Taher’); mysql_query($ins);
  • 287. PHP MySQL Insert Into Insert Data From a Form Into a Database  Now we will create an HTML form that can be used to add new records to the "Person" table.  Here is the HTML form:
  • 288. PHP MySQL Insert Into Query • When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php". The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST variables. Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the database table.  Example of the code in the "insert.php" page  If(isset($_request[‘’])) { $ins = “ insert into values(‘$_request[‘name’],$_request[‘age’]); mysql_query(‘$ins’); }
  • 289. PHP MySQL Select • The SELECT statement is used to select data from a database. Select Data From a Database Table • The SELECT statement is used to select data from a database.  Syntax SELECT column_name(s) FROM table_name Note: SQL statements are not case sensitive. SELECT is the same as select. To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. The example above stores the data returned by the mysql_query() function in the $result variable. Next, we use the mysql_fetch_array() function to return the first row from the record set as an array. Each subsequent call to mysql_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']).
  • 290. PHP MySQL Select  The following example selects the same data as the example above, but will display the data in an HTML table:  The output of the code above will be:
  • 291. PHP MySQL The Where Clause • To select only data that matches a specified criteria, add a WHERE clause to the SELECT statement. The WHERE clause  To select only data that matches a specific criteria, add a WHERE clause to the SELECT statement.  Syntax
  • 293. PHP MySQL Order By Keyword  The ORDER BY keyword is used to sort the data in are cordset.The ORDER BY Keyword  The ORDER BY keyword is used to sort the data in are cordset.  Example:-  SELECT column_name(s)FROM table_nameORDER BY column_name
  • 294. Diff Between Group by and order by • The Group by can be specified after the select * from table name and we can also use the where clause or having clause for it, but in the case for order by we have to use the where clause and after which the Order by should come Example:-( for Group By) select * from books group by book_name having book_rate > 10; example for Order By select * from books where book_rate > 10 order by book_name;
  • 295. Example of Order by :Below simle tabel: SELECT * FROM `registraton` ORDER BY user_name LIMIT 0 , 30
  • 296. Example of Group by  SELECT count(*) "Total Indian Man" ,sum(pass)"sum of password" FROM `registraton` group by contry
  • 297. JOINS  Different SQLJOINs  Before we continue with examples, we will list the types of JOIN you can use, and  the differences between them.  JOIN: Return rows when there is at least one match in both tables  LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table  RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table  SQL INNER JOIN Keyword   The INNER JOIN keyword return rows when there is at least one match in both tables. SQL INNER JOIN Syntax Example:- SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name  Note: INNER JOIN is the same as JOIN.
  • 298. Join(inner) Consider the following SQL statement: SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer FROM Customers, Sales WHERE Customers.CustomerID = Sales.CustomerID GROUP BY Customers.FirstName, Customers.LastName The SQL expression above will select all distinct customers (their first and last names) and the total respective amount of dollars they have spent. The SQL JOIN condition has been specified after the SQL WHERE clause and says that the 2 tables have to be matched by their respective CustomerID columns.
  • 299. Joins (contd…)  There are 2 types of SQL JOINS –INNER JOINS and OUTER JOINS. If you don't put INNER or OUTER keywords in front of the SQL JOIN keyword, then INNER JOIN is used. In short "INNER JOIN" = "JOIN" (note that different databases have different syntax for their JOIN clauses).  The INNER JOIN will select all rows from both tables as long as there is a match between the columns we are matching on. In case we have a customer in the Customers table, which still hasn't made any orders (there are no entries for this customer in the Sales table), this customer will not be listed in the result of our SQL query above.
  • 300. Outer Join  The second type of SQL JOIN is called SQL OUTER JOIN and it has 2 sub-types called LEFT OUTER JOIN and RIGHT OUTER JOIN.  The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the OUTER keyword in most databases), selects all the rows from the first table listed after the FROM clause, no matter if they have matches in the second table.
  • 301. PHP MySQL Order By Keyword Sort Ascending or Descending • If you use the ORDER BY keyword, the sort-order of there cordset is ascending by default (1 before 9 and "a" before "p"). • Use the DESC keyword to specify a descending sort-order (9 before 1 and "p" before "a"): Order by Two Columns •It is possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are identical:
  • 305. PHP Cookies A message given to a Web browser by a Web server. The browser stores the message in a text file. The message is then sent back to the server each time the browser requests a page from the server. •A cookie is often used to identify a user What is a Cookie? A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. How to Create a Cookie? •The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax •setcookie(name, value, expire, path, domain);
  • 306. Example Cookies Set Cookies:<?php setcookie("user","tom",time()+3660); echo "cookie is set"; ?> Retrieve Cookies:<?php echo "Cookie value is ".$_COOKIE['user']; ?> • In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour <?php setcookie("user", "Alex Porter", time()+3600); ?> <html> <body> </body> </html> Note: The value of the cookie is automatically URL encoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use set raw cookie() instead).
  • 308. PHP Cookies How to Delete a Cookie? •When deleting a cookie you should assure that the expiration date is in the past. •Delete example: <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?> The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> Retrieve the values in the "welcome.php" file like this: <html> <body> Welcome <?php echo $_POST["name"]; ?>.<br/> You are <?php echo $_POST["age"]; ?> years old. </body>
  • 309. PHP Sessions •A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. PHP Session Variables •When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. •A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. •Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
  • 310.  PHP Sessions – Overview  A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.  It is important to ponder if the sessions' temporary storage is applicable to your website. If you require a more permanent storage you will need to find another solution, like a MySQL database.  Sessions work by creating a unique identification (UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from getting confused with one another when visiting the same webpage.  Note: If you are not experienced with session programming it is not recommended that you use sessions on a website that requires highsecurity, as there are security holes that take some advanced techniques to plug.
  • 311. Starting a PHP Session  Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.  Below is a simple script that you should place at the beginning of your PHP code to start up a PHP session.  PHP Code:  This tiny piece of code will register the user's session with the server, allow you to start saving user information and assign a UID (unique identification number) for that user's session.
  • 312. PHP Sessions Starting a PHP Session • Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the <html> tag: <?php session_start(); ?> <html> <body> </body> </html> • The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session. Storing a Session Variable •The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: <?php session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html>
  • 313. PHP Sessions Output: •Pageviews=1 •In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1: <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?>
  • 314. PHP Sessions Destroying a Session • If you wish to delete some session data, you can use the unset()or the session_destroy() function. • The unset() function is used to free the specified session variable: <?php unset($_SESSION['views']); ?> •You can also completely destroy the session by calling the session_destroy() function: <?php session_destroy(); ?> Note: session_destroy() will reset your session and you will lose all your stored session data.
  • 315. Understanding session  This piece of code does one of two things. If the user does not already have a session, it creates a new session -or -if the user does already have a session it connects to the existing session file. When a new session is created, PHP session management generates a session identifier that consists of a random 32 hex digit string and creates an empty session file on the server with the name sess_ followed by the session identifier. It also includes a set-cookie in the response and a session cookie in the browser with the value of the session identifier. This means that any subsequent request to the server will include this session identifier allowing PHP to connect to the appropriate session file.  <?php session_start(); ?>
  • 320. PHP File Upload Restrictions on Upload •In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br/>"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br/>"; echo "Type: " . $_FILES["file"]["type"] . "<br/>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br/>"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; } ?> Note: For IE to recognize jpg files the type must be p jpeg, for Fire Fox it must be jpeg.
  • 321. PHP File Upload Saving the Uploaded File •The examples above create a temporary copy of the uploaded filesin the PHP temp folder on the server. •The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br/>"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br/>"; echo "Type: " . $_FILES["file"]["type"] . "<br/>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br/>"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br/>"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> •The script above checks if the file already exists, if it does not, it copies the file to the specified folder. Note:This example saves the file to a new folder called "upload"
  • 323. Multiple File Upload  Example:-imgck.php
  • 324.  Example:- img.php Also Make a Folder:- upimg
  • 325. Another Example <form action="" method="post“ enctype="multipart/form-data"> <p>Pictures: <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="submit" value="Send" /> </p> </form> <?php foreach($_FILES["pictures"]["error"]as$key=>$error){ if($error==UPLOAD_ERR_OK){ $tmp_name=$_FILES["pictures"]["tmp_name"][$key]; $name=$_FILES["pictures"]["name"][$key]; move_uploaded_file($tmp_name,"data/$name"); } } ?>
  • 327. PHP File Handling •The fopen() function is used to open files in PHP.  Opening a File • The fopen() function is used to open files in PHP. •The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: <html> <body> <?php $file=fopen("welcome.txt","r");?> </body> </html> •The file may be opened in one of the following modes:
  • 328. PHP File Handling •Note: If the fopen() function is unable to open the specified file, it returns 0 (false). Example •The following example generates a message if the fopen() function is unable to open the specified file: <html> <body> <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?> </body> </html> Closing a File •The fclose() function is used to close an open file: <?php $file =fopen("test.txt","r");//some code to beexecutedfclose($file); ?>
  • 329. PHP File Handling Check End-of-file •The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length. Note: You cannot read from files opened in w, a, and x mode! •if (feof($file)) echo "End of file"; Reading a File Line by Line •The fgets() function is used to read a single line from a file. Note :After a call to this function the file pointer has moved to the next line. Example •The example below reads a file line by line, until the end of file is reached: <?php $file =fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echofgets($file). "<br/>"; } fclose($file); ?>
  • 330. PHP File Handling Reading a File Character by Character •The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character. Example •The example below reads a file character by character, until the end of file is reached: <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>
  • 331. Example Of File Handling
  • 332. php - file write: fwrite function  PHP Code:  $myFile = "testFile.txt"; $fh = fopen($myFile, 'w');  We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you're good to go! $myFile = "testFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "Bobby Boppern"; fwrite($fh, $stringData); $stringData = "Tracy Tannern"; fwrite($fh, $stringData); fclose($fh);  The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.  We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained Bobby Bopper and second contained Tracy Tanner. After we finished writing we closed the file using the fclose function.
  • 334. PHP Sending E-Mails •PHP allows you to send e-mails directly from a script. The PHP mail() Function •The PHP mail() function is used to send emails from inside a script. Syntax •mail(to,subject,message,headers,parameters) •Note: For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file.
  • 335. PHP Sending E-Mails PHP Simple E-Mail • The simplest way to send an email with PHP is to send a text email. • In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail() function to send an e-mail: <?php $to = "[email protected]"; $subject = "Test mail"; $message = "Hello! This is a simple email message."; $from = "[email protected]"; $headers = "From: $from"; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?>
  • 336. PHP Sending E-Mails •With PHP, you can create a feedback-form on your website. The example below sends a text message to a specified e-mail address: <html> <body> <?php if (isset($_REQUEST['email'])) //if "email" is filled out, send email { //send email $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail( "[email protected]", "Subject: $subject", $message, "From: $email" ); echo "Thank you for using our mail form"; } else //if "email" is not filled out, display the form { echo "<form method='post' action='mailform.php'> Email: <input name='email' type='text' /><br/> Subject: <input name='subject' type='text' /><br/> Message:<br/> <textareaname='message' rows='15' cols='40'> </textarea><br/> <input type='submit' /> </form>"; } ?> </body> </html>
  • 337. PHP Secure E-mails • There is a weakness in the PHP e-mail script in the previous chapter. • PHP E-mail Injections • First, look at the PHP code from the previous chapter: <html> <body> <?php if (isset($_REQUEST['email'])) //if "email" is filled out, send email { //send email $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("[email protected]", "Subject: $subject", $message, "From: $email" ); echo "Thank you for using our mail form"; } else //if "email" is not filled out, display the form { echo "<form method='post' action='mailform.php'> Email: <input name='email' type='text' /><br/> Subject: <input name='subject' type='text' /><br/> Message:<br/> <textareaname='message' rows='15' cols='40'> </textarea><br/> <input type='submit' /> </form>"; } ?> </body> </html>
  • 338. PHP Secure E-mails The problem with the code above is that unauthorized users can insert data into the mail headers via the input form. • What happens if the user adds the following text to the email input field in the form? [email protected]%0ACc:[email protected] %0ABcc:[email protected],[email protected], [email protected],[email protected] %0ABTo:[email protected] •The mail() function puts the text above into the mail headers as usual, and now the header has an extra Cc:, Bcc:, and To: field. When the user clicks the submit button, the e-mail will be sent to all of the addresses above! PHP Stopping E-mail Injections •The best way to stop e-mail injections is to validate the input. •The code below is the same as in the previous chapter, but now we have added an input valuator that checks the email field in the form:
  • 339. <html> <body> <?php { function spamcheck($field) //filter_var() sanitizes the e-mail //address using FILTER_SANITIZE_EMAIL $field=filter_var($field, FILTER_SANITIZE_EMAIL); //filter_var() validates the e-mail //address using FILTER_VALIDATE_EMAIL if(filter_var($field, FILTER_VALIDATE_EMAIL)) { return TRUE; } else { return FALSE; } } if (isset($_REQUEST['email'])) {//if "email" is filled out, proceed //check if the email address is invalid $mailcheck=spamcheck($_REQUEST['email']); if ($mailcheck==FALSE) { echo "Invalid input"; } else {//send email $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("[email protected]", "Subject: $subject", $message, "From: $email" ); echo "Thank you for using our mail form"; } } else {//if "email" is not filled out, display the form echo "<form method='post' action='mailform.php'> Email: <input name='email' type='text' /><br/> Subject: <input name='subject' type='text' /><br/> Message:<br/> <textarea name='message' rows='15' cols='40'> </textarea><br/> <input type='submit' /> </form>"; } ?> </body> </html>
  • 340. <form action="" method="post"> <?php function spamcheck($fld) // Othe Example:{ $field=filter_var($fld,FILTER_SANITIZE_EMAIL); if(filter_var($field,FILTER_VALIDATE_EMAIL)) { return true; } else { return false; } } if(isset($_REQUEST['email'])) { $mailcheck=spamcheck($_REQUEST['email']); if($mailcheck==false) { echo "Invalid email address"; } else { $email=$_REQUEST['email']; $sub=$_REQUEST['sub']; $msg=$_REQUEST['msg']; mail(“[email protected]",$sub,$msg,"From: $email")or die("ERROR"); echo "Thank you for using services"; } } else { ?> Your email add: <input type="text" name="email" /><br /><br /> Subject : <input type="text" name="sub" /><br /><br /> Message : <input type="text" name="msg" /><br /><br /> <input type="submit" value="send" /> <?php } ?> </form>
  • 343. Introduction  JavaScript is a cross-platform, object-oriented scripting language invented in web browsers to make web pages more dynamic and give feedback to your user. Adding JavaScript to your HTML code allows you to change completely the document appearance, from changing text, to changing colors, or changing the options available in a drop-down list, or switching one image with another when you roll your mouse over it and much more.  JavaScript is mainly used as a client side scripting language. This means that all the action occurs on the client's side of things. When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it's up to the browser to do something with it.
  • 344. What can JavaScript do?  Here are a few things you can do with JavaScript:  Display information based on the time of the day  JavaScript can check the computer's clock and pull the appropriate data based on the clock information.  Detect the visitor's browser  JavaScript can be used to detect the visitor's browser, and load another page specifically designed for that browser.  Control Browsers  JavaScript can open pages in customized windows, where you specify if the browser's buttons, menu line, status line or whatever should be present.  Validate forms data  JavaScript can be used to validate form data at the client-side saving both the precious server resources and time.  Create Cookies  JavaScript can store information on the visitor's computer and retrieve it automatically next time the user visits your page.  Add interactivity to your website  JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on a button.  Change page contents dynamically  JavaScript can randomly display content without the involvement of server programs .It can read and change the content of an HTML elements or move them around
  • 345. How to implement JavaScript to an HTML page •You can link to outside files (with the file extension .js), or write blocks of code right into your HTML documents with the <script> tag. So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends. <html> <head> <title>My First Script</title> </head> <body> <script type="text/javascript"> <!-//--> </script> </body> </html>
  • 346. Functions • Defining <script type="text/javascript"> function function_name (argument_1, ... , argument_n) {statement_1; statement_2; statement_m; return return_value; } </script>
  • 347. Example <html> <head> <script type="text/javascript"> function showmessage() { alert(“JavaScript !"); } </script> </head> <body> <form name="myform"> <input type="button" value="Click me!“ onclick="showmessage()"> </form> </body> </html>
  • 349. Form Validation  Any interactive web site has form input -a place where the users input different kind of information. This data is passed to script, or some other technology and if the data contains an error, there will be a delay before the information travels over the Internet to the server, is examined on the server, and then returns to the user along with an error message.  If you run a validation of the user’s form input before the form is submitted, there will be no wait time and redundant load on the server. "Bad data" are already filtered out when input is passed to the serverbased program.  Client side form validation usually done with JavaScript. For the majority of your users, JavaScript form validation will save a lot of time up front, but double-checking the data on the server remains necessary, in case the user has turned JavaScript off.
  • 350. Events •Events •By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. •Every element on a web page has certain events which can trigger JavaScript. For example, we can use the onClickevent of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. •Examples of events: •* A mouse click • * A web page or an image loading • *Mousing over a hot spot on the web page • * Selecting an input field in an HTML form • * Submitting an HTML form •* A keystroke
  • 351. Events • Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs! • For a complete reference of the events recognized by JavaScript, go to our complete Event reference. • onLoad and onUnload • The onLoad and onUnload events are triggered when the user enters or leaves the page. • The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. • Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!". • onFocus, onBlur and onChange
  • 352. Events • The onFocus,onBlurandonChangeevents are often used in combination with validation of form fields. • Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field: • <input type="text" size="30" id="email“ onchange="checkEmail()"> • onSubmit
  • 353. Events • onMouseOver and onMouseOut • onMouseOver and onMouseOut are often used to create "animated" buttons. • Below is an example of an onMouseOver event. An alert box appears when an event is detected:onMouseOver <ahref="http://www.w3schools.com"onmouseover="alert('onMouseOv erevent');return false"><img src="w3s.gif" alt="W3Schools" /></a> Example:<A HREF="jmouse.htm" onMouseover="window.status='Hi there!'; return true" onMouseout="window.status=' '; return true">Place your mouse here!</A>
  • 355. example <html> <head> <title>JavascriptForm Validation</title> <script language='JavaScript' type='text/JavaScript'> <!-function validate() { if(document.form1.textinput.value=='') { alert('Fill the Input box before submitting'); return false; } else{ return true; } } //--> </script> </head> <body> <form name='form1' action='javascript_validation.php‘ method='post' onSubmit='return validate();'> Input :<input type=text name=textinput value=''> <input type=submit value=submit> </form> </body> </html>
  • 356. Form data that typically are checked by a JavaScript could be:  Required fields  Valid user name  Valid password  Valid e-mail address  Valid phone number
  • 357. Regular Expression •The RegExpobject is used to specify what to search for in a text •RegExp, is short for regular expression. •When you search in a text, you can use a pattern to describe what you are searching for.RegExpIS this pattern. A simple pattern can be a single character. •A more complicated pattern consists of more characters, and can be used for parsing, format checking, substitution and more. •Methods of the RegExpObject •The RegExpObject has 3 methods: test(), exec(), and compile(). •test() •The test() method searches a string for a specified value. Returns true or false •Example: •varpatt1=newRegExp("e"); document.write(patt1.test("The best things in life are free"));
  • 358. Validate FormOnSubmit( ) •This is a main function that calls a series of subfunctions, each of which checks a single form element for compliance. If the element complies than subfunction returns an empty string. Otherwise it returns a message describing the error and highlight appropriate element with yellow. Function validateFormOnSubmit(theForm) { varreason = ""; reason +=validateUsername(theForm.username); reason +=validatePassword(theForm.pwd); reason +=validatePhone(theForm.phone); if (reason != "") { alert("Some fields need correction:n" + reason); return false; } return true; }
  • 359. validateEmpty( ) •The function below checks if a required field has been left empty. If the required field is blank, we return the error string to the main function. If it’s not blank, the function returns an empty string. Function validateEmpty(fld){ var error = ""; if (fld.value.length == 0) { error = "The required field has not been filled in.n" } return error; }
  • 360. ValidateUsername( ) • The function below checks if the user entered anything at all in the username field. If it’s not blank, we check the length of the string and permit only usernames that are between5 and 15 characters. Next, we use the JavaScript regular expression /W/ to forbid illegal characters from appearing in usernames. We want to allow only letters, numbers and underscores. functionvalidateUsername(fld){ Var error = ""; var illegalChars= /W/; // allow letters, numbers, and underscores if (fld.value == "") { error = "You didn't enter a username.n"; } else if ((fld.value.length < 5) || (fld.value.length > 15)) { error = "The username is the wrong length.n"; } else if (illegalChars.test(fld.value)) { error = "The username contains illegal characters.n"; } else { } return error; }
  • 361. validatePassword( ) •The function below checks the password field for blankness and allow only letters and numbers – no underscopes this time. So we should use a new regular expression to forbid underscopes. This one /[W_]/ allow only letters and numbers. Next, we want to permit only passwords that contain letters and at least one numeral. For that we use the search() method and two more regular expressions: /(a-z)+/ and /(0-9)/. functionvalidatePassword(fld){ varerror = ""; var illegalChars= /[W_]/; // allow only letters and numbers if (fld.value == "") { error = "You didn't enter a password.n"; } else if ((fld.value.length < 7) || (fld.value.length > 15)) { error = "The password is the wrong length. n"; } else if (illegalChars.test(fld.value)) { error = "The password contains illegal characters.n"; } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) { error = "The password must contain at least one numeral.n"; } else { } return error; }
  • 363.  JavaScript Form Submit Example The code: <form name="myform" action="handle-data.php"> Search: <input type='text' name='query'> <A href="javascript: submitform()">Search</A> </form> <SCRIPT language="JavaScript"> function submitform() { document.myform.submit(); } </SCRIPT>
  • 364. <html> <head> <title>JavascriptForm Validation</title> <script language='JavaScript' type='text/JavaScript'> <!-function validate() { if(document.form1.textinput.value=='') { alert('Fill the Input box before submitting'); return false; } else{ return true; } } //--> </script> </head> <body> <form name='form1' action='javascript_validation.php‘ method='post' onSubmit='return validate();'> Input :<input type=text name=textinput value=''> <input type=submit value=submit> </form> </body>
  • 365. <form name="demo“ onsubmit="returnvalidateFormOnSubmit(this)" action="test.htm"> <table summary="Demonstration form"> <tbody> <tr> <td><label for="username">Your user name:</label></td> <td><input name="username" size="35"maxlength="50" type="text"></td> </tr> <tr> <td><label for="pwd">Your password</label></td> <td><input name="pwd" size="35"maxlength="25" type="password"></td> </tr> <tr> <td><label for="email">Your email:</label></td> <td><input name="email" size="35"maxlength="30" type="text"></td> </tr> <tr> <td><label for="phone">Your telephone number:</label></td> <td><input name="phone" size="35"maxlength="25" type="text"></td> </tr> <tr> <td> <label for="from">Where are you :</label></td> <td><input name="from" size="35"maxlength="50" type="text"></td> </tr> <tr> <td>&nbsp;</td> <td><input name="Submit" value="Send" type="submit" ></td> <td>&nbsp;</td> </tr> </tbody> </table> </form>
  • 373. Ajax (programming)  Ajax (shorthand for asynchronous JavaScript + XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages and better quality of Web services due to the asynchronous mode. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.  XMLHttpRequest (XHR) is a DOM API that can be used inside a web browser scripting language, such as JavaScript, to send an HTTP or an HTTPS request directly to a web server and load the server response data directly back into the scripting language.[1] Once the data is within the scripting language, it is available as both an XML document, if the response was valid XML markup, and as plain text. The XML data can be used to manipulate the currently active document in the browser window without the need of the client loading a new web page document. Plain text data can be evaluated within the scripting language to manipulate the document, too; in the example of JavaScript, the plain text may be formatted as JSON by the web server and evaluated within JavaScript to create an object of data for use on the current DOM.  XMLHttpRequest has an important role in the AJAX web development technique. It is currently used by many websites to implement responsive and dynamic web applications. Examples of these web applications include Gmail, Google Maps, Bing Maps, the MapQuest dynamic map interface, Facebook, and others.
  • 374. PHP And AJAX AJAX = Asynchronous JavaScript And XML •AJAX is an acronym for Asynchronous JavaScript And XML. •AJAX is not a new programming language, but simply a new technique for creating better, faster, and more interactive web applications. •AJAX uses JavaScript to send and receive data between a web browser and a web server. •The AJAX technique makes web pages more responsive by exchanging data with the web server behind the scenes, instead of reloading an entire web page each time a user makes a change. AJAX Is Based On Open Standards •AJAX is based on the following open standards: •JavaScript •XML •HTML •CSS • The open standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent. (Cross-Platform, Cross-Browser technology)
  • 375. PHP And AJAX AJAX Is About Better Internet Applications •Web applications have many benefits over desktop applications: •they can reach a larger audience •they are easier to install and support •they are easier to develop •However, Internet applications are not always as "rich" and userfriendly as traditional desktop applications. •With AJAX, Internet applications can be made richer (smaller, faster, and easier to use). You Can Start Using AJAX Today •There is nothing new to learn. •AJAX is based on open standards. These standards have been used by most developers for several years. •Most existing web applications can be rewritten to use AJAX technology instead of traditional HTML forms.
  • 376. PHP And AJAX AJAX Uses XML And HTTP Requests  A traditional web application will submit input (using an HTML form) to a web server. After the web server has processed the data, it will return a completely new web page to the user.  Because the server returns a new web page each time the user submits input, traditional web applications often run slowly and tend to be less user friendly.  With AJAX, web applications can send and retrieve data without reloading the whole web page. This is done by sending HTTP requests to the server (behind the scenes), and by modifying only parts of the web page using JavaScript when the server returns data.  XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.
  • 377. PHP And AJAX PHP and AJAX •There is no such thing as an AJAX server. •AJAX is a technology that runs in your browser. It uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. •AJAX is a web browser technology independent of web server software. •However, in this tutorial we will focus more on actual examples running on a PHP server, and less on how AJAX works.
  • 378. AJAX XMLHttpRequest • The XMLHttpRequestobject makes AJAX possible. The XMLHttpRequest •The XMLHttpRequestobject is the key to AJAX. •It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005. Creating An XMLHttpRequestObject •Different browsers use different methods to create an XMLHttpRequest object. •Internet Explorer uses an ActiveXObject. •Other browsers uses a built in JavaScript object called XMLHttpRequest. •Here is the simplest code you can use to overcome this problem:
  • 379. AJAX XMLHttpRequest • First create a variable XMLHttpto use as your XMLHttpRequestobject. Set the value to null. • Then test if the object window.XMLHttpRequestis available. This object is available in newer versions ofFirefox,Mozilla, Opera, and Safari. • If it's available, use it to create a new object:XMLHttp=newXMLHttpRequest() • If it's not available, test if an object window.ActiveXObjectis available. This object is available in Internet Explorer version 5.5 and later. • If it is available, use it to create a new object:XMLHttp=newActiveXObject()
  • 380. function disp_state() { var xmlhtp=null; try { xmlhtp = new XMLHttpRequest(); alert("You are using mozilla"); } catch(e) { try { xmlhtp = new ActiveXObject("Microsoft.XMLHTTP"); alert("You are using IE"); } catch(e) { try { xmlhtp=new ActiveXObject("Msxml2.XMLHTTP"); alert("You are using IE"); } catch(e) { alert("Your Browser Does Not Support Javascript"); } } } cat=document.getElementById('txtb_userid').value; xmlhtp.open("GET","get_state.php?cate="+cat,true); xmlhtp.send(null); xmlhtp.onreadystatechange=function() { if(xmlhtp.readyState==4) { document.getElementById('div_state').innerHTML=xmlhtp.responseText; // document.getElementById('div_product_photo_upload').innerHTML="<input type='file' name='f1' id='f1' onchange='show_image()' />"; } } }
  • 381.  AJAX - More about the XMLHttpRequest object  Before sending data off to a server, we will look at three important properties of the XMLHttpRequest object.  The onreadystatechange property  After a request to a server, we need a function to receive the data returned from the server.  The onreadystatechange property stores the function that will process the response from a server. The function is stored in the property to be called automatically.  The following code sets the onreadystatechange property and stores an empty function inside it:
  • 383. PHP And AJAX Suggest AJAX Suggest •In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a web form. Type a Name in the Box Below Suggestions: This example consists of three pages: •a simple HTML form •a JavaScript •a PHP page
  • 384. PHP And AJAX Suggest The HTML Form •This is the HTML page. It contains a simple HTML form and a linkto a JavaScript: •HTML Form <html> <head> <scriptsrc="clienthint.js"></script> </head> <body> <form> First Name: <input type="text" id="txt1"onkeyup="showHint(this.value)"> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html>
  • 385. var xmlHttp function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML="" return } xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return } var url="gethint.php" url=url+"?q="+str url=url+"&sid="+Math.random() xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true) xmlHttp.send(null) }
  • 386. function stateChanged() { if (xmlHttp.readyState==4 ||xmlHttp.readyState=="complete") { document.getElementById("txtHint").innerHTML=xmlHttp.responseText } } functionGetXmlHttpObject() { var xmlHttp=null; try { //Firefox, Opera 8.0+, Safari xmlHttp=newXMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=newActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=newActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
  • 387. <?php // Fill up array with names $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty"; $a[]="Linda"; $a[]="Nina"; $a[]="Ophelia"; $a[]="Petunia"; $a[]="Amanda"; $a[]="Raquel"; $a[]="Cindy"; $a[]="Doris"; $a[]="Eve"; $a[]="Evita"; $a[]="Sunniva"; $a[]="Tove"; $a[]="Unni"; $a[]="Violet"; $a[]="Liza"; $a[]="Elizabeth"; $a[]="Ellen"; $a[]="Wenche"; $a[]="Vicky"; //get the q parameter from URL $q=$_GET["q"];
  • 388. //lookup all hints from array if length of q>0 if (strlen($q) > 0) { $hint=""; for($i=0; $i<count($a); $i++) { if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) { if ($hint=="") { $hint=$a[$i]; } else { $hint=$hint." , ".$a[$i]; } } } } //Set output to "no suggestion" if no hint were found //or to the correct values if ($hint == "") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response; ?>
  • 391. Class Every class definition begins with the keyword class, followed by a class name, which can be any name that isn't a reserved word in PHP. Followed by a pair of curly braces, which contains the definition of the classes members and methods. A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object). This is illustrated in the following examples
  • 392. Example 19.2. Simple Class definition <?php class SimpleClass { // member declaration public $var = 'a default value'; // method declaration public function displayVar() { echo $this->var; } }
  • 393. <?php class A { function foo() { if (isset($this)) { echo '$this is defined ('; echo get_class($this); echo ")n"; } else { echo "$this is not defined.n"; } } } class B { function bar() { A::foo(); } } $a = new A(); $a->foo(); A::foo(); $b = new B(); $b->bar(); B::bar(); ?> //The above example will output: $this is defined (a) $this is not defined. $this is defined (b) $this is not defined.
  • 394. Example 19.5. Object Assignment <?php $instance->var = '$assigned will have this value'; $assigned = $instance; $reference =& $instance; $instance = null; // $instance and $reference become null var_dump($instance); var_dump($reference); var_dump($assigned); ?> The above example will output: NULL NULL object(SimpleClass)#1 (1) { ["var"]=> string(30) "$assigned will have this value“ }
  • 395. Extends A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class. The inherited methods and members can be overridden, unless the parent class has defined a method as final by redeclaring them with the same name defined in the parent class. It is possible to access the overridden methods or static members by referencing them with parent:: .
  • 396. Visibility The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public Declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item. Members Visibility Class members must be defined with public, private, or protected.
  • 397.  Member Variable declaration (Example of extends) <?php /** * Define MyClass */ class MyClass { public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } $obj = new MyClass(); echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private
  • 398.  Member function declaration (Example of extends) <?php /** * Define MyClass */ class MyClass { // Contructors must be public public function __construct() { } // Declare a public method public function MyPublic() { } // Declare a protected method protected function MyProtected() { } // Declare a private method private function MyPrivate() { } // This is public function Foo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); } }
  • 399. $myclass = new MyClass; $myclass->MyPublic(); // Works $myclass->MyProtected(); // Fatal Error $myclass->MyPrivate(); // Fatal Error $myclass->Foo(); // Public, Protected and Private work
  • 400.  access parent class methods class MyClass2 extends MyClass { // This is public function Foo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); // Fatal Error } } $myclass2 = new MyClass2; $myclass2->MyPublic(); // Works $myclass2->Foo2(); // Public and Protected work, not Private
  • 401.  Example of extends class Bar { public function test() { $this->testPrivate(); $this->testPublic(); } public function testPublic() { echo "Bar::testPublicn"; } private function testPrivate() { echo "Bar::testPrivaten"; } }
  • 402. class Foo extends Bar { public function testPublic() { echo "Foo::testPublicn"; } private function testPrivate() { echo "Foo::testPrivaten"; } } $myFoo = new foo(); $myFoo->test(); //Output…………… Bar::testPrivate Foo::testPublic
  • 403. Constructor void __construct ( [mixed $args [, $...]] ) PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
  • 404. Example 19.8. using new unified constructors <?php class BaseClass { function __construct() { print "In BaseClass constructorn"; } } class SubClass extends BaseClass { function __construct() { parent::__construct(); print "In SubClass constructorn"; } } $obj = new BaseClass(); $obj = new SubClass(); ?>
  • 405. For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Destructor void __destruct( void ) PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.
  • 406. <?php class MyDestructableClass { function __construct() { print "In constructorn"; $this->name = "MyDestructableClass"; } function __destruct() { print "Destroying " . $this->name . "n"; } } $obj = new MyDestructableClass(); ?>
  • 407. Scope Resolution Operator (::) The Scope Resolution Operator (also called Paamayim Nekudotayim)or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden members or methods of a class. When referencing these items from outside the class definition, use the name of the class. Example : from outside the class definition <?php Class MyClass { const CONST_VALUE = 'A constant value'; } echo MyClass:: CONST_VALUE; ?>
  • 408. Example : from inside the class definition <?php class OtherClass extends MyClass { public static $my_static = 'static var'; public static function doubleColon() { echo parent::CONST_VALUE . "n"; echo self::$my_static . "n"; } } $classname = 'OtherClass'; echo $classname::doubleColon(); OtherClass::doubleColon(); ?>
  • 409. When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading,and Magic method definitions. class MyClass { protected function myFunc() { echo "MyClass::myFunc()n"; } } class OtherClass extends MyClass { // Override parent's definition public function myFunc() { // But still call the parent function parent::myFunc(); echo "OtherClass::myFunc()n"; } } $class = new OtherClass(); $class->myFunc();
  • 410. Static Keyword Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can). For compatibility with PHP 4, if no as if it was declared as public. visibility declaration is used, then the member or method will be treated Because static methods are callable without an instance of the object created, the pseudo variable not available inside the method declared as static. Static properties cannot be accessed through the object using the arrow operator ->.
  • 411. class Foo { public static $my_static = 'foo'; public function staticValue() { return self::$my_static; } } class Bar extends Foo { public function fooStatic() { return parent::$my_static; } } print Foo::$my_static . "n"; $foo = new Foo(); print $foo->staticValue() . "n"; print $foo->my_static . "n"; // Undefined "Property" my_static print Bar::$my_static . "n"; $bar = new Bar(); print $bar->fooStatic() . "n";
  • 412. Class Constants It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. Class Abstraction PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.
  • 413. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility . For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Example 19.18. Abstract class example <?php abstract class AbstractClass { // Force Extending class to define this method abstract protected function getValue(); abstract protected function prefixValue($prefix); // Common method public function printOut() { print $this->getValue() . "n"; } }
  • 414. class ConcreteClass1 extends AbstractClass { protected function getValue() { return "ConcreteClass1"; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass1"; } } class ConcreteClass2 extends AbstractClass { public function getValue() { return "ConcreteClass2"; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass2"; } }
  • 415. $class1 = new ConcreteClass1; $class1->printOut(); echo $class1->prefixValue('FOO_') ."n"; $class2 = new ConcreteClass2; $class2->printOut(); echo $class2->prefixValue('FOO_') ."n"; ?> The above example will output: ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2
  • 416. Object Interfaces Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled. Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined. All methods declared in an interface must be public, this is the nature of an interface. Implements To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma. Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity.
  • 417. // Declare the interface 'iTemplate' interface iTemplate { public function setVariable($name, $var); public function getHtml($template); } // Implement the interface // This will work class Template implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } public function getHtml($template) { foreach($this->vars as $name => $value) { $template = str_replace('{' . $name . '}', $value, $template); } return $template; } }
  • 418. // This will not work // Fatal error: Class BadTemplate contains 1 abstract methods // and must therefore be declared abstract (iTemplate::getHtml) class BadTemplate implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } }
  • 419. Overloading Both method calls and member accesses can be overloaded via the __call, __get and __set methods. These methods will only be triggered when your object or inherited object doesn't contain the member or method you're trying to access. All overloading methods must not be defined as static. All overloading methods must be defined as public.  Member overloading void __set ( string $name, mixed $value ) mixed __get ( string $name ) Class members can be overloaded to run custom code defined in your class by defining these specially named methods. The __set() method's $name $value parameter used is the name of the variable that should be set or retrieved. parameter specifies the value that the object should set the $name. Note: The __set() method cannot take arguments by reference.
  • 420. <?php class myclass { function __set($data,$value) { echo "__set is called<br>"; echo "Variable= ".$data." "; echo "Value= ".$value; } } $myclassobj = new myclass(); $myclassobj->x=30; class myget { function __get($data) { //note: variable 'x' is not defined in myclass $data = "<br>__get is called<br>undefined attributes "; return $data; } }
  • 421. $mygetobj = new myget(); echo $mygetobj->getdata; //note: variable 'getdata' is not defined in myclass
  • 422.  Method overloading mixed __call ( string $name, array $arguments ) The magic method __call() allows to capture invocation of non existing methods. That way __call() can be used to implement user defined method handling that depends on the name of the actual method being called. This is for instance useful for proxy implementations. The arguments that were passed in the function will be defined as an array in the $arguments parameter. The value returned from the __call() method will be returned to the caller of the method.
  • 423. Example 19.21. overloading with __call example The above example will output: <?php class Caller { Private $x = array(1 , 2 ,3 ); public function __call ($m , { print "Method $m called:n" var_dump ($a ); return $this -> x ; } } $foo = new Caller (); $a = $foo -> test (1 , "2", var_dump ($a ); ?> $a ) ; 3.4 , true );
  • 424. Method test called(output): array(4) { [0]=> int(1) [1]=> string(1) "2" [2]=> float(3.4) [3]=> bool(true) } array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
  • 425. Autoloading Objects Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class). <?php function __autoload($class_name) { require_once $class_name . '.php'; } $obj = new MyClass1(); $obj2 = new MyClass2(); ?>
  • 426. Object Iteration PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for Example a foreach statement. By default, all visible properties will be used for the iteration. Example 19.22. Simple Object Iteration class MyClass { public $var1 = 'value 1'; public $var2 = 'value 2'; public $var3 = 'value 3'; protected $protected = 'protected var'; private $private = 'private var'; function iterateVisible() { echo "MyClass::iterateVisible:n"; foreach($this as $key => $value) { print "$key => $valuen"; } } }
  • 427. $class = new MyClass(); foreach($class as $key => $value) { print "$key => $valuen"; } echo "n"; $class->iterateVisible(); ?> The above example will output: var1 => value 1 var2 => value 2 var3 => value 3 MyClass::iterateVisible: var1 => value 1 var2 => value 2 var3 => value 3 protected => protected var private => private var
  • 428. Final Keyword PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. Example 19.29. Final methods example <?php class BaseClass { public function test() { echo "BaseClass::test() calledn"; } final public function moreTesting() { echo "BaseClass::moreTesting() calledn"; } } class ChildClass extends BaseClass { public function moreTesting() { echo "ChildClass::moreTesting() calledn"; } }
  • 429. Example Final class example <?php final class BaseClass { public function test() { echo "BaseClass::test() calledn"; } // Here it doesn't matter if you specify the function as final or not final public function moreTesting() { echo "BaseClass::moreTesting() calledn"; } } class ChildClass extends BaseClass { } // Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass) ?>
  • 430. Type Hinting PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). Example 19.41. Type Hinting examples <?php // An example class class MyClass { /* A test function First parameter must be an object of type OtherClass */ public function test(OtherClass $otherclass) { echo $otherclass->var; }
  • 431. /* Another test function First parameter must be an array */ public function test_array(array $input_array) { print_r($input_array); } } // Another example class class OtherClass { public $var = 'Hel o World'; } ?> Failing to satisfy the type hint results in a catchable fatal error. <?php // An instance of each class $myclass = new MyClass; $otherclass = new OtherClass;
  • 432. // Fatal Error: Argument 1 must be an object of class OtherClass $myclass->test('hello'); // Fatal Error: Argument 1 must be an instance of OtherClass $foo = new stdClass; $myclass->test($foo); // Fatal Error: Argument 1 must not be null $myclass->test(null); // Works: Prints Hello World $myclass->test($otherclass); // Fatal Error: Argument 1 must be an array $myclass->test_array('a string'); // Works: Prints the array $myclass->test_array(array('a', 'b', 'c')); ?>
  • 433. Overview of MVC Architecture
  • 434. Understanding MVC  MVC stands for Model-View-Controller. • It is a type of architecture for developing software, recently pretty popular in web applications development. • Model is what interacts with the database, it would be the backend class code for an object-oriented language like PHP, Ruby on Rails, or C++. • View is basically the user interface. • Controller is the logic that operates everything in between
  • 436. Model The MVC structure is meant for reasonably-sized applications, using object-oriented coding. The Model part, in a PHP app, would usually be a class (or multiple classes). Fairly often, the class is a representation of a table you store in the database — member variables are the data columns, and member methods are operations that can be done. As an example, you might have a User class, having variables such as username, password, email address, and other things. Some of its methods might be a new user creation function, a login function, an authentication function, and a logout function.
  • 437. Model (Example of creating Model Code) class User { var $username; var $password; var $email; function User($u, $p, $e) // constructor { $this->username = $u; $this->password = $p; $this->email = $e; } function create() { // creates user in the db } function login() { // checks against db, does login procedures } static function authenticate($u, $p) { // checks against db } function logout() { // does logout procedures } }
  • 438. The View, in the simplest words, is the user interface. <?php require_once('User.php'); // makes sure user isn't already logged in if (User::authenticate($_COOKIE['username'], $_COOKIE['password'])) { header(”Location:/main.php”); exit(); } ?> <html> <head><title>Please login</title></head> <body> <h1>Login</h1> <? if ($_GET['error'] == 1) { echo ‘Login incorrect. Please try again.<br />’; } ?> <form action=”login_action.php” method=”post”> User: <input type=”text” name=”username” /><br /> Pass: <input type=”password” name=”password” /><br /> <input type=”submit” value=”Login” /> </form> </body> </html>
  • 439. Controller <?php require_once('User.php'); // in reality, a lot more error checking needs to be done. $currentuser = new User($_POST['username'], $_POST['password'], ”); if ($currentuser->login()) { // set cookies for login info header(”Location:/main.php”); exit(); } else { header(”Location:/login.php?error=1 ″); exit(); } ?>