0% found this document useful (0 votes)
39 views

PHP - Introduction

Uploaded by

nandhuda21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

PHP - Introduction

Uploaded by

nandhuda21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

PHP | Introduction

The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a


server-side scripting language designed specifically for web development. It is
open-source which means it is free to download and use. It is very simple to
learn and use. The files have the extension “.php”.

Rasmus Lerdorf inspired the first version of PHP and participated in the later
versions. It is an interpreted language and it does not require a compiler.
 PHP code is executed in the server.
 It can be integrated with many databases such as Oracle, Microsoft SQL
Server, MySQL, PostgreSQL, Sybase, and Informix.
 It is powerful to hold a content management system like WordPress and can
be used to control user access.
 It supports main protocols like HTTP Basic, HTTP Digest, IMAP, FTP, and
others.
 Websites like www.facebook.com and www.yahoo.com are also built on
PHP.
 One of the main reasons behind this is that PHP can be easily embedded in
HTML files and HTML codes can also be written in a PHP file.
 The thing that differentiates PHP from the client-side language like HTML is,
that PHP codes are executed on the server whereas HTML codes are
directly rendered on the browser. PHP codes are first executed on the server
and then the result is returned to the browser.
 The only information that the client or browser knows is the result returned
after executing the PHP script on the server and not the actual PHP codes
present in the PHP file. Also, PHP files can support other client-side scripting
languages like CSS and JavaScript.

characteristics of PHP :

 Simple and fast


 Efficient
 Secured
 Flexible
 Cross-platform, it works with major operating systems like Windows, Linux,
and macOS.
 Open Source
 Powerful Library Support
 Database Connectivity
PHP Scripting:
<?php
PHP code goes here
?>
Example:
 HTML

<html>

<head>

<title>PHP Example</title>

</head>

<body>

<?php echo "Hello, World! This is PHP code";?>

</body>

</html>

Output:
Hello, World! This is PHP code

PHP Comments
PHP comments can be used to describe any line of code so that other developer can
understand the code easily. It can also be used to hide any code.
PHP supports single line and multi line comments. These comments are similar to C/C++
and Perl style (Unix shell style) comments.

PHP Single Line Comments


There are two ways to use single line comments in PHP.

o // (C++ style single line comment)


o # (Unix Shell style single line comment)

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. ?>

Output:

Welcome to PHP single line comments

PHP Multi Line Comments


In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within
/* */. Let's see a simple example of PHP multiple line comment.

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. ?>

Output:

Welcome to PHP multi line comment


PHP Operators
Operators are used to performing operations on some values. In other words, we can
describe operators as something that takes some values, performs some operation on them,
and gives a result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes
two values 1 and 2, performs an addition operation on them to give 3.
. Given below are the various groups of operators:
 Arithmetic Operators
 Logical or Relational Operators
 Comparison Operators
 Conditional or Ternary Operators
 Assignment Operators
 Spaceship Operators (Introduced in PHP 7)
 Array Operators
 Increment/Decrement Operators
 String Operators
Let us now learn about each of these operators in detail.
Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their
syntax and operations in PHP.

Operator Name Syntax Operation

+ Addition $x + $y Sum the operands

– Subtraction $x – $y Differences the operands

* Multiplication $x * $y Product of the operands

/ Division $x / $y The quotient of the operands

** Exponentiation $x ** $y $x raised to the power $y

% Modulus $x % $y The remainder of the operands

Note: The exponentiation has been introduced in PHP 5.6.


Logical or Relational Operators:
These are basically used to operate with conditional statements and expressions.
Conditional statements are based on conditions. Also, a condition can either be met or
cannot be met so the result of a conditional statement can either be true or false. Here are
the logical operators along with their syntax and operations in PHP.

Operator Name Syntax Operation

Logical $x and
and True if both the operands are true else false
AND $y

or Logical OR $x or $y True if either of the operands is true else false

Logical True if either of the operands is true and false if


xor $x xor $y
XOR both are true

Logical $x &&
&& True if both the operands are true else false
AND $y

|| Logical OR $x || $y True if either of the operands is true else false

Logical
! !$x True if $x is false
NOT

Comparison Operators: These operators are used to compare two elements and outputs
the result in boolean form. Here are the comparison operators along with their syntax and
operations in PHP.
Operator Name Syntax Operation

== Equal To $x == $y Returns True if both the operands are equal


Operator Name Syntax Operation

Returns True if both the operands are not


!= Not Equal To $x != $y
equal

Returns True if both the operands are


<> Not Equal To $x <> $y
unequal

$x === Returns True if both the operands are equal


=== Identical
$y and are of the same type

Returns True if both the operands are


!== Not Identical $x == $y
unequal and are of different types

< Less Than $x < $y Returns True if $x is less than $y

> Greater Than $x > $y Returns True if $x is greater than $y

Less Than or
<= $x <= $y Returns True if $x is less than or equal to $y
Equal To

Greater Than or Returns True if $x is greater than or equal to


>= $x >= $y
Equal To $y

Conditional or Ternary Operators:


These operators are used to compare two values and take either of the results
simultaneously, depending on whether the outcome is TRUE or FALSE. These are also
used as a shorthand notation for if…else statement that we will read in the article on
decision making.
Syntax:
$var = (condition)? value1 : value2;
Here, the condition will either evaluate as true or false. If the condition evaluates to True,
then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.

Operator Name Operation

If the condition is true? then $x : or else $y. This means that if the
?: Ternary condition is true then the left result of the colon is accepted otherwise
the result is on right.

Assignment Operators: These operators are used to assign values to different variables,
with or without mid-operations. Here are the assignment operators along with their
syntax and operations, that PHP provides for the operations.
Operator Name Syntax Operation

Operand on the left obtains the value of the


= Assign $x = $y
operand on the right

$x +=
+= Add then Assign Simple Addition same as $x = $x + $y
$y

-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y

$x *=
*= Multiply then Assign Simple product same as $x = $x * $y
$y

Divide then Assign


/= $x /= $y Simple division same as $x = $x / $y
(quotient)

Divide then Assign $x %=


%= Simple division same as $x = $x % $y
(remainder) $y

Array Operators: These operators are used in the case of arrays. Here are the array
operators along with their syntax and operations, that PHP provides for the array operation.
Operator Name Syntax Operation

+ Union $x + $y Union of both i.e., $x and $y

$x ==
== Equality Returns true if both has same key-value pair
$y

!= Inequality $x != $y Returns True if both are unequal

$x === Returns True if both have the same key-value pair in


=== Identity
$y the same order and of the same type

Non- $x !==
!== Returns True if both are not identical to each other
Identity $y

$x <>
<> Inequality Returns True if both are unequal
$y

Increment/Decrement Operators: These are called the unary operators as they work on
single operands. These are used to increment or decrement values.
Operator Name Syntax Operation

++ Pre-Increment ++$x First increments $x by one, then return $x

— Pre-Decrement –$x First decrements $x by one, then return $x

++ Post-Increment $x++ First returns $x, then increment it by one

— Post-Decrement $x– First returns $x, then decrement it by one

String Operators: This operator is used for the concatenation of 2 or more strings using
the concatenation operator (‘.’). We can also use the concatenating assignment operator
(‘.=’) to append the argument on the right side to the argument on the left side.
Operator Name Syntax Operation

. Concatenation $x.$y Concatenated $x and $y

Concatenation and First concatenates then assigns, same


.= $x.=$y
assignment as $x = $x.$y

Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship
operator or combined comparison operator is denoted by “<=>“. These operators are used
to compare values but instead of returning the boolean results, it returns integer values. If
both the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the
left operand is greater, it returns 1. The following table shows how it works in detail:

Operator Syntax Operation

$x < $y $x <=> $y Identical to -1 (right is greater)

$x > $y $x <=> $y Identical to 1 (left is greater)

$x <= $y $x <=> $y Identical to -1 (right is greater) or identical to 0 (if both are equal)

$x >= $y $x <=> $y Identical to 1 (if left is greater) or identical to 0 (if both are equal)

$x == $y $x <=> $y Identical to 0 (both are equal)

$x != $y $x <=> $y Not Identical to 0

PHP Regular Expressions


Regular expressions are commonly known as regex. These are nothing more than a
pattern or a sequence of characters, which describe a special search pattern as text string.
Regular expression allows you to search a specific string inside another string. Even we
can replace one string by another string and also split a string into multiple chunks. They
use arithmetic operators (+, -, ^) to create complex expressions.

By default, regular expressions are case sensitive.

PHP Primitives
Data Types define the type of data a variable can store. PHP allows eight different types
of data types. All of them are discussed below. There are pre-defined, user-defined, and
special data types.
The predefined data types are:
 Boolean
 Integer
 Double
 String
The user-defined (compound) data types are:
 Array
 Objects
The special data types are:
 NULL
 resource
The first five are called simple data types and the last three are compound data types:

1. Integer: Integers hold only whole numbers including positive and negative numbers,
i.e., numbers without fractional part or decimal point. They can be decimal (base 10),
octal (base 8), or hexadecimal (base 16). The default base is decimal (base 10). The octal
integers can be declared with leading 0 and the hexadecimal can be declared with leading
0x. The range of integers must lie between -2^31 to 2^31.

2. Double: Can hold numbers containing fractional or decimal parts including positive
and negative numbers or a number in exponential form. By default, the variables add a
minimum number of decimal places. The Double data type is the same as a float as
floating-point numbers or real numbers.

3. String: Hold letters or any alphabets, even numbers are included. These are written
within double quotes during declaration. The strings can also be written within single
quotes, but they will be treated differently while printing variables. To clarify this look at
the example below.
4. Boolean: Boolean data types are used in conditional testing. Hold only two values,
either TRUE(1) or FALSE(0). Successful events will return true and unsuccessful events
return false. NULL type values are also treated as false in Boolean. Apart from NULL, 0
is also considered false in boolean. If a string is empty then it is also considered false in
boolean data type.
5. Array: Array is a compound data type that can store multiple values of the same data
type. Below is an example of an array of integers. It combines a series of data that are
related together.

6. Objects: Objects are defined as instances of user-defined classes that can hold both
values and functions and information for data processing specific to the class. This is an
advanced topic and will be discussed in detail in further articles. When the objects are
created, they inherit all the properties and behaviours from the class, having different
values for all the properties.
Objects are explicitly declared and created from the new keyword
7. NULL: These are special types of variables that can hold only one value i.e., NULL.
We follow the convention of writing it in capital form, but it’s case-sensitive. If a
variable is created without a value or no value, it is automatically assigned a value of
NULL. It is written in capital letters.
8. Resources: Resources in PHP are not an exact data type. These are basically used to
store references to some function call or to external PHP resources. For example,
consider a database call. This is an external resource. Resource variables hold special
handles for files and database connection.

PHP | Variables
Variables in a program are used to store some values or data that can be used later in a
program. The variables are also like containers that store character values, numeric
values, memory addresses, and strings. PHP has its own way of declaring and storing
variables.
There are a few rules, that need to be followed and facts that need to be kept in mind
while dealing with variables in PHP:
 Any variables declared in PHP must begin with a dollar sign ($), followed by the
variable name.
 A variable can have long descriptive names (like $factorial, $even_nos) or short
names (like $n or $f or $x)
 A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-
z’, ‘A-Z’, ‘0-9, and ‘_’) in their name. Even it cannot start with a number.
 A constant is used as a variable for a simple value that cannot be changed. It is also
case-sensitive.
 Assignment of variables is done with the assignment operator, “equal to (=)”. The
variable names are on the left of equal and the expression or values are to the right of
the assignment operator ‘=’.
 One must keep in mind that variable names in PHP names must start with a letter or
underscore and no numbers.
 PHP is a loosely typed language, and we do not require to declare the data types of
variables, rather PHP assumes it automatically by analyzing the values. The same
happens while conversion. No variables are declared before they are used. It
automatically converts types from one type to another whenever required.
 PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.
Data types used by PHP to declare or construct variables:
 Integers
 Doubles
 NULL
 Strings
 Booleans
 Arrays
 Objects
 Resources
Variable Scopes
Scope of a variable is defined as its extent in a program within which it can be
accessed, i.e. the scope of a variable is the portion of the program within which
it is visible or can be accessed.
Depending on the scopes, PHP has three variable scopes:

 Local variables: The variables declared within a function are called local
variables to that function and have their scope only in that particular function.
In simple words, it cannot be accessed outside that function. Any declaration
of a variable outside the function with the same name as that of the one
within the function is a completely different variable. We will learn about
functions in detail in later articles. For now, consider a function as a block of
statements.

 Global variables: The variables declared outside a function are called


global variables. These variables can be accessed directly outside a
function. To get access within a function we need to use the “global”
keyword before the variable to refer to the global variable.

Static variable: It is the characteristic of PHP to delete the variable, once it


completes its execution and the memory is freed. But sometimes we need to
store the variables even after the completion of function execution. To do this
we use the static keywords and the variables are then called static
variables. PHP associates a data type depending on the value for the variable.
You must have noticed that $num regularly increments even after the first
function call but $sum doesn’t. This is because $sum is not static, and its
memory is freed after the execution of the first function call.

Variable Variables:-
 PHP allows us to use dynamic variable names, called variable variables.
 Variable variables are simply variables whose names are dynamically
created by another variable’s value.

PHP control statements


PHP if else statement is used to test condition. There are various ways to use if statement
in PHP.

o if
o if-else
o if-else-if
o nested if

PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true.

If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.

Syntax

Play Video

1. if(condition){
2. //code to be executed
3. }

Flowchart
Example

1. <?php
2. $num=12;
3. if($num<100){
4. echo "$num is less than 100";
5. }
6. ?>

Output:

12 is less than 100

PHP If-else Statement


PHP if-else statement is executed whether condition is true or false.
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

1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }

Flowchart

Example
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>

Output:

12 is even number

PHP 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

1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else{
9. //code to be executed if all given conditions are false
10. }

Flowchart
Example

1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail";
5. }
6. else if ($marks>=34 && $marks<50) {
7. echo "D grade";
8. }
9. else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>

Output:

B Grade

PHP 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

1. if (condition) {
2. //code to be executed if condition is true
3. if (condition) {
4. //code to be executed if condition is true
5. }
6. }

Flowchart
PHP - Arrays
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.
 Numeric array − An array with a numeric index. Values are stored and accessed
in linear fashion.
 Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
 Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices
NOTE − Built-in array functions is given in function reference PHP Array Functions

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.
Here we have used array() function to create array. This function is explained in function
reference.
Live Demo

<html>
<body>

<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>

</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

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.
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.
NOTE − Don't keep associative array inside double quote while printing otherwise it would
not return any value.
Example
Live Demo

<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>
</html>
This will produce the following result −
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

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.

PHP - Functions
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and
returns a value.
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.
There are two parts which should be clear to you −

 Creating a PHP Function


 Calling a PHP Function
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.
Creating PHP Function
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 −
Live Demo

<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!";
}

/* Calling a PHP Function */


writeMessage();
?>

</body>
</html>
This will display following result −
You are really a nice person, Have a nice time!

PHP Functions with Parameters


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.
Live Demo

<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

</body>
</html>
This will display following result −
Sum of the two numbers is : 30

Passing Arguments by Reference


It is possible to pass arguments to functions by reference. This means that a reference to
the variable is manipulated by the function rather than a copy of the variable's value.
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.
Following example depicts both the cases.
Live Demo

<html>

<head>
<title>Passing Argument by Reference</title>
</head>

<body>

<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

</body>
</html>
This will display following result −
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.
Live Demo

<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>
</body>
</html>
This will display following result −
Returned value from the function : 30

Form Processing
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.
Attributes of Form Tag:
Attribute Description

name or It specifies the name of the form and is used to identify individual
id forms.

It specifies the location to which the form data has to be sent when
action
the form is submitted.

It specifies the HTTP method that is to be used when the form is


submitted. The possible values are get and post. If get method is
method
used, the form data are visible to the users in the url. Default HTTP
method is get.

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.

Controls used in forms: Form processing contains a set of controls through


which the client and server can communicate and share information. The
controls used in forms are:
 Textbox: Textbox allows the user to provide single-line input, which can be
used for getting values such as names, search menu and etc.
 Textarea: Textarea allows the user to provide multi-line input, which can be
used for getting values such as an address, message etc.
 DropDown: Dropdown or combobox allows the user to provide select a
value from a list of values.
 Radio Buttons: Radio buttons allow the user to select only one option from
the given set of options.
 CheckBox: Checkbox allows the user to select multiple options from the set
of given options.
 Buttons: Buttons are the clickable controls that can be used to submit the
form.
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 “email”, which prevents the user from entering the incorrect value for
an email. Every 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:
 isset(): This function is used to determine whether the variable or a form
control is having a value or not.
 $_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.
 $_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.
 $_REQUEST[]: It is used to retrieve an information while using a database.
Form Processing using PHP: Above HTML script is rewritten using the above
mentioned functions and array. The rewritten script validates all the form fields
and if there are no errors, it displays the received information in a tabular form.
 Example:

<?php

if (isset($_POST['submit']))

if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname']))
||
(!isset($_POST['address'])) || (!isset($_POST['emailaddress']))
||

(!isset($_POST['password'])) || (!isset($_POST['gender'])))

$error = "*" . "Please fill all the required fields";

else

$firstname = $_POST['firstname'];

$lastname = $_POST['lastname'];

$address = $_POST['address'];

$emailaddress = $_POST['emailaddress'];

$password = $_POST['password'];

$gender = $_POST['gender'];

?>

<html>

<head>

<title>Simple Form Processing</title>


</head>

<body>

<h1>Form Processing using PHP</h1>

<fieldset>

<form id="form1" method="post" action="form.php">

<?php

if (isset($_POST['submit']))

if (isset($error))

echo "<p style='color:red;'>"

. $error . "</p>";

?>

FirstName:

<input type="text" name="firstname"/>

<span style="color:red;">*</span>
<br>

<br>

Last Name:

<input type="text" name="lastname"/>

<span style="color:red;">*</span>

<br>

<br>

Address:

<input type="text" name="address"/>

<span style="color:red;">*</span>

<br>

<br>

Email:

<input type="email" name="emailaddress"/>

<span style="color:red;">*</span>

<br>

<br>

Password:

<input type="password" name="password"/>

<span style="color:red;">*</span>
<br>

<br>

Gender:

<input type="radio"

value="Male"

name="gender"> Male

<input type="radio"

value="Female"

name="gender">Female

<br>

<br>

<input type="submit" value="Submit" name="submit" />

</form>

</fieldset>

<?php

if(isset($_POST['submit']))

if(!isset($error))

echo"<h1>INPUT RECEIVED</h1><br>";
echo "<table border='1'>";

echo "<thead>";

echo "<th>Parameter</th>";

echo "<th>Value</th>";

echo "</thead>";

echo "<tr>";

echo "<td>First Name</td>";

echo "<td>".$firstname."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Last Name</td>";

echo "<td>".$lastname."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Address</td>";

echo "<td>".$address."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Email Address</td>";

echo "<td>" .$emailaddress."</td>";


echo "</tr>";

echo "<tr>";

echo "<td>Password</td>";

echo "<td>".$password."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Gender</td>";

echo "<td>".$gender."</td>";

echo "</tr>";

echo "</table>";

?>

</body>

</html>
 Output:

PHP File Handling


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

PHP Open File - fopen()


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

Syntax

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $c
ontext ]] )

Example

Play Video

1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>
Click me for more details...
PHP Close File - fclose()
The PHP fclose() function is used to close an open file pointer.

Syntax

1. ool fclose ( resource $handle )

Example

1. <?php
2. fclose($handle);
3. ?>

PHP Read File - fread()


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

Syntax

1. string fread ( resource $handle , int $length )

Example

1. <?php
2. $filename = "c:\\myfile.txt";
3. $handle = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($handle, filesize($filename));//read file
6.
7. echo $contents;//printing data of file
8. fclose($handle);//close file
9. ?>

Output

hello php file


Click me for more details...
PHP Write File - fwrite()
The PHP fwrite() function is used to write content of the string into file.

Syntax

1. int fwrite ( resource $handle , string $string [, int $length ] )

Example

1. <?php
2. $fp = fopen('data.txt', 'w');//open file in write mode
3. fwrite($fp, 'hello ');
4. fwrite($fp, 'php file');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>

Output

File written successfully


Click me for more details...

PHP Delete File - unlink()


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

Syntax

1. bool unlink ( string $filename [, resource $context ] )

Example

1. <?php
2. unlink('data.txt');
3.
4. echo "File deleted successfully";
5. ?>

Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the web server
stores on the client computer. They are typically used to keep track of information
such as a username that the site can retrieve to personalize the page when the
user visits the website next time. A cookie can only be read from the domain that
it has been issued from. Cookies are usually set in an HTTP header but
JavaScript can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used.
The setcookie() function needs to be called prior to any output generated by the
script otherwise the cookie will not be set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which
are:
 Name: It is used to set the name of the cookie.
 Value: It is used to set the value of the cookie.
 Expire: It is used to set the expiry timestamp of the cookie after which the
cookie can’t be accessed.
 Path: It is used to specify the path on the server for which the cookie will be
available.
 Domain: It is used to specify the domain for which the cookie is available.
 Security: It is used to indicate that the cookie should be sent only if a secure
HTTPS connection exists.
Below are some operations that can be performed on Cookies in PHP:
 Creating Cookies: Creating a cookie named Auction_Item and assigning the
value Luxury Car to it. The cookie will expire after 2 days(2 days * 24 hours *
60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
 PHP

<!DOCTYPE html>
<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

echo "cookie is created."

?>

<p>

<strong>Note:</strong>

You might have to reload the

page to see the value of the cookie.

</p>

</body>

</html>

Note: Only the name argument in the setcookie() function is mandatory. To skip
an argument, the argument can be replaced by an empty string(“”).
Output:

Cookie creation in PHP


A cookie in PHP is a small file with a maximum size of 4KB that the web server
stores on the client computer. They are typically used to keep track of information
such as a username that the site can retrieve to personalize the page when the
user visits the website next time. A cookie can only be read from the domain that
it has been issued from. Cookies are usually set in an HTTP header but
JavaScript can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used.
The setcookie() function needs to be called prior to any output generated by the
script otherwise the cookie will not be set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which
are:
 Name: It is used to set the name of the cookie.
 Value: It is used to set the value of the cookie.
 Expire: It is used to set the expiry timestamp of the cookie after which the
cookie can’t be accessed.
 Path: It is used to specify the path on the server for which the cookie will be
available.
 Domain: It is used to specify the domain for which the cookie is available.
 Security: It is used to indicate that the cookie should be sent only if a secure
HTTPS connection exists.
Below are some operations that can be performed on Cookies in PHP:
 Creating Cookies: Creating a cookie named Auction_Item and assigning the
value Luxury Car to it. The cookie will expire after 2 days(2 days * 24 hours *
60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
 PHP

<!DOCTYPE html>

<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>
<body>

<?php

echo "cookie is created."

?>

<p>

<strong>Note:</strong>

You might have to reload the

page to see the value of the cookie.

</p>

</body>

</html>

Note: Only the name argument in the setcookie() function is mandatory. To skip
an argument, the argument can be replaced by an empty string(“”).
Output:

Cookie creation in PHP

PHP Session
PHP session is used to store and pass information from one page to another temporarily
(until user close the website).
PHP session technique is widely used in shopping websites where we need to store and
pass cart information e.g. username, product code, product name, product price etc from
one page to another.

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

PHP session_start() function


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

Play Video

Syntax

1. bool session_start ( void )

Example

1. session_start();

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

1. $_SESSION["user"] = "Sachin";

Example: Get information

1. echo $_SESSION["user"];

PHP Session Example


File: session1.php

1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. $_SESSION["user"] = "Sachin";
8. echo "Session information are set successfully.<br/>";
9. ?>
10. <a href="session2.php">Visit next page</a>
11. </body>
12. </html>
File: session2.php

1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. echo "User is: ".$_SESSION["user"];
8. ?>
9. </body>
10. </html>
PHP Session Counter Example
File: sessioncounter.php

1. <?php
2. session_start();
3.
4. if (!isset($_SESSION['counter'])) {
5. $_SESSION['counter'] = 1;
6. } else {
7. $_SESSION['counter']++;
8. }
9. echo ("Page Views: ".$_SESSION['counter']);
10. ?>

PHP Destroying Session


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

File: session3.php

1. <?php
2. session_start();
3. session_destroy();
4. ?>

Database connection
The collection of related data is called a database. XAMPP stands for cross-platform,
Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for
website development.
Requirements: XAMPP web server procedure:
 Start XAMPP server by starting Apache and MySQL.
 Write PHP script for connecting to XAMPP.
 Run it in the local browser.
 Database is successfully created which is based on the PHP code.
In PHP, we can connect to the database using XAMPP web server by using the following
path.
"localhost/phpmyadmin"
Steps in Detail:
 Open XAMPP and start running Apache, MySQL and FileZilla

 Now open your PHP file and write your PHP code to create database and a table in
your database.
PHP code to create a database:
 PHP

<?php

// Server name must be localhost

$servername = "localhost";

// In my case, user name will be root


$username = "root";

// Password is empty

$password = "";

// Creating a connection

$conn = new mysqli($servername,

$username, $password);

// Check connection

if ($conn->connect_error) {

die("Connection failure: "

. $conn->connect_error);

// Creating a database named geekdata

$sql = "CREATE DATABASE geekdata";

if ($conn->query($sql) === TRUE) {

echo "Database with name geekdata";

} else {
echo "Error: " . $conn->error;

// Closing connection

$conn->close();

?>

 Save the file as “data.php” in htdocs folder under XAMPP folder.

 Then open your web browser and type localhost/data.php

Finally the database is created and connected to PHP.


If you want to see your database, just type localhost/phpmyadmin in the web browser and
the database can be found.

You might also like