pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP...

49
PHP PHP is a open source, interpreted and object-oriented scripting language i.e. executed at server side. It is used to develop web applications (an application i.e. executed at server side and generates dynamic page). PHP is a server side scripting language. PHP is an interpreted language, i.e. there is no need for compilation. PHP is an object-oriented language. PHP is an open-source scripting language. PHP is simple and easy to learn language. PHP Features There are given many features of PHP. Performance: Script written in PHP executes much faster then those scripts written in other languages such as JSP & ASP. Open Source Software: PHP source code is free available on the web, you can developed all the version of PHP according to your requirement without paying any cost. Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application developed in one OS can be easily executed in other OS also. Compatibility: PHP is compatible with almost all local servers used today like Apache, IIS etc. Embedded: PHP code can be easily embedded within HTML tags and script. PHP Example create a file and write HTML tags + PHP code and save this file with .php extension. All PHP code goes between php tag. A syntax of PHP tag is given below:

Transcript of pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP...

Page 1: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

PHP

PHP is a open source, interpreted and object-oriented scripting language i.e. executed at server side. It is used to develop web applications (an application i.e. executed at server side and generates dynamic page).

PHP is a server side scripting language. PHP is an interpreted language, i.e. there is no need for compilation. PHP is an object-oriented language. PHP is an open-source scripting language. PHP is simple and easy to learn language.

PHP Features

There are given many features of PHP.

Performance: Script written in PHP executes much faster then those scripts written in other languages such as JSP & ASP.

Open Source Software: PHP source code is free available on the web, you can developed all the version of PHP according to your requirement without paying any cost.

Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application developed in one OS can be easily executed in other OS also.

Compatibility: PHP is compatible with almost all local servers used today like Apache, IIS etc.

Embedded: PHP code can be easily embedded within HTML tags and script.

PHP Example

create a file and write HTML tags + PHP code and save this file with .php extension.

All PHP code goes between php tag. A syntax of PHP tag is given below:

<?php   

//your code here  

?>  

<html>   <body>   <?php  

Page 2: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

echo "<h2>Hello First PHP</h2>";   ?>  </body>  </html> 

PHP Echo

PHP echo is a language construct not a function, so you don't need to use parenthesis with it.

<?php  

echo "Hello by PHP echo";  

?>  

 PHP echo: printing multi line string

File: echo2.php

<?php  

echo "Hello by PHP echo  

this is multi line  

text printed by   

PHP echo statement  

";  

?>  

PHP echo: printing escaping characters

File: echo3.php

<?php  

echo "Hello escape \"sequence\" characters";  

?>  

PHP echo: printing variable value

Page 3: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

File: echo4.php

<?php  

$msg="Hello JavaTpoint PHP";  

echo "Message is: $msg";    

?>  

PHP Print

Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the argument list.

PHP print: printing string

File: print1.php

<?php  

print "Hello by PHP print ";  

?> 

PHP Variables

A variable in PHP is a name of memory location that holds data. A variable is a temporary storage that is used to store data temporarily.

In PHP, a variable is declared using $ sign followed by variable name.

Syntax of declaring a variable in PHP is given below:

$variablename=value;

PHP Variable: Declaring string, integer and float

Let's see the example to store string, integer and float values in PHP variables.

File: variable1.php

<?php  

Page 4: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

$str="hello string";  

$x=200;  

$y=44.6;  

echo "string is: $str <br/>";  

echo "integer is: $x <br/>";  

echo "float is: $y <br/>";  

?>  

PHP Variable: Sum of two variables

File: variable2.php

<?php  

$x=5;  

$y=6;  

$z=$x+$y;  

echo $z;  

?>  

PHP Variable: case sensitive

In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR, COLor etc.

File: variable3.php

<?php  

$color="red";  

echo "My car is " . $color . "<br>";  

echo "My house is " . $COLOR . "<br>";  

echo "My boat is " . $coLOR . "<br>";  

Page 5: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

?> 

PHP Variable: Rules

PHP variables must start with letter or underscore only.

PHP variable can't be start with numbers and special symbols.

File: variablevalid.php

<?php  

$a="hello";//letter (valid)  

$_b="hello";//underscore (valid)  

echo "$a <br/> $_b";  

?>  

PHP: Loosely typed language

PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type.

PHP Constants

PHP constants are name or identifier that can't be changed during the execution of the script. PHP constants can be defined by 2 ways:

1. Using define() function2. Using const keyword

PHP constants follow the same PHP variable rules. For example, it can be started with letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()

Let's see the syntax of define() function in PHP.

define(name, value, case-insensitive)

1. name: specifies the constant name

Page 6: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

2. value: specifies the constant value3. case-insensitive: Default value is false. It means it is case sensitive by default.

Let's see the example to define PHP constant using define().

File: constant1.php

<?php  

define("MESSAGE","Hello  PHP");  

echo MESSAGE;  

?>  

File: constant2.php

<?php  

define("MESSAGE","Hello  PHP",true);//not case sensitive  

echo MESSAGE;  

echo message;  

?>  

File: constant3.php

<?php  

define("MESSAGE","Hello  PHP",false);//case sensitive  

echo MESSAGE;  

echo message;  

?>

PHP constant: const keyword

The const keyword defines constants at compile time. It is a language construct not a function.

It is bit faster than define().

Page 7: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

It is always case sensitive.

File: constant4.php

<?php  

const MESSAGE="Hello const by  PHP";  

echo MESSAGE;  

?>  

PHP Data Types

PHP data types are used to hold different types of data or values. PHP supports 6 primitive data types that can be categorized further in 2 types:

1. Scalar Types2. Compound Types

PHP Data Types: Scalar Types

There are 4 scalar data types in PHP.

1. boolean2. integer3. float4. string

PHP Data Types: Compound Types

There are 2 compound data types in PHP.

1. array2. object

PHP Operators

PHP Operator is a symbol i.e used to perform operations on operands.

Page 8: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

PHP Comments

PHP comments can be used to describe any line of code so that other developer can understand the code easily. It can also be used to hide any code.

PHP supports single line and multi line comments. These comments are similar to C/C++

Control Statement

PHP If Statement

PHP if statement is executed if condition is true.

Syntax

if(condition){  

//code to be executed  

}  

Example

<?php  

$num=12;  

if($num<100){  

echo "$num is less than 100";  

}  

?>  

PHP If-else Statement

PHP if-else statement is executed whether condition is true or false.

Syntax

if(condition){  

//code to be executed if true  

Page 9: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

}else{  

//code to be executed if false  

}  

Example

<?php  

$num=12;  

if($num%2==0){  

echo "$num is even number";  

}else{  

echo "$num is odd number";  

}  

?>  

php if else if statement

<?phpif ($a > $b) {    echo "a is bigger than b";} elseif ($a == $b) {    echo "a is equal to b";} else {    echo "a is smaller than b";}?>

PHP Switch

PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.

Syntax

switch(expression){      

case value1:      

Page 10: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

 //code to be executed  

 break;  

case value2:      

 //code to be executed  

 break;  

......      

default:       

 code to be executed if all cases are not matched;    

}  

PHP Switch Example

<?php    

$num=20;    

switch($num){    

case 10:    

echo("number is equals to 10");    

break;    

case 20:    

echo("number is equal to 20");    

break;    

case 30:    

echo("number is equal to 30");    

break;    

default:    

Page 11: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

echo("number is not equal to 10, 20 or 30");    

}   

?>

PHP For Loop

PHP for loop can be used to traverse set of code for the specified number of times.

Syntax

for(initialization; condition; increment/decrement){  

//code to be executed  

}  

Example

<?php  

for($n=1;$n<=10;$n++){  

echo "$n<br/>";  

}  

?>

PHP Nested For Loop

We can use for loop inside for loop in PHP, it is known as nested for loop.

In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).

Example

<?php  

for($i=1;$i<=3;$i++){  

Page 12: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

for($j=1;$j<=3;$j++){  

echo "$i   $j<br/>";  

}  

}  

?>  

PHP For Each Loop

PHP for each loop is used to traverse array elements.

Syntax

foreach( $array as $var ){  

 //code to be executed  

}  

?>  

Example

<?php  

$season=array("summer","winter","spring","autumn");  

foreach( $season as $arr ){  

  echo "Season is: $arr<br />";  

}  

?>  

PHP While Loop

PHP while loop can be used to traverse set of code like for loop.

It should be used if number of iteration is not known.

Syntax

Page 13: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

while(condition){

//code to be executed

}

PHP While Loop Example

<?php  

$n=1;  

while($n<=10){  

echo "$n<br/>";  

$n++;  

}  

?>  

PHP Nested While Loop

We can use while loop inside another while loop in PHP, it is known as nested while loop.

In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer while loop is to be executed for 3 times and nested while loop for 3 times, nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).

Example

<?php  

$i=1;  

while($i<=3){  

$j=1;  

while($j<=3){  

echo "$i   $j<br/>";  

$j++;  

Page 14: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

}  

$i++;  

}  

?>  

PHP do while loop

PHP do while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at least once.

It executes the code at least one time always because condition is checked after executing the code.

Syntax

do{

//code to be executed

}while(condition);

Example

<?php  

$n=1;  

do{  

echo "$n<br/>";  

$n++;  

}while($n<=10);  

?>  

PHP Functions

PHP function is a piece of code that can be reused many times. It can take input as argument list and return value. There are thousands of built-in functions in PHP.

Page 15: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times, like in other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of function, you can write the logic only once and reuse it.

Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of the application because every logic is divided in the form of functions.

PHP User-defined Functions

We can declare and call user-defined functions easily. Let's see the syntax to declare user-defined functions.

Syntax

function functionname(){  

//code to be executed  

}  

PHP Functions Example

File: function1.php

<?php  

function sayHello(){  

echo "Hello PHP Function";  

}  

sayHello();//calling function  

?>  

PHP Function Arguments

We can pass the information in PHP function through arguments which is separated by comma.

Let's see the example to pass single argument in PHP function.

Page 16: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

File: functionarg.php

<?php  

function sayHello($name){  

echo "Hello $name<br/>";  

}  

sayHello("Sonoo");  

sayHello("Vimal");  

sayHello("John");  

?>  

Let's see the example to pass two argument in PHP function.

File: functionarg2.php

<?php  

function sayHello($name,$age){  

echo "Hello $name, you are $age years old<br/>";  

}  

sayHello("Sonoo",27);  

sayHello("Vimal",29);  

sayHello("John",23);  

?>  

PHP Function: Default Argument Value

We can specify a default argument value in function. While calling PHP function if you don't specify any argument, it will take the default argument. Let's see a simple example of using default argument value in PHP function.

File: functiondefaultarg.php

Page 17: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

<?php  

function sayHello($name="Sonoo"){  

echo "Hello $name<br/>";  

}  

sayHello("Rajesh");  

sayHello();//passing no value  

sayHello("John");  

?> 

PHP Function: Returning Value

Let's see an example of PHP function that returns value.

File: functiondefaultarg.php

<?php  

function cube($n){  

return $n*$n*$n;  

}  

echo "Cube of 3 is: ".cube(3);  

?>  

PHP Parameterized Function

PHP Parameterized functions are the functions with parameters. You can pass any number of parameters inside a function. These passed parameters act as variables inside your function.

They are specified inside the parentheses, after the function name.

The output depends upon the dynamic values passed as the parameters into the function.

PHP Parameterized Example

Page 18: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

Addition and Subtraction

In this example, we have passed two parameters $x and $y inside two functions add() and sub().

<html>

<head>

<title>Parameter Addition and Subtraction Example</title>

</head>

<body>

<?php

//Adding two numbers

function add($x, $y) {

$sum = $x + $y;

echo "Sum of two numbers is = $sum <br><br>";

}

add(467, 943);

//Subtracting two numbers

function sub($x, $y) {

$diff = $x - $y;

echo "Difference between two numbers is = $diff";

}

sub(943, 467);

?>

</body>

</html>

Page 19: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

PHP Arrays

PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable.

PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

$season=array("summer","winter","spring","autumn");  

2nd way:

$season[0]="summer";  

$season[1]="winter";  

$season[2]="spring";  

$season[3]="autumn";  

Example

File: array1.php

<?php  

$season=array("summer","winter","spring","autumn");  

echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  

?>

File: array2.php

<?php  

$season[0]="summer";  

$season[1]="winter";  

Page 20: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

$season[2]="spring";  

$season[3]="autumn";  

echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  

?>

PHP Associative Array

We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");  

2nd way:

$salary["Sonoo"]="350000";  

$salary["John"]="450000";  

$salary["Kartik"]="200000";  

Example

File: arrayassociative1.php

<?php    

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");    

echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  

echo "John salary: ".$salary["John"]."<br/>";  

echo "Kartik salary: ".$salary["Kartik"]."<br/>";  

?>    

File: arrayassociative2.php

<?php    

Page 21: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

$salary["Sonoo"]="350000";    

$salary["John"]="450000";    

$salary["Kartik"]="200000";    

echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  

echo "John salary: ".$salary["John"]."<br/>";  

echo "Kartik salary: ".$salary["Kartik"]."<br/>";  

?>    

PHP String

A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 2 ways to specify string in PHP.

single quoted double quoted

Single Quoted PHP String

We can create a string in PHP by enclosing text in a single quote. It is the easiest way to specify string in PHP.

<?php  

$str='Hello text within single quote';  

echo $str;  

?>  

We can store multiple line text, special characters and escape sequences in a single quoted PHP string.

<?php  

$str1='Hello text   

multiple line  

text within single quoted string';  

Page 22: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

$str2='Using double "quote" directly inside single quoted string';  

$str3='Using escape sequences \n in single quoted string';  

echo "$str1 <br/> $str2 <br/> $str3";  

?>

Double Quoted PHP String

In PHP, we can specify string through enclosing text within double quote also. But escape sequences and variables will be interpreted using double quote PHP strings.

<?php  

$str="Hello text within double quote";  

echo $str;  

?>

Now, you can't use double quote directly inside double quoted string.

<?php  

$str1="Using double "quote" directly inside double quoted string";  

echo $str1;  

?> 

PHP String Functions

PHP provides various string functions to access and manipulate strings.

1) PHP strtolower() function

The strtolower() function returns string in lowercase letter.

Example

<?php  

$str="My name is KHAN";  

Page 23: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

$str=strtolower($str);  

echo $str;  

?>

2) PHP strtoupper() function

The strtoupper() function returns string in uppercase letter.

Example

<?php  

$str="My name is KHAN";  

$str=strtoupper($str);  

echo $str;  

?>  

3) PHP ucfirst() function

The ucfirst() function returns string converting first character into uppercase. It doesn't change the case of other characters.

Example

<?php  

$str="my name is KHAN";  

$str=ucfirst($str);  

echo $str;  

?> 

4) PHP lcfirst() function

The lcfirst() function returns string converting first character into lowercase. It doesn't change the case of other characters.

Example

Page 24: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

<?php  

$str="MY name IS KHAN";  

$str=lcfirst($str);  

echo $str;  

?>  

5) PHP ucwords() function

The ucwords() function returns string converting first character of each word into uppercase.

Example

<?php  

$str="my name is Sonoo jaiswal";  

$str=ucwords($str);  

echo $str;  

?>

6) PHP strrev() function

The strrev() function returns reversed string.

Example

<?php  

$str="my name is Sonoo jaiswal";  

$str=strrev($str);  

echo $str;  

?>  

7) PHP strlen() function

The strlen() function returns length of the string.

Page 25: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

Example

<?php  

$str="my name is Sonoo jaiswal";  

$str=strlen($str);  

echo $str;  

?>

PHP Math function

PHP provides many predefined math constants and functions that can be used to perform mathematical operations.

PHP Math: abs() function

The abs() function returns absolute value of given number. It returns an integer value but if you pass floating point value, it returns a float value.

Example

<?php

echo (abs(-7)."<br/>"); // 7 (integer)

echo (abs(7)."<br/>"); //7 (integer)

echo (abs(-7.2)."<br/>"); //7.2 (float/double)

?>

PHP Math: ceil() function

The ceil() function rounds fractions up.

Example

<?php  

echo (ceil(3.3)."<br/>");// 4  

echo (ceil(7.333)."<br/>");// 8  

Page 26: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

echo (ceil(-4.8)."<br/>");// -4  

?> 

PHP Math: floor() function

The floor() function rounds fractions down.

Example

<?php  

echo (floor(3.3)."<br/>");// 3  

echo (floor(7.333)."<br/>");// 7  

echo (floor(-4.8)."<br/>");// -5  

?>

PHP Math: sqrt() function

The sqrt() function returns square root of given argument.

Example

<?php  

echo (sqrt(16)."<br/>");// 4  

echo (sqrt(25)."<br/>");// 5  

echo (sqrt(7)."<br/>");// 2.6457513110646  

?>

PHP Math: decbin() function

The decbin() function converts decimal number into binary. It returns binary number as a string.

Example

<?php  

echo (decbin(2)."<br/>");// 10  

Page 27: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

echo (decbin(10)."<br/>");// 1010  

echo (decbin(22)."<br/>");// 10110  

?>  

PHP Math: dechex() function

The dechex() function converts decimal number into hexadecimal. It returns hexadecimal representation of given number as a string.

<?php  

echo (dechex(2)."<br/>");// 2  

echo (dechex(10)."<br/>");// a  

echo (dechex(22)."<br/>");// 16  

?>  

PHP Math: decoct() function

The decoct() function converts decimal number into octal. It returns octal representation of given number as a string.

Example

<?php  

echo (decoct(2)."<br/>");// 2  

echo (decoct(10)."<br/>");// 12  

echo (decoct(22)."<br/>");// 26  

?>

PHP Form Handling

We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and $_POST.

Page 28: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

The form request may be get or post. To retrieve data from get request, we need to use $_GET, for post request $_POST.

PHP Get Form

Get request is the default form request. The data passed through get request is visible on the URL browser so it is not secured. You can send limited amount of data through get request.

Let's see a simple example to receive data from get request in PHP.

File: form1.html

<form action="welcome.php" method="get">

Name: <input type="text" name="name"/>

<input type="submit" value="visit"/>

</form>

File: welcome.php

<?php

$name=$_GET["name"];//receiving name field value in $name variable

echo "Welcome, $name";

?>

PHP Post Form

Post request is widely used to submit form that have large amount of data such as file upload, image upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it is secured. You can send large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.

File: form1.html

<form action="login.php" method="post">   

<table>   

Page 29: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>  

<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>   

<tr><td colspan="2"><input type="submit" value="login"/>  </td></tr>  

</table>  

</form>   

File: login.php

<?php  

$name=$_POST["name"];//receiving name field value in $name variable  

$password=$_POST["password"];//receiving password field value in $password variable 

  echo "Welcome: $name, your password is: $password";  

?>

PHP Include File

PHP allows you to include file so that page content can be reused many times. There are two ways to include file in PHP.

1. include2. require

Advantage

Code Reusability: By the help of include and require construct, we can reuse HTML code or PHP script in many PHP scripts.

PHP include example

PHP include is used to include file on the basis of given path. You may use relative or absolute path of the file. Let's see a simple PHP include example.

File: menu.html

<a href="home.php">Home</a> |   

<a href="php.php">PHP</a> |   

Page 30: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

<a href="java.php">Java</a> |    

<a href="html.php">HTML</a>  

File: include1.php

<?php include("menu.html"); ?>  

<h1>This is Main Page</h1> 

PHP require example

PHP require is similar to include. Let's see a simple PHP require example.

File: menu.html

<a href=" http://www.facebook.com">facebook</a> |   

<a href=" http://www.google.com">google</a> |   

<a href="http://www.gmail.com">gmail</a> |    

<a href="http://www.yahoo.com">yahoo</a>  

File: require1.php

<?php require("menu.html"); ?>  

<h1>This is Main Page</h1> 

PHP include vs PHP require

If file is missing or inclusion fails, include allows the script to continue but require halts the script producing a fatal error.

PHP Cookie

PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.

Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at the server side.

Page 31: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

In short, cookie can be created, sent and received at server end. PHP Cookie must be used before <html> tag.

There are three steps involved in identifying returning users −

Server script sends a set of cookies to the browser. For example name, age, or identification number etc.

Browser stores this information on local machine for future use. When next time browser sends any request to web server then it sends those cookies

information to the server and server uses that information to identify the user.

Setting Cookies with PHP

PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.

setcookie(name, value, expire, path, domain, security);

Here is the detail of all the arguments −

Name − This sets the name of the cookie. This variable is used while accessing cookies. Value − This sets the value of the named variable and is the content that you actually

want to store. Expiry − This specify a future time in seconds. After this time cookie will become

inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.

Path − This specifies the directories for which the cookie is valid. Domain − This can be used to specify the domain name. Security − This can be set to 1 to specify that the cookie should only be sent by secure

transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

Following example will create two cookies name and age these cookies will be expired after one hour.

Page 32: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

<?php setcookie("name", "John Watkin", time()+3600, "/","", 0); setcookie("age", "36", time()+3600, "/", "", 0);?><html> <head> <title>Setting Cookies with PHP</title> </head> <body> <?php echo "Set Cookies"?> </body> </html>

Accessing Cookies with PHP

PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

<html><head> <title>Accessing Cookies with PHP</title> </head> <body> <?php echo $_COOKIE["name"]. "<br />"; /* is equivalent to */ echo $HTTP_COOKIE_VARS["name"]. "<br />"; echo $_COOKIE["age"] . "<br />"; /* is equivalent to */ echo $HTTP_COOKIE_VARS["age"] . "<br />"; ?> </body></html>

Deleting Cookie with PHP

To delete a cookie, use the setcookie() function with an expiration date in the past.

<?php setcookie( "name", "", time()- 60, "/","", 0); setcookie( "age", "", time()- 60, "/","", 0);?>

Page 33: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

<html> <head> <title>Deleting Cookies with PHP</title> </head> <body> <?php echo "Deleted Cookies" ?> </body> </html>

PHP SessionPHP session is used to store and pass information from one page to another temporarily (until user close the website).

PHP session technique is widely used in shopping websites where we need to store and pass cart information e.g. username, product code, product name, product price etc from one page to another.

PHP session creates unique user id for each browser to recognize the user and avoid conflict between multiple browsers.

PHP session_start() function

PHP session_start() function is used to start the session. It starts a new or resumes existing session. It returns existing session if session is created already. If session is not available, it creates and returns new session.

Page 34: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

PHP $_SESSION

PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.

PHP Destroying Session

PHP session_destroy() function is used to destroy all session variables completely.

PHP File Handling

PHP File System allows us to create file, read file line by line, read file character by character, write file, append file, delete file and close file.

PHP Open File - fopen()

The PHP fopen() function is used to open a file.

PHP Close File - fclose()

The PHP fclose() function is used to close an open file pointer.

PHP Read File - fread()

The PHP fread() function is used to read the content of the file. It accepts two arguments: resource and file size.

PHP Write File - fwrite()

The PHP fwrite() function is used to write content of the string into file.

PHP Delete File - unlink()

The PHP unlink() function is used to delete file.

PHP MySQL Connect to a DatabaseThe free MySQL Database is very often used with PHP.Connecting to a MySQL DatabaseBefore you can access and work with data in a database, you must create a connection to thedatabase.In PHP, this is done with the mysql_connect() function.Syntaxmysql_connect(servername,username,password);Parameter Description

Page 35: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

Servername Optional. Specifies the server to connect to. Default value is "localhost:3306"username Optional. Specifies the username to log in with. Default value is the name of

the user that owns the server processpassword Optional. Specifies the password to log in with. Default is ""ExampleIn the following example we store the connection in a variable ($con) for later use in the script.The "die" part will be executed if the connection fails:<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());}echo 'Connected successfully';?>

The die() function prints a message and exits the current script.The mysqli_error() function returns the last error description for the most recent function call, if any.

Closing a ConnectionThe connection will be closed as soon as the script ends. To close the connection before, use themysqli_close() function.<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());}// some codemysqli_close($con);?>

PHP MySQL Create Database and TablesA database holds one or multiple tables.Create a DatabaseThe CREATE DATABASE statement is used to create a database in MySQL.SyntaxCREATE DATABASE database_nameTo get PHP to execute the statement above we must use the mysqli_query() function. Thisfunction is used to send a query or command to a MySQL connection.ExampleIn the following example we create a database called "my_db":<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());}if (mysqli_query("CREATE DATABASE my_db",$con)){echo "Database created";}else{echo "Error creating database: " . mysqli_error();}mysqli_close($con);?>

The mysqli_query() function performs a query against the database.

Create a Table

Page 36: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

The CREATE TABLE statement is used to create a database table in MySQL.SyntaxCREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name3 data_type,.......)We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.ExampleThe following example shows how you can create a table named "person", with three columns.The column names will be "FirstName", "LastName" and "Age":<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());}// Create databaseif (mysqli_query("CREATE DATABASE my_db",$con)){echo "Database created";}else{echo "Error creating database: " . mysqli_error();}// Create table in my_db databasemysqli_select_db("my_db", $con);$sql = "CREATE TABLE person(FirstName varchar(15),LastName varchar(15),Age int)";mysqli_query($sql,$con);mysqli_close($con);?>Important: A database must be selected before a table can be created. The database is selectedwith the mysqli_select_db() function.Note: When you create a database field of type varchar, you must specify the maximum length ofthe field, e.g. varchar(15).PHP MySQL Insert IntoThe INSERT INTO statement is used to insert new records into a database table.Insert Data Into a Database TableThe INSERT INTO statement is used to add new records to a database table.SyntaxINSERT INTO table_name VALUES (value1, value2,....)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 mysqli_query() function. This function is used to send a query or command to a MySQL connection.ExampleIn the previous chapter we created a table named "Person", with three columns; "Firstname","Lastname" and "Age". We will use the same table in this example. The following example addstwo new records to the "Person" table:<?php$con = mysqli_connect("localhost","root","");if (!$con)

Page 37: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

{die('Could not connect: ' . mysqli_error());}mysqli_select_db("my_db", $con);mysqli_query("INSERT INTO person (FirstName, LastName, Age)VALUES ('Peter', 'Grif', '35')");mysqli_query("INSERT INTO person (FirstName, LastName, Age)VALUES ('Glenn', 'jjjj', '33')");mysqli_close($con);?>Insert Data From a Form Into a DatabaseNow we will create an HTML form that can be used to add new records to the "Person" table.Here is the HTML form:<html><body><form action="insert.php" method="post">Firstname: <input type="text" name="firstname" />Lastname: <input type="text" name="lastname" />Age: <input type="text" name="age" /><input type="submit" /></form></body></html>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.Below is the code in the "insert.php" page:<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());}mysqli_select_db("my_db", $con);$sql="INSERT INTO person (FirstName, LastName, Age)VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";if (!mysqli_query($sql,$con)){die('Error: ' . mysql_error());}echo "1 record added";mysqli_close($con)?>PHP MySQL SelectThe SELECT statement is used to select data from a database.Select Data From a Database TableThe SELECT statement is used to select data from a database.SyntaxSELECT column_name(s)FROM table_nameNote: SQL statements are not case sensitive. SELECT is the same as select.To get PHP to execute the statement above we must use the mysqli_query() function. This function is used to send a query or command to a MySQL connection.ExampleThe following example selects all the data stored in the "Person" table (The * character selects allof the data in the table):<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());

Page 38: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

}mysqli_select_db("my_db", $con);$result = mysqli_query("SELECT * FROM person");while($row = mysqli_fetch_array($result)){echo $row['FirstName'] . " " . $row['LastName'];echo "<br />";}mysqli_close($con);?>The example above stores the data returned by the mysql_query() function in the $result variable. Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an array. Each subsequent call to mysqli_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']).Display the Result in an HTML TableThe following example selects the same data as the example above, but will display the data in anHTML table:<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());}mysqli_select_db("my_db", $con);$result = mysqli_query("SELECT * FROM person");echo "<table border='1'><tr><th>Firstname</th><th>Lastname</th></tr>";while($row = mysqli_fetch_array($result)){echo "<tr>";echo "<td>" . $row['FirstName'] . "</td>";echo "<td>" . $row['LastName'] . "</td>";echo "</tr>";}echo "</table>";mysqli_close($con);?>PHP MySQL The Where ClauseTo select only data that matches a specified criteria, add a WHERE clause to the SELECTstatement.The WHERE clauseTo select only data that matches a specific criteria, add a WHERE clause to the SELECT statement.SyntaxSELECT column FROM table WHERE column operator valueTo get PHP to execute the statement above we must use the mysqli_query() function. Thisfunction is used to send a query or command to a MySQL connection.ExampleThe following example will select all rows from the "Person" table, where FirstName='Peter':<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());}mysqli_select_db("my_db", $con);$result = mysqli_query("SELECT * FROM personWHERE FirstName='Peter'");

Page 39: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

while($row = mysqli_fetch_array($result)){echo $row['FirstName'] . " " . $row['LastName'];echo "<br />";}?>PHP MySQL UpdateThe UPDATE statement is used to modify data in a database table.Update Data In a DatabaseThe UPDATE statement is used to modify data in a database table.SyntaxUPDATE table_name SET column_name = new_value WHERE column_name = some_valueTo 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.<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());}mysqli_select_db("my_db", $con);mysqli_query("UPDATE Person SET Age = '36'WHERE FirstName = 'Peter' AND LastName = 'Griffin'");mysqli_close($con);?>

PHP MySQL Delete FromThe DELETE FROM statement is used to delete rows from a database table.Delete Data In a DatabaseThe DELETE FROM statement is used to delete records from a database table.SyntaxDELETE FROM table_name WHERE column_name = some_value<?php$con = mysqli_connect("localhost","root","");if (!$con){die('Could not connect: ' . mysqli_error());}mysqli_select_db("my_db", $con);mysqli_query("DELETE FROM Person WHERE LastName='Griff'");mysqli_close($con);?>

AJAXAJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related technologies like JavaScript, DOM, XML, HTML, CSS etc.AJAX communicates with the server using XMLHttpRequest object.

AJAX allows you to send and receive data asynchronously without reloading the web page. So it is fast.

AJAX allows you to send only important information to the server not the entire page. So only valuable data from the client side is routed to the server side. It makes your application interactive and faster.

Page 40: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

There are too many web applications running on the web that are using ajax technology like gmail, facebook,twitter, google map, youtube etc.

Synchronous (Classic Web-Application Model)

A synchronous request blocks the client until operation completes i.e. browser is unresponsive. In such case, javascript engine of the browser is blocked.

Asynchronous (AJAX Web-Application Model)

An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user can perform another operations also. In such case, javascript engine of the browser is not blocked.

AJAX technologies includes:

Page 41: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

HTML/XHTML and CSS DOM XML or JSON XMLHttpRequest JavaScript

HTML/XHTML and CSS

These technologies are used for displaying content and style. It is mainly used for presentation.

DOM

It is used for dynamic display and interaction with data.

XML or JSON

For carrying data to and from server. JSON (Javascript Object Notation) is like XML but short and faster than XML.

XMLHttpRequest

For asynchronous communication between client and server. An object of XMLHttpRequest is used for asynchronous communication between client and server.

It performs following operations:

1. Sends data from the client in the background2. Receives the data from the server3. Updates the webpage without reloading it.

JavaScript

It is used to bring above technologies together. Independently, it is used mainly for client-side validation.

Advantages of AJAX

Reduce the traffic travels between the client and the server. Response time is faster so increases performance and speed. You can use JSON(JavaScript Object Notation) which is alternative to XML. AJAX communicates over HTTP Protocol. Asynchronous calls

AJAX make asynchronous calls to a web server. This means client browsers are avoid waiting for all data arrive before start the rendering.

XMLHttpRequestXMLHttpRequest has an important role in the Ajax web development technique.

Page 42: pavanatmacollege.orgpavanatmacollege.org/Students Corner/file/1521799520.docx  · Web viewPHP. PHP is a open source, interpreted and object-oriented scripting language i.e. executed

Disadvantages of AJAX

It can increase design and development time More complex than building classic web application Security is less in AJAX application as all files are downloaded at client side. Search Engine like Google cannot index AJAX pages. JavaScript disabled browsers cannot use the application. Open Source: View source is allowed and anyone can view the code source written for AJAX.