Professional Documents
Culture Documents
What Is PHP: Common Uses of PHP
What Is PHP: Common Uses of PHP
INTRODUCTION
What is PHP
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
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.
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
Characteristics of PHP
Five important characteristics make PHP's practical nature possible −
Simplicity
Efficiency
Security
Flexibility
Familiarity
PHP Features
There are given many features of PHP.
o Performance: Script written in PHP executes much faster then those scripts written
in other languages such as JSP & ASP.
o 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.
o 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.
o Compatibility: PHP is compatible with almost all local servers used today like
Apache, IIS etc.
o Embedded: PHP code can be easily embedded within HTML tags and script.
Page |3
History
History of the Language
Originally (it is believed) the letters stood for Personal Home Page. The first
work was done by Rasmus Lerdorf and dates back to about 1994. Lerdorf
originally used it for his personal page – specifically to track visitors. Soon, a
lot of additional functions were added. It took a few years, though, for it to
become a language and not just a set of tools.
The code was released in the mid-1990s. Israel’s Andi Gutmans and Zeev
Suraski did a major overhaul in 1997 with the goal of using PHP to run an
eCommerce site. Their version, termed PHP 3.0, had more of the features
we expect and see today.
The same duo later created Version 4.0. 2004 saw another major revision,
PHP 5.0. Although there has not yet been a 6.0, there have been significant
improvements since 5.0, including the removal of several things that had
caused instability or potential security breaches.
Page |4
Output
Page |5
Example
1.<!DOCTYPE>
2.<html>
3.<body>
4.<?php
5.echo "<h2>Hello by PHP</h2>";
6.?>
7.</body>
8.</html>
Page |6
Client side vs
server side
BASIS FOR SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING
COMPARISON
Basic Works in the back end which could Works at the front end and
not be visible at the client end. script are visible among the
users.
the server.
Affect Could effectively customize the Can reduce the load to the
websites.
Page |7
STATIC VS DYNAMIC
WEBSITE
Static v Dynamic Website Design
There are basically two main types of website - static and dynamic.
A static site is one that is usually written in plain HTML and what is in the
code of the page is what is displayed to the user.
A dynamic site is one that is written using a server-side scripting language such as PHP,
ASP, JSP, or Coldfusion. In such a site the content is called in by the scripting language
from other files or from a database depending on actions taken by the user.
Flexibility is the main advantage of a static site - every page can be different if desired,
to match the layout to different content, and the designer is free to put in any special
effects that a client may ask for in a unique way on different pages. This allows theming
- for instance an author may want a different theme for a different book and associated
pages or perhaps for a series of books, in order to match the cover designs or the
context of the stories.
The main problem with any static site appears when you wish to update the content.
Unless you are conversant with HTML and the design methods used in the site then you
Page |9
have to go back to the designer to have any content changes made. This may be
perfectly ok when a new page is required which needs design input, but if all you want
to do is change some text then it can be a nuisance for both client and designer.
The second main problem is scalability. If you wish to sell products on your site and you
have a lot of them then you may have to construct individual pages for each one, which
can take considerable time, effort and cost.
The main advantages of dynamic sites are that by connecting them to databases you
can easily pull in information in an organised and structured way to create product
pages or categories of related products sorted in a variety of different ways depending
on how the user wants to view them.
This ability to connect to a database means that you can also create a content
management system - an interface which allows the client to input and manage data via
a web-based series of administration pages. That content can be text for their pages and
images to go along with the text, or items in their product range with categories,
specifications, short and long descriptions, images, etc. In both these cases it can be as
simple or as complex as the client requires.
There are little or no ongoing costs unless there is a change in the basic design or an
extra capability added.
The design of a dynamic site is more fixed than a static one because many of the pages
are essentially a template into which data and content is poured to create multiple
pages of a similar type. So for instance all your product pages will be essentially the
same page layout with different data being displayed. While some customisation
cabability can be built in it is usually quite limited, such a selecting from a set of pre-
defined options. Individual layout changes to particular pages are not usually possible.
P a g e | 10
P a g e | 11
EMBEDDING PHP
CODE IN WEB PAGES
Step 1. Launch a plain text editor and create this valid barebones HTML5
document with an empty body section
<!DOCTYPE HTML>
<html lang=“en”>
<head><meta charset=”UTF-8”>
<body>
</body>
</html>
Step 2. Insert tags into the body section to contain PHP code
<?php
?>
Step 3. Now insert between the PHP tags a descriptive comment and a
line of code to write content into the body section
Step 5. Next enter the location http://localhost/hello.php into your web browser’s
address field to see Abyss serve up a web page containing content written by embedded PHP
code
Step 6. Now use your web browser’s View Source facility to see that PHP has written the
content into the body section, including the HTML <h1> </h1> heading tags
P a g e | 14
PHP BASIC
TOKENS:
A token is the basic component of source code in programming language. It is the smallest different,
individual and independent unit used in any programming language. Token plays an important role in
the development of a program. The different types of token used in PHP an:
Keywords
Identifiers
Constants
Operators
Strings etc
Variable
A variable is a name given to storage area that may be used to store a data
value. A variable is a name that carrier a value with it. Variables are those
quantities whose value vary during execution of the program. It is a way to
access computer’s memory. Variables act as a container that stores
information for later use in your scripts.
Local variables
Function parameters
Global variables
Static variables.
Local Variables
A variable declared in a function is considered local; that is, it can be
referenced solely in that function. Any assignment outside of that function
will be considered to be an entirely different variable from the one
contained in the function −
P a g e | 15
Global Variables
In contrast to local variables, a global variable can be accessed in any part
of the program. However, in order to be modified, a global variable must be
explicitly declared to be global in the function in which it is to be modified.
This is accomplished, conveniently enough, by placing the keyword GLOBAL
in front of the variable that should be recognized as global. Placing this
keyword in front of an already existing variable tells PHP to use the variable
having that name
Constants
A constant is a name or an identifier for a simple value. A constant value
cannot change during the execution of the script. By default, a constant is
case-sensitive. By convention, constant identifiers are always uppercase. A
constant name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores. If you have defined a constant, it can
never be changed or undefined.
To define a constant you have to use define() function and to retrieve the
value of a constant, you have to simply specifying its name. Unlike with
variables, you do not need to have a constant with a $. You can also use
the function constant() to read a constant's value if you wish to obtain the
constant's name dynamically.
constant() function
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not
know its name, i.e. It is stored in a variable or returned by a function.
P a g e | 16
1. Scalar Types
2. Compound Types
3. Special Types
1. boolean
2. integer
3. float
4. string
1. array
2. object
1. resource
2. NULL
P a g e | 17
OPERANDS AND
OPERATORS precedence
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and
5 are called operands and + is called operator. PHP language supports
following type of operators.
Arithmetic Operators
Comparison Operators
Assignment Operators
Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Show Examples
Comparison Operators
There are following comparison operators supported by PHP language
Show Examples
> Checks if the value of left operand is greater than the (A > B) is not
value of right operand, if yes then condition becomes true.
true.
< Checks if the value of left operand is less than the (A < B) is
value of right operand, if yes then condition becomes true.
true.
P a g e | 19
Logical Operators
There are following logical operators supported by PHP language
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.
! Called Logical NOT Operator. Use to reverses the logical !(A && B) is
state of its operand. If a condition is true then Logical false.
NOT operator will make false.
Assignment Operators
There are following assignment operators supported by PHP language −
P a g e | 20
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
P a g e | 21
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.
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.
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++
and Perl style (Unix shell style) comments.
1. <?php
2. // this is C++ style single line comment
3. # this is Unix Shell style single line comment
4. echo "Welcome to PHP single line comments";
5. ?>
1. <?php
2. /*
3. Anything placed
4. within comment
5. will not be displayed
6. on the browser;
7. */
8. echo "Welcome to PHP multi line comment";
9. ?>
P a g e | 24
PHP echo statement can be used to print string, multi line strings, escaping characters,
variable, array etc.
PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with
the argument list. Unlike echo, it always returns 1.
PHP print statement can be used to print string, multi line strings, escaping characters,
variable, array etc.
P a g e | 25
FLOWCHART
P a g e | 26
DECISION MAKING
The if, elseif ...else and switch statements are used to take decision based
on the different condition.
You can use conditional statements in your code to make your decisions.
PHP supports following three decision making statements –
OUTPUT
P a g e | 28
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
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")
else
?>
</body>
</html>
P a g e | 29
OUTPUT
P a g e | 30
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;
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")
else
?>
</body>
</html>
P a g e | 31
Output
P a g e | 32
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;
}
Example
<html>
<body>
<?php
$d = date("D");
P a g e | 33
switch ($d){
case "Mon":
break;
case "Tue":
break;
case "Wed":
break;
case "Thu":
break;
case "Fri":
break;
case "Sat":
break;
case "Sun":
break;
P a g e | 34
?>
</body>
</html>
P a g e | 35
We will discuss about continue and break keywords used to control the
loops execution.
P a g e | 36
FLOWCHART
P a g e | 37
Syntax
for (initialization; condition; increment){
code to be executed;
}
The initializer is used to set the start value for the counter of the number of
loop iterations. A variable may be declared here for this purpose and it is
traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value
of two variables on each pass of the loop −
<html>
<body>
<?php
$a = 0; $b = 0;
$a += 10; $b += 5;
?>
</body>
</html>
P a g e | 38
FLOWCHART
P a g e | 39
If the test expression is true then the code block will be executed. After the
code has executed the test expression will again be evaluated and the loop
will continue until the test expression is found to be false.
Syntax
while (condition) {
code to be executed;
}
Example
This example decrements a variable value on each iteration of the loop and
the counter increments until it reaches 10 when the evaluation is false and
the loop ends.
<html>
<body>
<?php
$i = 0; $num = 50;
$num--; $i++;
?>
</body>
</html>
P a g e | 40
OUTPUT
P a g e | 41
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 10
−
<html>
<body>
<?php
$i = 0; $num = 0;
do {
$i++;
while( $i < 10 );
?>
</body>
</html>
P a g e | 42
OUTPUT
P a g e | 43
Syntax
foreach (array as value) {
code to be executed;
}
Example
Try out following example to list out the values of an array.
<html>
<body>
<?php
?>
</body>
</html>
P a g e | 44
FUNCTION
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.
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.
The following section will show you how easily you can define
your own function in PHP.
P a g e | 46
OUTPUT
P a g e | 47
Example
<?php
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>
P a g e | 48
FORMAL VS ACTUAL
PARAMETER
Actual vs Formal Parameters
The Actual
parameters are
the values that The Formal Parameters are the variables defined by the
are passed to the function that receives values when the function is called.
function when it
is invoked.
Related Function
The actual
parameters are
The formal parameters are in the called function.
passed by the
calling function.
Data Types
In actual
parameters,
there is no
In formal parameters, the data types of the receiving values
mentioning of
should be included.
data types. Only
the value is
mentioned.
P a g e | 49
OUTPUT
P a g e | 50
LIBRARY FUNCTION
Library function are the in-built function in PHP which are used to perform a specific task. PHP comes
standard with many function and constructos. A library function is accessed by simply writing the
function name, followed by a list of arguments, which represents the information being passed to the
function, The arguments must be enclosed in parentheses and separated by commas they can be
constants variable or more complex expressions, Note that the parentheses must be represents even
when these are so arguments.
Function Description
chop() Removes whitespace or other characters from the right end of a string
STRING
PHP String
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4
ways to specify string in PHP.
o single quoted
o double quoted
o heredoc syntax
o newdoc syntax (since PHP 5.3)
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>
1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>
P a g e | 54
INTERPOLATION
Variable interpolation is adding variables in between a string data. PHP will
parse the interpolated variables and replace the variable with its value while
processing the string data. The variable parsing is allowed with the string data
enclosed with double quotes or with heredocs. Since, the variable interpolation
will not be effective with the single quoted string or nowdocs, since it doesn’t
support variable parsing.
$name = "PHPPOT";
CHARACTER AND
STRING INDEXES
In some programming language there are different data types for character and strings. In PHP
there is no distinct character type different from the string type. PHP takes character argument
as a string of 1 length. In PHP, you can retrieve the individual character of a string by including
the number of character m starting at 0, enclosed in curly braces { } immediately followed by a
string variable.
<httml>
<head>
</head>
<body>
<?php
$my_string= “programming”
$character = $my_string($index);
?>
P a g e | 56
</body>
</html>
P a g e | 57
OPERATORS
PHP String Operators
PHP has two operators that are specially designed for strings.
Heredoc
In order to allow people to easily write large amounts of text from within PHP, but
without the need to constantly escape things, heredoc syntax was developed. Heredoc
might be a little tricky to understand at first, but it's actually a big help. Put simply, it
allows you to define your own string limiter so that you can make it something other
than a double or single quote. So, for example, we could use the string "EOT" (end of
text) for our delimiter, meaning that we can use double quotes and single quotes freely
within the body of the text - the string only ends when we type EOT.
It is a little more complicated than that in practice, but not much - the string delimiter
needs to be by itself on a line, in the very first column. That is, you cannot add spacing
or tabs around it.
Take a look at this example:
<?php
It is completely free
?>
P a g e | 59
String Functions
These are functions that manipulate string data, refer to the article on strings for
implementation examples of string functions
Function Description
Formatting Strings
There's a pair of string functions that are particularly useful when you want to format
data for display (such as when you're formatting numbers in string
form): printf and sprintf. The printf function echoes text directly, and you assign
the return value of sprintf to a string. Here's how you use these functions (items in
square brackets, [ and ], in function specifications like this one are optional):
The format string is composed of zero or more directives: characters that are copied
directly to the result, and conversion specifications. Each conversion specification
consists of a percent sign (%), followed by one or more of these elements, in order:
An optional padding specifier that indicates which character should be used to pad
the results to the correct string size. This may be a space character or a 0 (zero
character). The default is to pad with spaces.
An optional alignment specifier that indicates whether the results should be left-
justified or right-justified. The default is right-justified (a - character here will make it
left-justified).
An optional number, the width specifier, specifying how many characters
(minimum) this conversion should result in.
An optional precision specifier that indicates how many decimal digits should be
displayed for floating-point numbers. (There is no effect for types other
than float.)
A type specifier that says what type the argument data should be treated as.
+-
P a g e | 62
ARRAY
An array is a data structure that stores one or more similar type of values in
a single value. For example if you want to store 100 numbers then instead
of defining 100 variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed
using an ID c which is called array index.
OUTPUT
P a g e | 64
Numeric Array
These arrays can store numbers, strings and any object but their index will
be represented by numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
<html>
<body>
<?php
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
?>
</body>
</html>
P a g e | 66
OUTPUT
P a g e | 67
Associative Arrays
The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index. Associative array
will have their index as string so that you can establish a strong association
between key and values.
NOTE − Don't keep associative array inside double quote while printing
otherwise it would not return any value.
Example
<html>
<body>
<?php
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
?>
</body>
</html>
P a g e | 69
OUTPUT
P a g e | 70
Multidimensional Arrays
A multi-dimensional 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.
Values in the multi-dimensional array are accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three
students in three subjects −
This example is an associative array, you can create numeric array in the
same fashion.
<html>
<body>
<?php
$marks = array(
"chemistry" => 39
),
"chemistry" => 29
P a g e | 71
),
"chemistry" => 39
);
?>
</body>
</html>
P a g e | 72
output
P a g e | 73
Accessing array
elements
Array elements can be accessed using the array[key] syntax.
<html>
<head> </head>
<body>
<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)0
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
</body>
</httml>
P a g e | 74
OUTPUT
P a g e | 75
Also if you have the value and don't know the key to delete the element you can
use array_search()to get the key.
unset() method
Note that when you use unset() the array keys won't change/reindex. If you
want to reindex the keys you can use array_values() after unset()which will
convert all keys to numerical enumerated keys starting from 0.
<html>
<head>
</head>
<body>
<?php
print_r($cars);
echo "<br>";
print_r($cars);
?>
</body> </html>
P a g e | 76
OUTPUT
P a g e | 77
CURRENT FUNCTION
current() Function
The current() function is an inbuilt function in PHP.
It is used to return the value of the element in an array which the internal pointer is currently
pointing to.
The current() function does not increment or decrement the internal pointer after returning
the value.
In PHP, all arrays have an internal pointer. This internal pointer points to some element in that array
which is called as the current element of the array.
Usually, the current element is the first inserted element in the array.
<html>
<head>
</head>
<body>
<?php
$fruit=array("mangp","guava","grapes");
echo current($fruit);
?>
</body>
</html>
P a g e | 78
OUTPUT
P a g e | 79
NEXT FUNCTION
PHP next() Function
The next() function is an inbuilt function in PHP and does the following
operations:
It is used to return the value of the next element in an array which the
internal pointer is currently pointing to. We can know the current
element by current function.
The next() function increments the internal pointer after returning the
value.
In PHP, all arrays have an internal pointer. This internal pointer points
to some element in that array which is called as the current element of
the array.
Usually, the next element at the beginning is the second inserted
element in the array.
<html>
<head>
</head>
<body>
<?php
$fruit=array("mango","guava","grapes","orange");
?>
</body>
</html>
P a g e | 81
OUTpUT
P a g e | 82
PREV
PHP prev() Function
The prev() function is an inbuilt function in PHP.
It is used to return the immediate previous element from an array of the element
which is currently pointed by the internal pointer.
We have already discussed current() function in PHP.
The current() function is used to return the value of the element which is currently
pointed by the internal pointer whereas the prev() function decrements or make the
internal pointer to point to the previous element of the currently pointed element.
<html>
<head>
</head>
<body>
<?php
?>
</body>
</html>
P a g e | 83
OUTPUT
P a g e | 84
RESET
PHP reset() Function
The reset() function is an inbuilt function in PHP.
This function is used to move any array’s internal pointer to the first element of
that array.
While working with arrays, it may happen that we modify the internal pointer of an array using
different functions like prev() function, current() function, key() function etc.
The reset() function resets the internal pointer to point to the first element of the array.
Example
<html>
<head>
</head>
<body>
<?php
$fruit=array("mango","guava","grapes","orange");
?>
</body>
</html>
P a g e | 86
OUTPUT
P a g e | 87
END
PHP | end() Function
The end() function is an inbuilt function in PHP and is used to find
the last element of the given array. The end() function changes
the internal pointer of an array to point to the last element and
returns the value of the last element.
<html>
<head>
</head>
<body>
<?php
$fruit=array("mango","guava","grapes","orange");
?>
</body>
</html>