Chapter 1 _ Introduction to PHP
Chapter 1 _ Introduction to PHP
Web Page
Web page is a document available on world wide web. Web Pages are stored on web server
and can be viewed using a web browser.
A web page can contain huge information including text, graphics, audio, video and hyper
links. These hyperlinks are the link to other web pages. Collection of linked web pages on a
web server is known as website. There is unique Uniform Resource Locator (URL) is associated
with each web page.
Static web pages are created using only HTML, CSS, Javascript. Static web pages are only used
when the information is no more required to be modified.
A client-side script is a program that is processed within the client browser. These kinds of
scripts are small programs which are downloaded, compiled and run by the browser. JavaScript
3 Chapter 1 : Introduction to PHP
is an important client-side scripting language and widely used in dynamic websites. The script
can be embedded within the HTML or stored in an external file.
External scripts are sent to the client from the server when they are requested. Scripts can also
be executed as a result of the user doing something like pressing a page button.
Client-side scripts can often be looked at if the user chooses to view the source code of the
page. JavaScript code is widely copied and recycled.
When a server-side script is processed, the request is sent to the server and the result is sent
back to the client. This is useful for websites which store large amounts of data, such as search
engines or social networks - it would be very slow for the client browser to download all the
data.
Difference between Client Side Scripting Language and Server Side Scripting
Language.
What is PHP ?
PHP originally stood for Personal Home Page. However, now, it stands for Hypertext
Preprocessor
PHP is an interpreted language, i.e., there is no need for compilation.
PHP is faster than other scripting languages, for example, ASP and JSP.
PHP is a server-side scripting language, which is used to manage the dynamic content of the
website.
PHP can be embedded into HTML.
PHP is an object-oriented language.
PHP is an open-source scripting language.
PHP is simple and easy to learn language.
PHP was created by Rasmus Lerdorf in 1994. It’s currently maintained by the PHP
Development Team.
Characteristics of PHP :
There are many features given by PHP. All Features discussed below one by one.
1. Familiarity
5 Chapter 1 : Introduction to PHP
2. Simplicity
3. Efficiency
4. Security
5. Flexibility
6. Open source
7. Object Oriented
Familiarity : If you are in programming background then you can easily understand the PHP
syntax. And you can write PHP script because of most of PHP syntax inherited from other
languages like C or Pascal.
Simplicity : PHP provides a lot of pre-define functions to secure your data. It is also compatible
with many third-party applications, and PHP can easily integrate with other.
In PHP script there is no need to include libraries like c, special compilation directives like Java,
PHP engine starts execution from (<?) escape sequence and end with a closing escape sequence
(<?). In PHP script, there is no need to write main function. And also you can work with PHP
without creating a class.
Efficiency : PHP 4.0 introduced resource allocation mechanisms and more pronounced support
for object-oriented programming, in addition to session management features. Eliminating
unnecessary memory allocation.
Security : Several trusted data encryption options are supported in PHP’s predefined function
set. You can use a lot of third-party applications to secure our data, allowing for securing our
application.
Flexibility : You can say that PHP is a very flexible language because of PHP is an embedded
language you can embed PHP scripts with HTML, JAVA SCRIPT, WML, XML, and many others.
You can run your PHP script any device like mobile Phone, tabs, laptops, PC and other because
of PHP script execute on the server then after sending to the browser of your device.
Free :PHP is an open source programming language so you can download freely there is no
need to buy a licence or anything.
Object Oriented : PHP has added some object-oriented programming features, and Object
Oriented programming became possible with PHP 4. With the introduction of PHP 5, the PHP
6 Chapter 1 : Introduction to PHP
developers have really beefed up the object-oriented features of PHP, resulting in both more
speed and added features.
First, the web browser sends an HTTP request to the web server, e.g., index.php.
Second, the PHP preprocessor that locates on the web server processes PHP code to
generate the HTML document.
Third, the web server sends the HTML document back to the web browser.
PHP Syntax
There are four ways to use PHP in your Webpage.
(1) Canonical PHP tags : The most universally effective PHP tag style is :
<?php...?>
If you use this style, you can be positive that your tags will always be correctly
interpreted.
(2) Short-open (SGML-style) tags : Short or short-open tags look like this :
<?...?>
If you want to use this type, then you have to follow below steps :
1. Open php.ini file
7 Chapter 1 : Introduction to PHP
<%...%>
If you want to use this type, then you have to follow below steps :
4. Open php.ini file
5. Set asp_tags attribute to On
6. Restart All Services.
(4) HTML script tags : HTML script tags look like this
PHP Comments
Comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.
Single line Comment : Single line comment is specified with ‘//’ or ‘#’
PHP Datatypes
Datatype determines which type of value a variable can contain.
1. Integer : Integer is a whole number which stores number without decimal point. It
stores positive and negative whole number. Integer can be represented in Decimal,
Octal and Hexadecimal. Default is Decimal. Octal number is represented with leading 0
and hexadecimal number is represented with leader 0x or 0X.
<?php
$a=12;
$b=012;
$c=0x12;
echo “$a”; //12
echo “<br>$b”; //10
echo “<br>$c”; //18
?>
2. Double /Float : A float (floating point number) is a number with a decimal
point or a number in exponential form. The PHP var_dump() function
returns the data type and value.
<?php
$a=3.14;
$b=1.2e3;
$c=1.2e-3;
echo $a; //3.14
echo "<br> $b"; //1200
echo "<br> $c"; //0.0012
var_dump($a); // float(3.14)
?>
4. String : It is a collection of characters. You can specify string in either single quote(‘ ‘) or
double quote (“ “). Single quoted string is printed as literal, but double quoted string
replace variable with their value.
<?php
$a=”KBSSC”;
9 Chapter 1 : Introduction to PHP
<?php
$x = "Hello world!";
$x = null;
var_dump($x); //NULL
?>
6. Array : An array stores multiple values in one single variable.
<?php
$cars = array("Volvo","BMW","Toyota");
print_r($cars); // Array ( [0] => Volvo [1] => BMW [2] => Toyota )
?>
7. Object : An object is an instance of the class.
<?php
class student {
public $rollno;
public $name;
public function display()
{
echo "Rollno : " . $this->rollno;
echo "<br> Name : ". $this->name;
}
}
$s=new student();
$s->rollno=1;
$s->name="BCA";
$s->display();
?>
8. Resource : The special resource type is not an actual data type. It is the storing of a
reference to functions and resources external to PHP.
A common example of using the resource data type is a database call.
10 Chapter 1 : Introduction to PHP
PHP Variable
Variables are "containers" for storing information. In PHP, a variable starts with the $ sign,
followed by the name of the variable.
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Scope of variable
Variable scope is known as its boundary within which it can be visible or accessed from code. In
other words, it is the context within which a variable is defined.
1. Local variable : A local scope is a restricted boundary of a variable within which code
block it is declared. That block can be a function, class or any conditional span. The
variable within this limited local scope is known as the local variable of that specific code
block.
<?php
$msg = “I am outside of function”;
function test()
{
$msg=”I am inside of function”;
echo $msg;
}
echo $msg;
test();
?>
2. Function parameter : Function parameters are declared after function name and inside
parenthesis. They are declared as typical variable.
<?php
$a=10;
$b=20;
11 Chapter 1 : Introduction to PHP
sum($a,$b);
function sum($x, $y)
{
$z=$x+$y;
echo $z;
}
?>
3. Global variable : As its name, the global scope provides widespread access to the
variable declared in this scope. Variables in global scope can be accessed from anywhere
from outside a function or class independent of its boundary.
PHP global variables can be defined by using global keyword. If we want to use global
variables inside a function, we have to prefix the global keyword with the variable.
<?php
$count = 10;
function display() {
global $count;
echo "$count <br/>"; //10
$count++;
}
display();
echo $count; //11
?>
4. Static variable : Static variables exist only in a local function, but it does not free its
memory after the program execution leaves the scope. We use the static keyword
before the variable to define a variable, and this variable is called as static variable.
<?php
function display()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
$num1++;
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
display(); // 4 7
display(); // 5 7
?>
12 Chapter 1 : Introduction to PHP
<?php
count_page();
function count_page()
{
static $p=0;
$p++;
Echo “<br> Page count : $pc”;
}
?>
PHP Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Conditional operators
String operators
Arithmetic Operators :
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
Assignment Operators:
There are following assignment operators supported by PHP language:
Operato
Description Example
r
Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal $x == $y True if $x is equal to $y
True if $x is equal to $y, and
=== Identical $x === $y
they are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
True if $x is not equal to $y, or
!== Not identical $x !== $y
they are not of the same type
> Greater than $x > $y True if $x is greater than $y
< Less than $x < $y True if $x is less than $y
Greater than or True if $x is greater than or
>= $x >= $y
equal to equal to $y
True if $x is less than or equal
<= Less than or equal to $x <= $y
to $y
Logical Operators
There are following logical operators supported by PHP language
Operato
Description Example
r
(A && B)
Called Logical AND operator. If both
&& True if a and b are true, otherwise it
the operands are non zero then
And is false.
then condition becomes true.
(A xor B)
xor Called Logical XOR Operator. True if either a or b is true but not
both, otherwise it is false.
Conditional Operator or ternary operator
Operato
Description Example
r
String Operator
The string operators are used to perform the operation on strings.
Operato
Description Example
r
1. Get method : GET is used to request data from a specified resource. GET is one of the
most common HTTP methods. Note that the query string (name/value pairs) is sent in
the URL of a GET request:
/test/demo_form.php?name1=value1&name2=value2
The get method is restricted to send up to 1024 characters only. Never use get method
if you want to send sensitive information like password, account number, etc.
16 Chapter 1 : Introduction to PHP
Get method cannot be used to send binary data like images, word document, etc. to the
server.
PHP $_GET is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="get".
Example 1 :
test_get.html
<html>
<body>
</body>
</html>
test_get.php
<?php
$a= $_GET[‘name’];
$b= $_GET[‘branch’];
echo “Name : $a”;
echo “<br>Branch : $b”;
?>
Example 2 :
get.html
<html>
<body>
<form method=get action=get.php>
Enter Name: <input type=text name=t1> <br>
Enter Branch: <input type=text name=t2> <br>
<input type=submit name=b1 value=Display>
</body>
</html>
get.php
<?php
$a= $_GET[‘t1’];
$b= $_GET[‘t2’];
17 Chapter 1 : Introduction to PHP
2. Post method : Post method is also used to send user information to the server. The post
method does not have any restriction on the data size to be sent. The post method can
also be used to send ASCII as well as binary data. Post method is secure than get
method.
PHP $_POST is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="post".
post.html
<html>
<body>
<form method=post action=post.php>
Enter Name: <input type=text name=t1> <br>
Enter Branch: <input type=text name=t2> <br>
<input type=submit name=b1 value=Display>
</body>
</html>
post.php
<?php
$a= $_POST[‘t1’];
$b= $_POST[‘t2’];
echo “Name : $a”;
echo “<br>Branch : $b”;
?>
$_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect form data after
submitting an HTML form with either method="post" or method=”get”.
request.html
<html>
<body>
<form method=post action=request.php>
Enter Name: <input type=text name=t1> <br>
Enter Branch: <input type=text name=t2> <br>
<input type=submit name=b1 value=Display>
</body>
</html>
request.php
<?php
$a= $_REQUEST[‘t1’];
$b= $_REQUEST[‘t2’];
echo “Name : $a”;
echo “<br>Branch : $b”;
?>
Conditional statements
When we want to test condition, conditional statements are used.
If statement :
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax :
if (condition)
{
statement(s)
19 Chapter 1 : Introduction to PHP
If…else Statement :
If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.
Syntax :
if (condition)
{
statement(s)
}
else
{
Statement(s)
}
If-else-if Statement :
The PHP if…else…if is a special statement used to combine multiple if..else statements. So, we
can check multiple conditions using this statement.
Syntax :
if (condition1)
{
//code to be executed if condition1 is true
}
elseif (condition2)
{
//code to be executed if condition2 is true
}
elseif (condition3)
{
//code to be executed if condition3 is true
}
else
20 Chapter 1 : Introduction to PHP
{
//code to be executed if all given conditions are false
}
Nested if Statement
The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.
Syntax :
if (condition)
{
if (condition)
{
statement(s)
}
else
{
Statement(s)
}
}
else
{
if (condition)
{
statement(s)
}
else
{
Statement(s)
}
}
Switch…case statement
PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.
21 Chapter 1 : Introduction to PHP
Syntax :
switch(expression)
{
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
// code to be executed if all cases are not matched;
}
Looping statements
Loops are used to execute the same block of code again and again, as long as a
certain condition is true.
1. For loop
2. While loop
3. Do…while loop
4. Foreach loop
For loop :
The for loop is used when you know in advance how many times the script should run.
Syntax:
for(initialization;condition; increment/decrement)
{
//statement(s)
}
Example :
<?php
22 Chapter 1 : Introduction to PHP
For($i=1;$i<=5;$i++)
{
Echo $i;
}
?>
While loop :
The while loop executes a block of code as long as the specified condition is true.
Syntax :
initialization
while (condition)
{
statement(s)
increment/decrement
}
Example :
<?php
$i=1;
while($i<6)
{
echo $i;
$i=$i+1;
}
?>
Do…while loop :
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:
23 Chapter 1 : Introduction to PHP
do
{
Statement(s)
Increment/decrement
} while (condition);
Example :
<?php
$i=1;
do
{
echo $i;
$i++;
}while($i<=5);
Foreach loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax :
For every loop iteration, the value of the current array element is assigned to $value and the
array pointer is moved by one, until it reaches the last array element.
24 Chapter 1 : Introduction to PHP
Example :
<?php
$colors = array("red", "green", "blue");
Output :
red
green
blue
<?php
$colors = array("red", "green", "blue");
Output :
0=red
1=green
2=blue
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.
array() is used to create an array of elements.
There are three different kind of arrays and each array value is accessed using an IDc which is
called array index.
25 Chapter 1 : Introduction to PHP
1. Numeric array or indexed 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.
array() is used to create an array of elements.
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
2. Associative array : 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.
To store the salaries of employees in an array, a numerically indexed array would not be
the best choice. Instead, we could use the employees names as the keys in our associative
array, and the value would be their respective salary.
<?php
/* First method to associate create array. */
$s = array("aaa" =>20000, "bbb" =>10000, "ccc" =>5000);
3. Multidimensional array : 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.
<?php
$marks = array
(
"aaa" => array (
"php" => 35,
"sql" => 30,
"java" => 39
),
$marks['bbb']['php']=30;
$marks['bbb']['sql']=32;
$marks['bbb']['java']=29;
$marks['ccc']['php']=31;
$marks['ccc']['sql']=22;
$marks['ccc']['java']=29;
?>