Notes of PHP
Notes of PHP
UNIT - 1
PHP Basics
PHP is a server-side scripting language. It is used to develop Static
websites or Dynamic websites or Web applications.
PHP stands for Hypertext Pre-processor, that earlier stood for Personal Home
Pages.
PHP scripts can only be interpreted on a server that has PHP installed.
The client computers accessing the PHP scripts require a web browser only.
A PHP file contains PHP tags and ends with the extension ".php".
Commonusesof PHP
¾ 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.
¾ We can add, delete and modify elements within our database through PHP.
¾ Access cookies variables and set cookies.
¾ Using PHP, you can restrict users to access some pages of your website.
¾ It can encrypt data.
History of PHP
Characteristics of PHP
There are many features given by PHP. All Features discussed below one by one.
Familiarity
Simplicity
Efficiency
Security
Flexibility
Open source
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
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 3+3¶V predefined
function set.
You can use a lot of third-party applications to secure data, allowing for securing
application.
Flexibility: -
PHP is a very flexible language because 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 on any device like mobile Phone,
tabs, laptops, PC and others because of PHP script execute on the server then
after sending to the browser of your device.
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
The variable $txt will hold the value Hello world! the variable $x
will hold the value 5, and the variable $y will hold the value 10.5.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive
name (age, car name, total volume).
Output Variables
¾ The PHP echo statement is often used to output data to the screen.
¾ The following example will show how to output text and a variable:
Example:
<?php
$txt = "Hello
World!"; echo
"Welcome To $txt!";
?>
Output:
Welcome To Hello World!
The following example will produce the same output as the example above:
<?php
$txt = "Hello World";
echo "Welcome To " . $txt. "!";
?>
Output: Welcome To Hello World!
Example:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo"<p>Variable x inside function is: $x</p>";
}
myTest();
Output:
Variable x inside function is:
Variable x outside function is: 5
A variable declared within a function has a LOCAL SCOPE and
can only be accessed within that function:
Example:
<?php
function myTest() {
$x = 5; // local scope
echo"<p>Variable x inside function is: $x</p>";
}
myTest();
Global Keyword
The global keyword is used to access a global variable from
within a function. To do this, use the global keyword before the
variables (inside the function):
Example:
<?php
$x = 5;
$y = 10;
functionmyTe
st(){ global
$x, $y;
$y = $x + $y;
}
myTest();
Example:
<?php
function
myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Output: 0 1 2
Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.
PHP String
A string is a sequence of characters, like "Hello world!". A string can
be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello
world!'; echo
$x;
echo"<br>";
echo $y; ?>
Output:
Hello World
Hello World
PHP Float
A float (floating point number) is a number with a decimal point or a
number in exponential form.
In the following example $x is a float. The PHP var_dump () function
returns the data type and value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
Output:
float (10.365)
PHP Boolean
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump ()
function returns the data type and value:
<?php
$cars =
array("Volvo","BMW","Toyo
ta"); var_dump($cars);
?>
Output
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota"
}
PHP Object
An object is a data type which stores data and information on how to
process that data. In PHP, an object must be explicitly declared. First we
must declare a class of object. For this, we use the class keyword.
<? php
class
Car {
function Car () {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object
properties echo
$herbie->model;
?>
Output: VW
var_dump(
$x);
?>
Output: NULL
PHP 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.
PHP Operators
Operators are used to perform operations on variables and values.
x=y x=y The left operand gets set to the value of the
expression on the right
x += y x=x+y Addition
x -= y x=x±y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
Comparison Operators
The PHP comparison operators are used to compare two values (number or
string):
or Or $x or $y True if either $x or
$y is true
True if either $x or
xor Xor $x xor
$y is true, but not
$y
both
|| Or $x || $y True if either $x or
$y is true
Concatenati
$txt1 .= $txt2 Appends $txt2 to
on
.= $txt1
assignment
PHP Array Operators
The PHP array operators are used to compare arrays.
Conditional statements are used to perform different actions based on different
conditions
UNIT 2
CONTROL STRUCTURE AND LOOPS
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is
less than 20:
Example
<?php
$t = date("H");
if ($t <"20") {
echo"Have a good day!";
}
?>
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;
}
The example below will output "Have a good day!" if the current time
is less than 20, and "Have a good night!" otherwise:
{
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
The example below will 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!":
Example
<?php
$t = date("H");
if ($t <"10") {
echo"Have a good morning!";
} elseif ($t <"20") {
echo"Have a good
day!";
} else {
echo"Have a good night!";
}
?>
executed.
Syntax
switch (n)
{
caselabel1:
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 execute when n is different from all label
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
<?php
$favcolor =
"red"; switch
($favcolor){
case ³UHG
HFKR³<RXU
favoritecolor is red!";
break;
case"blue":
echo"Your favoritecolor
is blue!"; break;
case"green":
echo"Your favoritecolor
is green!"; break;
default:
echo"Your favoritecolor is neither red, blue, nor green!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over
and over again in a row. Instead of adding several almost equal code-lines in a
script, we can use loops to perform a task like this.
¾ 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
¾ for each - loops through a block of code for each element in an array
The PHP while Loop
The while loop executes a block of code as long as the specified condition is
true.
Syntax
while (condition is true)
{
code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the
while loop will continue to run as long as $x is less than, or equal to 5 ($x <=
5). $x will increase by 1 each time the loop runs ($x++):
Example
<?php
$x = 1;
while($x <=
5) {
echo"The number is: $x <br>";
$x++;
}
?>
Output :
Syntax
do
{
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the
do while loop will write some output, and then increment the variable $x with
Output:
The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number
is: 5
Array
An array stores multiple values in one single variable:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
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";
Create an Array in
PHP
array();
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Associative arrays are arrays that use named keys that you
assign to them. There are two ways to create an associative
array:
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43"); or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43"); echo "Peter is " . $age['Peter'] .
" years old.";
?>
Example
<?php
$cars = array("Volvo", "BMW",
"Toyota"); sort($cars);
?>
The following example sorts the elements of the $numbers array in ascending
numerical
order:
Example
<?php
$numbers = array(4, 6, 2,
22, 11); sort($numbers);
?>
Sort Array in Descending Order - rsort()
The following example sorts the elements of the $cars array in descending
alphabetical
order:
Example
<?php
$cars = array("Volvo", "BMW",
"Toyota"); rsort($cars);
?>
Example
<?php
$numbers = array(4, 6, 2,
22, 11); rsort($numbers);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43"); asort($age);
?>
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43"); ksort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43"); arsort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43"); krsort($age);
?>
UNIT-III
PHP ± FUNCTIONS, OBJECTS AND ERRORS
You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.
7KHUHDUHWZRSDUWVZKLFKVKRXOGEHFOHDUWR\RXí
In fact you hardly need to create your own PHP function because there are already
more than 1000 of built-in library functions created for different area and you just need
to call them according to your requirement.
Please refer to PHP Function Reference for a complete set of useful functions.
Its very easy to create your own PHP function. Suppose you want to create a PHP
function which will simply write a simple message on your browser when you will call
it. Following example creates a function called writeMessage() and then calls it just
after creating it.
Note that while creating a function its name should start with keyword function and all
the PHP code should be put inside { and } braces as shown in the following example
below ±
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
</body>
</html>
7KLVZLOOGLVSOD\IROORZLQJUHVXOWí
PHP gives you option to pass your parameters inside a function. You can pass as many
as parameters your like. These parameters work like variables inside your function.
Following example takes two integer parameters and add them together and then print
them.
<html>
<head>
</head>
<body>
<?php
addFunction(10, 20);
?>
</body>
</html>
TKLVZLOOGLVSOD\IROORZLQJUHVXOWí
Any changes made to an argument in these cases will change the value of the original
variable. You can pass an argument by reference by adding an ampersand to the
variable name in either the function call or the function definition.
<html>
<head>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
function addSix(&$num) {
$num += 6;
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
?>
</body>
</html>
7KLVZLOOGLVSOD\IROORZLQJUHVXOWí
Original Value is 10
Original Value is 16
PHP Functions returning value
A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling
code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then
returns their sum to the calling program. Note that return keyword is used to return a
value from a function.
<html>
<head>
</head>
<body>
<?php
return $sum;
?>
</body>
</html>
7KLVZLOOGLVSOD\IROORZLQJUHVXOWí
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
</head>
<body>
<?php
print $param;
printMe("This is test");
printMe();
?>
</body>
</html>
7KLVZLOOSURGXFHIROORZLQJUHVXOWí
This is test
There are usually different types of error. In PHP, mainly four types of errors are
considered:
2. Fatal Error
3. Warning Error
4. Notice Error
A syntax error is a mistake in the syntax of source code, which can be done by
programmers due to their lack of concern or knowledge. It is also known as Parse
error. Compiler is used to catch the syntax error at compile time.
Fatal Error
A fatal error is another type of error, which is occurred due to the use of undefined
function. The PHP compiler understands the PHP code but also recognizes the
undefined function. This means that when a function is called without providing its
definition, the PHP compiler generates a fatal error.
Warning Error
A warning is generated when the programmer tries to include a missing file. The PHP
function calls that missing file which does not exist. The warning error does not
stop/prevent the execution of the program.
The main reason behind generating a warning error is to pass an incorrect number of
parameters to a function or to include a missing file
Notice Error
Notice error is same as warning error. When program contains something wrong, the
notice error occurs. But it allows/continue the execution of the program with a notice
error. Notice error does not prevent the execution of the code. For example - access to
undefined variable.
Objects in php
A class is defined by using the class keyword, followed by the name of the class and a
pair of curly braces ({}). All its properties and methods go inside the braces
<?php
class Fruit {
// code goes here...
}
?>
Classes are nothing without objects! We can create multiple objects from a class. Each
object has all the properties and methods defined in the class, but they will have
different property values.
In the example below, $apple and $banana are instances of the class Fruit:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
UNIT 4
WORKING WITH FORMS
HTML forms are used to send the user information to the server and returns the result
back to the browser. For example, if you want to get the details of visitors to your
website, and send them good thoughts, you can collect the user information by means
of form processing. Then, the information can be validated either at the client-side or
on the server-side. The final result is sent to the client through the respective web
browser. To create a HTML form, form tag should be used.
Attribute Description
It specifies the location to which the form data has to be sent when
action the form is submitted.
It specifies the encryption type for the form data when the form is
encType submitted.
It implies the server not to verify the form data when the form is
novalidate submitted.
Creating a simple HTML Form: All the form controls given above is designed by
using the input tag based on the type attribute of the tag. In the below script, when
the form is submitted, no event handling mechanism is done. Event handling refers to
the process done while the form is submitted. These event handling mechanisms can
be done by using javaScript or PHP. However, JavaScript provides only client-side
validation. Hence, we can use PHP for form processing.
Form Validation: Form validation is done to ensure that the user has provided the
relevant information. Basic validation can be done using HTML elements. For
example, in the above script, the email address text box is having a type value as
³HPDLO´ZKLFKSUHYHQWVWKHXVHUIURPHQWHULQJWKHLQFRUUHFWYDOXHIRUDQHPDLO(YHU\
form field in the above script is followed by a required attribute, which will intimate
the user not to leave any field empty before submitting the form. PHP methods and
arrays used in form processing are:
x isset(): This function is used to determine whether the variable or a form control is
having a value or not.
x $_GET[]: It is used the retrieve the information from the form control through the
parameters sent in the URL. It takes the attribute given in the url as the parameter.
x $_POST[]: It is used the retrieve the information from the form control through
the HTTP POST method. IT takes name attribute of corresponding form control as
the parameter.
x $_REQUEST[]: It is used to retrieve an information while using a database.
When and why we are using forms?
x Forms come in handy when developing flexible and dynamic applications that
accept user input.
x Forms can be used to edit already existing data from the database
Create a form
We will use HTML tags to create a form. Below is the minimal list of things you need
to create a form.
x 2SHQLQJDQGFORVLQJIRUPWDJVIRUP!«IRUP!
x Form submission type POST or GET
x Submission URL that will process the submitted data
x Input fields such as input boxes, text areas, buttons,checkboxes etc.
We can create and use forms in PHP. To get form data, we need to use PHP
superglobals $_GET and $_POST.
The form request may be get or post. To retrieve data from get request, we need to use
$_GET, for post request $_POST.
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.
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>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>