First 2 Units PHP
First 2 Units PHP
UNIT - I
PHP Definition :
PHP started out as a small open source project that evolved as more and more people found
out how useful it was. Rasmus Lerd orf unleashed the first version of PHP way back in
1994.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and
CORBA), making n-tier development a possibility for the first time.
What is PHP?
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code is executed on the server, and the result is returned to the browser as plain
HTML
PHP files have extension ".php"
With PHP you are not limited to output HTML. You can output images, PDF files, and even
Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
PHP 7 is much faster than the previous popular stable release (PHP 5.6)
PHP 7 has improved Error Handling
PHP 7 supports stricter Type Declarations for function arguments
PHP 7 supports new operators (like the spaceship operator: <=>)
Example :
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
Output :
PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, through email
you can send data, return data to the user.
You add, delete, modify elements within your database through PHP.
Using PHP, you can restrict users to access some pages of your website.
Characteristics of PHP :Five important characteristics make PHP's practical nature possible −
Simplicity
Efficiency
Security
Flexibility
Familiarity
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Output :
Hello World!
ESSENTIALS OF PHP :
As of April 2007 there were an estimated 20 million unique web domains actively using PHP
to generate and deliver content. While it is hard to conceptualize 20 million web servers using
PHP, it is not hard to infer from this number that PHP has taken the web design and
development community by storm since humble beginnings in 1995.
Intended Audience :
It is anticipated that the typical reader already has some web based experience at least in
terms of understanding the concepts of a web server and creating HTML based content.
PHP 3 - Hits the Big Time :By the time 1997 arrived the number of web sites on the internet
was growing exponentially and most of these web sites were being implemented using the
Apache web server.
It was around this time that Andy Gutmans and Zeev Suraski launched the PHP 3 project, a
project designed to take PHP to the next level.
One of the key achievements of the PHP 3 project was to implement PHP as a robust Apache
Module. PHP 3 was implemented using a modular approach that made it easy for others to
extend functionality, and also introduced the first elements of object-orientation that would
continue to evolve through subsequent releases.
The combination of PHP 3 and Apache quickly lead to the widespread adoption of PHP, and
it is commonly estimated that, at its peak adoption level, PHP3 was used to power over 10%
of all web sites on the internet.
PHP 4 - Optimization, Scalability and More :With PHP version 4 Andi Gutmans and Zeev
Suraski once again re-architected PHP from the ground up. PHP version 4 was built upon a
piece of technology called the Zend Engine. The move to the Zend Engine brought about a
number of key improvements in PHP:
Support for other web servers (Microsoft's Internet Information Server (IIS) being of
particular significance).
Improved memory handling to avoid memory leaks (one of the most difficult types of
problems to isolate in a program).
Improved efficiency and performance to support large scale, complex, mission critical
enterprise application development using PHP.
In addition PHP 4 also built on the earlier Object Oriented Programming features of
PHP 3 with the introduction of classes.
PHP 5 - Object Orientation, Error Handling and XML :The main, though far from only,
feature of PHP 5 is the improved support for Object Oriented Programming (OOP). In
addition, PHP 5 introduced some features common in other languages such as Java like
try/catch error and exception handling. PHP 5 also introduced new extensions aimed at easing
the storage and manipulation of data. Significant new features include SimpleXML for
handling XML documents, and SQLite, an embedded basic and easy to use database
interface.
How Popular is PHP?
A quick review of some statistics gives a very clear indication of the phenomenally
widespread use of PHP. A company called Netcraft specializes in recording data about the
types of web servers and web server modules that are used on the internet. As of April 2007
Netcraft reported that PHP was used on over 20,000,000 distinct web domains. A web survey
by SecuritySpace also lists PHP as the most widely deployed Apache module. It is safe to say
that PHP has taken the internet by storm. As if that wasn't enough one of the world’s most
popular web sites, Wikipedia, is build primarily using PHP.
AN OVERVIEW OF PHP
Given that a web browser knows nothing about PHP in a web page, then clearly something
has to be done with any PHP script in the page before it reaches the browser. This is where
the PHP pre-processing module comes in. The PHP module is, as mentioned previously,
integrated into the web server. The module tells the web server that when a page is to be
served which contains PHP script (identified by special markers) that it is to pass that script
to the PHP pre-processing module and wait for the PHP module to send it some content to
replace that script fragment. The PHP processing module understands PHP, executes the PHP
script written by the web developer and, based on the script instructions, creates output that
the browser will understand. The web server substitutes the content provided by the PHP pre-
processor module in place of the PHP script in the web page and sends it to the browser
where it is rendered for the user to view.
The following HTML contains some PHP script that is designed to output an HTML
paragraph tag
<html>
<head>
</head>
<body>
<?php
Echo ‘<p> This line of HTML generated by a PHP Script embedded into an HTML
document</p>’;
?>
</body>
</html>
The above example looks very much like standard HTML until you reach the part surrounded
by <?php and ?>. These are markers that designate where the embedded PHP script begins
and ends. When the web server finds this it sends it to the PHP module. The PHP module
interprets it, converts it to HTML and sends it back to the web server. The web server, in
turn, sends the following to the browser:
<html>
<head>
</head>
<body>
<p> This line of HTML generated by a PHP Script embedded into an HTML document</p>
</body>
</html>
Once loaded into the browser, it is rendered just like any other web page. The fact that the
web page originally contained PHP is completely transparent to the web browser. The above
example is certainly an oversimplification of the power of PHP. Some may question why one
would use PHP to output some static text that could have been achieved more easily using an
HTML tag.
needs to extract data from the database to be executed on the server, rather than waiting until
it reaches the browser. It is for this kind of task that PHP is perfectly suited. It is also fast and
efficient (because the script is executed on the server it gets to take advantage of multi-
processing, large scale memory and other such enterprise level hardware features. In addition
to the advantages of being a server side scripting language PHP is easy to learn and use. The
fact that PHP works seamlessly with HTML makes it accessible to a broad community of
web designers. Perhaps one of the most significant advantages of PHP to some is the ease
with which it interacts with the MySQL database to retrieve and store data.
PHP OPERATORS :
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators
Show Examples
10
Comparison Operators
Show Examples
> Checks if the value of left operand is greater than the (A > B) is
value of right operand, if yes then condition becomes not true.
true.
< Checks if the value of left operand is less than the value (A < B) is
of right operand, if yes then condition becomes true. true.
<= Checks if the value of left operand is less than or equal (A <= B) is
to the value of right operand, if yes then condition true.
becomes true.
Logical Operators
Show Examples
and Called Logical AND operator. If both the operands are (A and B) is
true then condition becomes true. true.
&& Called Logical AND operator. If both the operands are (A && B) is
non zero then condition becomes true. true.
Assignment Operators
Show Examples
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for
a true or false value and then execute one of the two given statements depending upon the
result of the evaluation. The conditional operator has this syntax −
Show Examples
Operators Categories
All the operators we have discussed above can be categorised into following categories −
Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression.
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
PHP STRINGS
In this chapter we will look at some commonly used functions to manipulate strings.
Example
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
OUTPUT : 12
(or)
<?php
echo strlen("Hello world!"); // outputs 12
?>
Example
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
OUTPUT : 2
(or)
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
EXAMPLE :
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
(or)
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE.
<!DOCTYPE html>
<html>
<body>
<?php
echo strpos("Hello world!", "world");
?>
</body>
</html>
OUTPUT : 6
(or)
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The first character position in a string is 0 (not 1).
The PHP str_replace() function replaces some characters with some other characters in a
string.
EXAMPLE :
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
(or)
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
PHP ARRAYS
EXAMPLE :
<!DOCTYPE html>
<html>
<body>
<?php
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
OUTPUT :
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
array();
The count() function is used to return the length (the number of elements) of an array:
<!DOCTYPE html>
<html>
<body>
<?php
echo count($cars);
?>
</body>
</html>
OUTPUT : 3
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
EXAMPLE :
<!DOCTYPE html>
<html>
<body>
<?php
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
OUTPUT:
To loop through and print all the values of an indexed array, you could use a for loop, like
this:
<!DOCTYPE html>
<html>
<body>
<?php
$arrlength = count($cars);
echo $cars[$x];
echo "<br>";
?>
</body>
</html>
OUTPUT:
Volvo
BMW
Toyota
Associative arrays are arrays that use named keys that you assign to them.
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
OUTPUT :
To loop through and print all the values of an associative array, you could use a foreach loop,
like this:
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
echo "<br>";
?>
</body>
</html>
OUTPUT:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an
element.
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column.
To get access to the elements of the $cars array we must point to the two indices (row and
column):
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
?>
</body>
</html>
OUTPUT:
In this chapter, we will go through the following PHP array sort functions:
Sort Array in Ascending Order - sort() : The following example sorts the elements of the
$cars array in ascending alphabetical order:
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
sort($cars);
$clength = count($cars);
echo $cars[$x];
echo "<br>";
?>
</body>
</html>
OUTPUT: BMW
Toyota
Volvo
The following example sorts the elements of the $numbers array in ascending numerical
order:
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
sort($numbers);
$arrlength = count($numbers);
echo $numbers[$x];
echo "<br>";
?>
</body>
</html>
OUTPUT:
2
4
6
11
22
FLOWCONTROLS IN PHP:
The if...else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
Output "Have a good day!" if the current time is less than 20, and "Have a good night!"
otherwise:
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
} else {
?>
</body>
</html>
OUTPUT:
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example
Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if
the current time is less than 20. Otherwise it will output "Have a good night!":
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
} else {
?>
</body>
</html>
OUTPUT:
The hour (of the server) is 10, and will give the following message:
Have a good day!
The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in
the structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
PHP Loops : Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost equal code-lines in
a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain
condition is true.
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as
the specified 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
The following chapters will explain and give examples of each loop type.
The while loop executes a block of code as long as the specified condition is true.
Syntax
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
while($x <= 5) {
$x++;
?>
</body>
</html>
OUTPUT:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>
The for loop is used when you know in advance how many times the script should run.
Syntax
Parameters:
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
</body>
</html>
OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
PHP Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
</body>
</html>
OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
PHP Functions
PHP has more than 1000 built-in functions, and in addition you can create your own custom
functions.
PHP has over 1000 built-in functions that can be called directly, from within a script, to
perform a specific task.
Besides the built-in PHP functions, it is possible to create your own functions.
Syntax
function functionName() {
code to be executed;
}
Note: A function name must start with a letter or an underscore. Function names are NOT
case-sensitive.
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
writeMsg();
?>
</body>
</html>
OUTPUT:
Hello world!
UNIT - II
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.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.
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.
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
}
File: function1.php
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
Hello PHP Function
SASC,PUDUKKOTTAI. Page 1
PROGRAMMING IN PHP
We can pass the information in PHP function through arguments which is separated by
comma.
File: functionarg.php
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
Hello Sonoo
Hello Sanoo
Hello Vimal
Hello John
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);
?>
Output:
Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old
SASC,PUDUKKOTTAI. Page 2
PROGRAMMING IN PHP
Value passed to the function doesn't modify the actual value by default (call by value). But
we can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you
need to use ampersand (&) symbol before the argument name.
File: functionref.php
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Hello Call By Reference
Output:
Hello Call By Reference
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
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
SASC,PUDUKKOTTAI. Page 3
PROGRAMMING IN PHP
Output:
Hello Rajesh
Hello Sonoo
Hello John
File: functiondefaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
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.
SASC,PUDUKKOTTAI. Page 4
PROGRAMMING IN PHP
<?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>
Output:
PHP allows you to call function by value and reference both. In case of PHP call by value,
actual value is not modified if it is modified inside the function.
Example
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Value' string. But, printing $str variable results 'Hello' only. It is because changes are
done in the local variable $str2 only. It doesn't reflect to $str variable.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
SASC,PUDUKKOTTAI. Page 5
PROGRAMMING IN PHP
?>
In case of PHP call by reference, actual value is modified if it is modified inside the function.
In such case, you need to use & (ampersand) symbol with formal arguments. The &
represents reference of the variable.
Example
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is
because changes are done in the actual variable $str.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
Output:29.6M561
This is Call By Reference
PHP allows you to define C++ style default argument values. In such case, if you don't pass
any value to the function, it will use default argument value.
Example
<?php
function sayHello($name="Ram"){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello();//passing no value
sayHello("Vimal");
?>
SASC,PUDUKKOTTAI. Page 6
PROGRAMMING IN PHP
Output:
Hello Sonoo
Hello Ram
Hello Vimal
PHP Variable Length Argument Function
PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.
The 3 dot concept is implemented for variable length argument since PHP 5.6.
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}
Output:
10
PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.
It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
EXAMPLE: PRINTING NUMBER
<?php
function display($number) {
if($number<=5){
SASC,PUDUKKOTTAI. Page 7
PROGRAMMING IN PHP
display(1);
?>
Output:
1
2
3
4
5
The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:
Example
<html>
<body>
</body>
</html>
OUTPUT:
SASC,PUDUKKOTTAI. Page 8
PROGRAMMING IN PHP
Name:
E-mail:
Submit
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.
To display the submitted data you could simply echo all the variables. The "welcome.php"
looks like this:
<html>
<body>
</body>
</html>
The same result could also be achieved using the HTTP GET method:
Example
<html>
<body>
</body>
</html>
OUTPUT:
SASC,PUDUKKOTTAI. Page 9
PROGRAMMING IN PHP
Name:
E-mail:
Submit
</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to
validate form data to protect your script from malicious code.
Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 =>
value3, ...)). This array holds key/value pairs, where keys are the names of the form controls
and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which
means that they are always accessible, regardless of scope - and you can access them from
any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to
send. The limitation is about 2000 characters. However, because the variables are displayed
in the URL, it is possible to bookmark the page. This can be useful in some cases.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Information sent from a form with the POST method is invisible to others (all names/values
are embedded within the body of the HTTP request) and has no limits on the amount of
information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark
the page.
Let's see a simple example to receive data from get request in PHP.4
File: form1.html
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>
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
SASC,PUDUKKOTTAI. Page 11
PROGRAMMING IN PHP
1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $password varia
ble
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>
Output:
The HTML form we will be working at in these chapters, contains various input fields:
required and optional text fields, radio buttons, and a submit button:
SASC,PUDUKKOTTAI. Page 12
PROGRAMMING IN PHP
First we will look at the plain HTML code for the form:
Text Fields
The name, email, and website fields are text input elements, and the comment field is a
textarea. The HTML code looks like this:
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
The Form Element
When the form is submitted, the form data is sent with method="post".
PHP - Required Fields
From the validation rules table on the previous page, we see that the "Name", "E-mail", and
"Gender" fields are required. These fields cannot be empty and must be filled out in the
HTML form.
SASC,PUDUKKOTTAI. Page 13
PROGRAMMING IN PHP
Then in the HTML form, we add a little script after each required field, which generates the
correct error message if needed (that is if the user tries to submit the form without filling out
the required fields):
Example
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
>
SASC,PUDUKKOTTAI. Page 14
PROGRAMMING IN PHP
</form>
* required field
Name: *
E-mail: *
Website:
Comment:
Submit
Your Input:
Web Browser
web Browser is an application software that allows us to view and explore information on
the web. User can request for any web page by just entering a URL into address bar.
Web browser can show text, audio, video, animation and more. It is the responsibility of a
web browser to interpret text and commands contained in the web page.
Earlier the web browsers were text-based while now a days graphical-based or voice-based
web browsers are also available. Following are the most common web browser available
today:
Browser Vendor
SASC,PUDUKKOTTAI. Page 15
PROGRAMMING IN PHP
Safari Apple
K-meleon K-meleon
PHP BROWSER :
PHP is written as standard text files with the .php extension. PHP files are often saved within
a folder in a web server's public directory (or a web root directory). On most systems this will
either be named public or public_html. For example, if a file was saved as index.php in a
web root directory, a user could access it by
typing http://www.example.org or http://www.example.org/index.php.
After Apache decides that is is a PHP file, it gives it to the PHP interpreter. When PHP
receives the file it reads through it and executes any PHP code it can find. After it is done
with the file, the PHP interpreter gives the output of the code, if any, back to Apache. When
Apache gets the output back from PHP, it sends that output back to a browser which renders
it to the screen.
SASC,PUDUKKOTTAI. Page 16
PROGRAMMING IN PHP
traditional sense, the main goal of PHP is to generate some HTML document that a browser
can render.
However, modern applications built with client-side MVC frameworks often see the role of
PHP change to just interacting with server-side data storage.
Let's take another look at this process with a diagram. In this diagram, we will assume the
user is going to the Laravel website at http://laravel.com/. The following figure has circled
numbers that will highlight the various stages of the request. A step-by-step explanation of
each step follows the figure.
Step 1
The user enters `http://laravel.com` into their browser and taps/hits 'enter'.
Step 2
After the user has tapped/hit 'enter', the browser sends the page request over the
Internet to the web server.
Step 3
The web server gets the request and analyzes the request information. Apache realizes
that we didn't specify a file, so it looks for a directory index and finds `index.php`.
Step 4
Since Apache knows to send files that end with the `.php` file extension to the PHP
interpreter, it asks PHP to execute the file.
Step 5
In this step, PHP is executing the code contained in the `index.php` file from the
request. During this step, PHP may interact with databases, the file system or make
external API calls, amongst other things.
Step 6
After PHP has finished executing the `index.php` file, it sends the output back to
Apache.
Step 7
Apache receives the output from PHP and sends it back over the Internet to a user's
web browser. This is called the `web response`.
SASC,PUDUKKOTTAI. Page 17
PROGRAMMING IN PHP
Step 8
The user's web browser receives the response from the server, and renders the web
page on a computer or device.
As you can see, PHP interacts with a web server in a very real way. The actual request
process is very simple, and one of the reasons that PHP is so well suited for web application
development.
The PHP programme interacts with the site server, which is the programme that sends out
web pages to the rest of the world. When you type a URL into the address bar of your web
browser, you’re telling the web server at that URL to email you an HTML file. The requested
file is sent by the web server in response. The HTML file is read by your browser, and then
shows the web page. When you press a source on a web page, you’re also requesting a file
from the web server. Additionally, when you press a web page button that submits a form, the
web server processes a file. When PHP is mounted, the procedure is exactly the same. You
submit a file, and the web server, which happens to be running PHP, responds with HTML,
because of PHP it all happens. You can understand this through these steps:-
Step 1 – Client send a page request to the web server.
SASC,PUDUKKOTTAI. Page 18
PROGRAMMING IN PHP
Step 3 – Now PHP interpreter will take the Date from Database and response it back to the
Web server.
SASC,PUDUKKOTTAI. Page 19
PROGRAMMING IN PHP
Step 4 – At last Web server response to the client who has asked for the page request.
Parameters :
The pow() function accepts two parameters as shown in the above syntax:
Return Value: It returns a number (integer or floating-point) which is equal to $base raised
to the power of $exponent.
Examples:
Input : pow(3, 2)
Output : 9
SASC,PUDUKKOTTAI. Page 20
PROGRAMMING IN PHP
Input : pow(-3, 2)
Output : 9
<?php
echo(pow(3, 2));
?>
Output:
9
When the $base is negative and $exponent is a positive even number:
<?php
echo(pow(-3, 2));
?>
Output:
9
When $base is negative and $exponent is a negative odd number:
<?php
echo(pow(-3, -3));
?>
Output:
0.037037037037037
SASC,PUDUKKOTTAI. Page 21
PROGRAMMING IN PHP
When $base is negative and $exponent is a negative number with decimal places:
<?php
echo(pow(-3, -3.2));
?>
Output:
NaN
SASC,PUDUKKOTTAI. Page 22