Download as pdf or txt
Download as pdf or txt
You are on page 1of 189

Prepared

by
A.kiran Kumar
CMRTC
Assistant Professor
UNIT- I

Introduction to PHP: Declaring variables, data types, arrays, strings, operators,


expressions, control structures, functions, Reading data from web form controls like text boxes,
radio buttons,
lists etc., Handling File Uploads. Connecting to database (MySQL as reference), executing simple
queries,
handling results, Handling sessions and cookies
File Handling in PHP: File operations like opening, closing, reading, writing, appending, deleting
etc.
on text and binary files, listing directories.
What is PHP used for & Market share
In terms of market share, there are over 20 million websites and application on the internet
developed using PHP scripting language.
PHP is the most popular scripting language on the web. Without PHP
Facebook, Yahoo, Google wouldn’t have exist
Prerequisite
Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript. So, learn
these technologies for better implementation of PHP.
HTML - HTML is used to design static webpage.
CSS - CSS helps to make the webpage content more effective and attractive.
JavaScript - JavaScript is used to design an interactive website.
What is scripting language
A scripting language is a language that interprets scripts at runtime.
The code is usually executed without compiling.
The purpose of the scripts is usually to enhance the performance or perform routine tasks for an
application.
Server side scripts are interpreted on the server while client side scripts are interpreted by the
client application.
PHP is a server side script that is interpreted on the server while JavaScript is an example of a
client side script that is interpreted by the client browser.
Both PHP and JavaScript can be embedded into HTML pages.
What is PHP?
 PHP is a server side scripting language. PHP 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.
 A PHP file contains PHP tags and ends with the extension “.php”.
 It is open-source which means it is free to download and use.
PHP is one of the most widely used server side scripting language for web development.
 Popular websites like Facebook, Yahoo, Wikipedia etc are developed using PHP.
 PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995.
 you can run PHP script from the command line to perform administrative tasks like sending
emails and generating PDF files.
  PHP 7.4.0 is the latest version of PHP, which was released on 28 November.
PHP:Imp points
 PHP is an Interpreted language, hence it doesn't need a compiler.
 To run and execute PHP code, we need a Web server on which PHP must be installed.
 PHP is a server side scripting language, which means that PHP is executed on the server and
the result is sent to the browser in plain HTML.
 PHP is open-source which means it is free to download and use.
 PHP can be embedded into HTML.
 PHP is an object-oriented language.
 PHP is simple and easy to learn language.

 It is faster than other scripting language e.g. asp and jsp. 


 You can use PHP with all leading web servers such as Nginx, OpenBSD, and Apache. Some
cloud environments also support PHP like Microsoft Azure and Amazon AWS.
 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.
What is a PHP File?
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code.
 PHP code is executed on the server, and the result is returned to the browser as plain HTML.
 PHP files have extension ".php“.
You can create PHP files without any html tags and that is called Pure PHP file .
The server interprets the PHP code and outputs the results as HTML code to the web browsers.
In order for the server to identify the PHP code from the HTML code, we must always enclose
the PHP code in PHP tags.
A PHP tag starts with the less than symbol followed by the question mark and then the words
“php”.
PHP is a case sensitive language, “VAR” is not the same as “var”.
How PHP Works
•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.
What's new in PHP 7
PHP 7 is much faster than the previous popular stable release (PHP 5.6)
PHP 7 has improved Error Handling
PHP 7 supports stricter Type Declarations for function arguments
PHP 7 supports new operators (like the spaceship operator: <=>)
Why use PHP or Uses of PHP
PHP is a server-side scripting language, which is used to design the dynamic web applications
with MySQL database.
PHP is that it supports many databases, such as MySQL, PostgreSQL, db2, Oracle Database, and
MongoDB.
•PHP can handle the forms, such as - collect the data from users using forms, save it into the
database, and return useful information to the user. Ex: Registration form.
•You add, delete, modify elements within your database through PHP.
•You can create sessions in PHP as well as session tracking for the website.
•It can access cookies variable and also set cookies.
•It helps to encrypt the data and apply validation.
•PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.
•Using PHP language, you can control the user to access some pages of your website.
•As PHP is easy to install and set up, this is the main reason why PHP is the best language to
learn.
PHP Features
Performance:
PHP script is executed much faster than scripts such as JSP and ASP. PHP uses its own memory,
so the server workload and loading time is automatically reduced.
Open Source:
PHP source code and software are freely available on the web without paying any cost.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it. PHP Syntax
is C-Like.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.
Database Support: PHP supports all the leading databases such as MySQL, SQLite, PostgreSQL,
db2, Oracle Database, and MongoDB. etc.
Error Reporting :
PHP has predefined error reporting constants to generate an error notice or warning at runtime.
Example: E_ERROR, E_WARNING etc.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the
time of execution based on the type of data and its value.
Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to prevent
threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same work in
a few lines of code.
A Helpful PHP Community:
It has a large community of developers who regularly updates documentation, tutorials, online help,
and FAQs.
PHP echo and print Statements
 echo and print are more or less the same. They are both used to output data to the screen.
 The differences between PHP echo and print
 echo has no return value while print has a return value of 1 so it can be used in expressions.
 echo can take multiple parameters (although such usage is rare) while print can take one
argument.
 echo is marginally faster than print.
Basic Syntax of PHP

 PHP code is start with <?php and ends with ?>


 Every PHP statements end with a semicolon (;).
 PHP code save with .php extension.
 PHP contain some HTML tag and PHP code.
 You can place PHP code any where in your document.

PHP Syntax

<?php

// PHP code goes here

?>
PHP Hello world Ex
The program shown below is a basic PHP application that outputs the words “Hello World!”
When viewed in a web browser.

<?php
echo "Hello world";
?>
Ex To demonstrate inserting php code in html

<html>

<body>

<h1>This is my first PHP code</h1>

<?php

echo "Hello CMR";

?>

</body>

</html>
Set Up PHP on Your Own PC
However, if your server does not support PHP, you must:
•install a web server
•install PHP
•install a database, such as MySQL
Webserver To install in your PC or Laptop
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems.
•WAMP for Windows
•LAMP for Linux
•XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform:
PHP variables 

Variable: A variable is the name given to the memory location used to store values at the time
of program execution.

PHP is loosely typed language that’s why we can store variables without data types. PHP
automatically converts the variable to the correct data type, depending on its value.

Syntax :

$variablename=value;
Rules for PHP variables:

 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 or special symbols.
 A variable name cannot contain spaces.
 A variable name can only contain alphabets, numbers and underscore symbol _.
 Variable names are case-sensitive ($age and $AGE are two different variables)
PHP Variable: Declaring string, integer, and float
<?php  
$str="hello string";  
$x=200;  
$y=44.6;  
echo "string is: $str <br/>";  
echo "integer is: $x <br/>";  
echo "float is: $y <br/>";  
?>  
PHP Variable Scope:
Variable Scope: The scope of a variable is the portion of the program within
which it is defined and can be accessed." 
Depending on the scopes, PHP has three variable scopes: 
1. Local Variable
2. Global variable
3. Static variable
Local Variable: The variables declared within a function are called local variables to that function and
have their scope only in that particular function.

Local Variables we can access within the function where we declared. we cannot access outside the
function.

<?php

function local_var()

$num = 10; // local variable

echo “variable num inside function : $num \n";

local_var();

?> output: variable num inside function:10


Global variable: 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.

<?php

$num = 10;

function global_var()

global $num;

echo "Variable num inside function : $num \n";

}
Static variables: It is a feature of PHP to delete the variable, once it completes its execution and memory
is freed. Sometimes we need to store a variable even after completion of function execution.

The variable which is declared with the static keyword is called static variable.

Static variables can maintain previous values .We can assign the values only one time in to static variable.

output: 6373
PHP DATA TYPES
Data type: Types define the type of data a variable can store.
PHP allows eight different types of data types
PHP supports 8 primitive data types that can be categorized further in 3 types:
1.Scalar Types (predefined)
2.Compound Types (user-defined)
3.Special Types
Scalar Types
A variable is a scalar when it holds a single value of the type integer, float, string, or boolean.
There are 4 scalar data types in PHP.
1.Integer:
Integers hold only whole numbers including positive and negative numbers,
i.e., numbers without fractional part or decimal point.

Note: Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Ex: to illustrate integer data type
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>

Output: Decimal number: 34


Octal number: 163
HexaDecimal number: 69
2.float:
A floating-point number is a number with a decimal point.
It can hold numbers with a fractional or decimal point, including a negative or positive sign.
<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;
echo “sum is :$sum”;
?>
Output: sum is :705.11
Note:The Double data type is the same as a float as floating-point numbers or real numbers.
3.boolean:Boolean data types are used in conditional testing. Hold only two values, either
TRUE(1) or FALSE(0)
<?php
if(TRUE)
echo "Today you have WT Class";
if(FALSE)
echo "Today you don’t have WT Class";
?> output: Today you have WT Class
4.string :
A string is a sequence of characters.
A string can be any text inside quotes. You can use single or double quotes
<?php
$name = "CMRTC";
echo "The name of the clg is $name";
?> output: The name of the clg is CMRTC
Compound Types
It can hold multiple values. There are 2 compound data types in PHP.
1.array:Array is a compound data type that can store multiple values of the same data type.
<?php
$arr = array( 10, 20 , 30);
echo "First : $arr[0]\n";
echo "Second : $arr[1]\n";
echo "Third : $arr[2]\n\n";
?>
Output:First : 10 Second : 20 Third : 30
2.object:
Objects is the instance of the class that can store both values and functions.
Object means allocating memory to instance variables.
An object has properties.
For example, a student object may have the first name, last name, and age properties.
An object also has behaviors, which are known as methods.
For example, a student object can have a method like read(),write(),talk() etc
Syntax:
<?php  
class MyClass  
{  
        // Class properties and methods 
}  
$obj = new MyClass;  // creating the object
  $obj->functionname(); //calling a function with the help of object here we use arrow
operator
 ?>  
Ex to demonstrate object
<?php
class bike
{
function model()
{
$model_name = "Royal Enfield";
echo "Bike Model: $model_name”;
}
}
$obj = new bike();
$obj -> model();
?>
Output: Bike Model: Royal Enfield
Special types
PHP has two special types: null and resource
Null
The null type has one value called null that represents a variable with no value.
There is a convention of writing it in capital letters as it is case sensitive
<?php
$nu = NULL;
echo $nu; // this will return no output
?> output: No output display
Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function
calls or
references to external PHP resources.
For example - a database call. It is an external resource.
A common example of using the resource data type is a database call.
Operator: Operator is used to perform operations on PHP variables and simple values.
Ex:$num=10+20;//+ is the operator and 10,20 are operands
PHP Operators :
In PHP there are total 7 types of operators, they are:
Arithmetic Operators
Assignment Operators
Comparison Operators
Increment/Decrement Operators
Logical Operators
String Operators
Array Operators
Execution Operators
Error Control Operators
Bitwise Operators
1. Arithmetic Operators are used to perform the mathematical manipulations on variables.
They include Addition, Subtraction, Multiplication, Division, Modulus and Exponential.
<?php
$x = 78; $y = 12;
Operator Name Example
echo "Addition : ",$x+$y,"</br>";
+ Addition $a + $b
echo "Subtraction : ",$x-$y,"</br>";
echo "Multiplication : ",$x*$y,"</br>"; - Subtraction $a - $b
echo "Division : ",$x/$y,"</br>";
* Multiplication $a * $b
echo "Modulus : ",$x%$y,"</br>";
echo "Exponential : ",$x^$y,"</br>"; / Division $a / $b

?> % Modulus $a % $b

** Exponentiatio $a ** $b
n
2 Assignment operators
 Assignment operators are used to assign values to variables.
The basic assignment operator is "=".
The variable on the left side of the operand is updated with the value on the right side.
EX: Operator Name Example
= Assign $a = $b
<?php
$x = 20;
+= Add then Assign $a += $b
$y=10;
-= Subtract then Assign $a -= $b
$x += 100;
$x-=100; *= Multiply then Assign $a *= $b

$y*=10
/= Divide then Assign $a /= $b
echo $y; (quotient)

echo $x; %= Divide then Assign $a %= $b


(remainder)
?>
3.Comparison operators:
The Comparison operators are used to compare two values (numbers or strings):
Ex: Operator Name Example Explanation
== Equal $a == $b Return TRUE if $a is
<?php equal to $b
=== Identical $a === $b Return TRUE if $a is
$x = 100; equal to $b, and they
are of same data type
$y = 10; !== Not identical $a !== $b Return TRUE if $a is not
equal to $b, and they
var_dump($x == $y); are not of same data
type
var_dump($x > $y); < Less than $a < $b Return TRUE if $a is
less than $b
var_dump($x===$y); > Greater than $a > $b Return TRUE if $a is
greater than $b
var_dump($x!=$y); <= Less than or $a <= $b Return TRUE if $a is
equal to less than or equal $b
var_dump($x<=$y); >= Greater than or $a >= $b Return TRUE if $a is
?> equal to greater than or equal
$b
4. The increment and decrement operators
The increment and decrement operators are used to increase and decrease the value of a
variable. These operators are unary operators, i.e they require only one
operand.
These operators are very useful and handy when use loops or when we have
simply increment any value by one in our program/script.
Ex:$x++;
<?php
Operator Name Description
$x = 78;
++$x Pre-increment Increments $x by one, then returns $x
echo ++$x; $x++ Post- Returns $x, then increments $x by one
echo "<br>"; increment
echo $x++; --$x Pre- Decrements $x by one, then returns $x
decrement
echo "<br>"; $x-- Post- Returns $x, then decrements $x by one
echo $x; decrement

?>
Logical operators
5.Logical operators are generally used when any action depends on two or more conditions.
The logical operators are used to perform bit-level operations on operands.
<?php
$x = 78; perator Name Example Explanation
and And $a and $b Return TRUE if
$y = 12; both $a and $b
are true

if ($x == 78 and $y == 12) Or Or $a or $b Return TRUE if


either $a or $b is
true
{
xor Xor $a xor $b Return TRUE if
echo "The value is parses correctly"; either $ or $b is
true but not both

} ! Not ! $a Return TRUE if


$a is not true
?> && And $a && $b Return TRUE if
either $a and $b
are true
|| Or $a || $b Return TRUE if
either $a or $b is
true
6.String Operators
The string operators are used to perform the operation on strings. There are only two
string operators
<?php
$a = "web";
$b = "Technologies";
Name Operator What does it Example
// concatenating $a and $b do?
echo $a.$b; Concatenation . (a dot) It is used to $a.$b
concatenate(joi
echo "<br>"; n together) two
strings.
// appending $b to $a Concatenation .= It is used to $a .= $b
Assignment append one
$a .= $b; string to
another.
echo $a;
?>
7.Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
<?php
$a=5; Operator Name Example Explanation
& And $a & $b Bits that are 1 in
$b=3; both $a and $b
are set to 1,
echo $a & $b; otherwise 0.
echo $a | $b; | Or (Inclusive or) $a | $b Bits that are 1 in
either $a or $b
echo $a ^ $b; are set to 1
^ Xor (Exclusive or) $a ^ $b Bits that are 1 in
echo $a & ~ $b; either $a or $b
are set to 0.
?>
~ Not ~$a Bits that are 1 set
to 0 and bits that
are 0 are set to 1
<< Shift left $a << $b Left shift the bits
of operand $a $b
steps
>> Shift right $a >> $b Right shift the
bits of $a
Left Shift( << )
Here the input bits are shifted to their left by the number of places as specified.
Left Shift( << )
Here the input bits are shifted to their left by the number of places as specified.
Syntax:
$first_op << $n
where $n refers to the number of places by which bits must be shifted.
<?php
$a=4;
Plac
$b=3; e
128 64 32 16 8 4 2 1
valu
echo $a << $b; e
?> $a 0 0 0 0 0 1 0 0 = 4
Out 0 0 1 0 0 0 0 0 = 32
put

Here we are specifying to shift binary 4 by 3 digits to its left. Hence the resulting output we get
is 32.
8.Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell
command. Execution operator and shell_exec() give the same result.

Operator Name Example Explanation


`` backticks echo `dir`; Execute the
shell command
and return the
result.
Here, it will
show the
directories
available in
current folder.
9.Error Control Operators
PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an expression,
any error message will be ignored that might be generated by that expression.

Operator Name Example Explanation


@ at @file Intentional file
('non_existent_ error
file')
10 .Array Operators
Array operators are used to compare the two arrays. Operator Name Example Explanation

<?php + Union $a + $y Union of $a


and $b
$array1 = array("Java","C++","webtechnologies");
== Equality $a == $b Return TRUE if
$array2 = array("Java","Smalltalk",".Net"); $a and $b
have same
$array3 = array("Java","Smalltalk",".Net"); key/value pair

echo var_dump($array1 == $array2) ."<br>";


!= Inequality $a != $b Return TRUE if
echo var_dump($array2 == $array3) ."<br>"; $a is not
equal to $b
?>
=== Identity $a === $b Return TRUE if
$a and $b
have same
key/value pair
of same type
in same order

!== Non-Identity $a !== $b Return TRUE if


$a is not
identical to $b

<> Inequality $a <> $b Return TRUE if


Arrays:
Array:
Array :An array is used to store multiple values of same type in a single variable.
we can traverse all the values stored in the array using the foreach loop.
We can store number, string and object in the PHP array
Creating an Array
We can create an array in PHP using the array() function.

Syntax:

<?php
/*
this function takes multiple values
separated by comma as input to create
an aray
*/
array();

?>
Advantages of Array
 It's very easy to define simple list of related data, rather than creating multiple variables.
 It's easy to use and traverse using the foreach loop.
 PHP provides built-in functions for sorting array, hence it can be used for sorting information
as well.
In PHP there are 3 types of array:
1. Indexed Array
2. Associative Array
3. Multidimension Array
1. Indexed Array:
 An indexed or numeric array stores each array element with a numeric index.
 In an indexed array Values are stored and accessed in a linear fashion.
 These arrays can store numbers, strings and any object but their index will be represented
by numbers. By default array index starts from zero.
There are two ways to define an indexed array:
1st way:
$language=array("java","c++","C",“python");
2nd way:
$language[0]="java";
$language[1]="C++";
$language[2]="C";
$language[3]=“python";
****Get The Length of an Array - The count() Function
The count() function is used to return the length (the number of elements) of an array:
Viewing Array Structure and Values
You can see the structure that is data type and values of any array by using one of two
statements — var_dump() or print_r().
Ex: To demonstrate var_dump
<?php
// Define array
$cities = array("London", "Paris", "New York");
// Display the cities array
var_dump($cities);
?>
This var_dump() statement gives the following output:
array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }
Ex1 : Todemonstrate indexed array
<?php
$lan = array("Java", "C++", "Phython");
echo "I like " . $lan[0] . ", " . $lan[1] . " and " . $lan[2] . ".";
?>
Output:
I like Java, C++ and Phython.
Ex2: using for loop
<?php
$lan = array("Java", "C++", "Phython");
$arrlength = count($lan);
for($x = 0; $x < $arrlength; $x++) {
echo $lan[$x];
echo "<br>";
}
?>
2. Associative Array:
Associative arrays have a named key as an index, the key can be numeric or text.
We can associate the name with each array element in PHP using => symbol.
Associative arrays are also very useful when retrieving data from the database.
The field names are used as id keys.
Creating Associate array in two ways
1st way:
$salary=array("ram"=>"350000","harika"=>"450000","charan"=>"200000");
2nd way:
$salary["ram"]="350000";
$salary[“Harika"]="450000";
$salary["charan"]="200000";
Ex1: Todemonstrate associative array:
<?php
$salary=array("ram"=>"350000","harika"=>"450000","charan"=>"200000");
echo " ram salary: ".$salary["ram"]."<br/>";
echo " harika salary: ".$salary["harika"]."<br/>";
echo " charansalary: ".$salary["charan"]."<br/>";
?>
ram salary: 350000
harika salary: 450000
charansalary: 200000
Ex2: To demonstrate associative array using foreach loop:
<?php
$salary=array("ram"=>"3500","harika"=>"4500","charan"=>"20000");
// Using for loop
foreach($salary as $sal=>$sal_val)
{
echo "key=" .$sal. ",value=" .$sal_val;
echo "<br>";
}
?>
Output:
key=ram,value=3500
key=harika,value=4500
key=charan,value=20000
3.PHP Multi-dimensional arrays
These are arrays that contain other nested arrays. A multidimensional array is also known as an
array of arrays
It allows you to store tabular data in an array.
The advantage of multidimensional arrays is that they allow us to group related data together.
Traversing Multidimensional Arrays: We can traverse through the multidimensional array using
for and foreach loop.
Ex:
$emp = array
(
array(1,"ram",400000),
array(2,"harika",500000),
array(3,"charan",300000)
);
Ex1: to demonstrate multidimensional array using for loop
<?php
$emp = array
(
array(1,"kiran",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

for ($row = 0; $row < 3; $row++)


{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Ex 2:to demonstrate multidimensional array using for and foreachloop
<?php
$emp = array(
array(
"name" => "ram",
"email" => "ram@gmail.com",
),
array(
"name" => "harika",
"email" => "harika@gmail.com",
)
);
Output:
0 name : ram email : ram@gmail.com
1 name : harika email : harika@gmail.com
Strings
What is String in PHP?
A string is a collection of characters. String is one of the data types supported by PHP. PHP only
supports a 256-character set.
Creating Strings:
There are four ways of creating strings in PHP:
1.single quoted
2.double quoted
3.heredoc syntax
4.newdoc syntax (since PHP 5.3)
1. Single-quote strings:
The simplest way to create a string is to use single quotes.
Note: This type of string does not process special characters inside quotes.
Ex:
<?php
// single-quote strings
$site = 'Welcome to Amazon';
echo $site;
?>
2.double quoted:
 we can create the string by enclosing text within double quote.
 Variable names can be used inside double quotes and their values will be displayed.
 double-quote strings in PHP are capable of processing special characters.
<?php
// double-quote strings
echo "Welcome to Freshers Party \n";
$site = "CSE Students";
echo "Welcome to $site";
?>
3. Heredoc:
 By using heredoc we can declare a string with out single and double quotes.
 If we want to define a multiline string, using the here doc syntax is the best and the easiest
technique.
Heredoc syntax (<<<)
heredoc three less than symbols <<< followed by an identifier.
In Heredoc syntax, an identifier is provided after this heredoc <<< operator, and immediately a
new line is started to write any text
note:That closing identifier must begin from the new line without any whitespace or tab.
Ex:
<?php
$lan=<<<EOT
java is purely object oriented programming language
EOT;
echo $lan;
?>
4.newdoc syntax (since PHP 5.3)
 The Newdoc string creation method is similar to the heredoc method but works like the way
single quotes work.
 The syntax is similar to the heredoc syntax with symbol <<< followed by an identifier
enclosed in single-quote
 No parsing takes place inside the Nowdoc.
Note:The difference between newdoc and heredoc is that - Newdoc is a single-quoted string
whereas heredoc is a double-quoted string.
Ex: newdoc
<?php
$str = <<<'DEMO'
Welcome to java.
Learn with newdoc example.
DEMO;
echo $str;
?>output: Welcome to java.Learn with newdox example
STRING FUNCTIONS
some commonly used string functions in PHP:
1. 1.strlen($str)
This function returns the length of the string or the number of characters in the string including
whitespaces.
2.str_word_count($str)
This function returns the number of words in the string.
3.strrev($str)
This function is used to reverse a string.
4.This function is used to replace a part of the string with some text.
str_replace($replacethis, $replacewith, $str)
5.ucwords($str)
This function converts first letter/character of every word in the string to uppercase.
6.ucfirst($str)
ucfirst() function returns string converting first character into uppercase
6.lcfirst($str): Make the first character of a string value lower case
7.strtoupper($str):
To convert every letter/character of every word of the string to uppercase.
8.strtolower($str):
This function is used to convert every letter/character of a string to lowercase.
9.explode() function: This function converts a string into an array.
10. substr() function: This function gives the substring of a given string from a given index.
11.The strpos() function finds the position of the first occurrence of a string inside another
string.
Syntax: strpos(string,find)
Ex 1:to demonstrate string functions strlen, str_word_count, strrev, ucwords, ucfirst
<?php
$str = "welcome to nareshIT";
echo "Length of the string is: ". strlen($str)."</br>";
echo " word count:" .str_word_count($str)."</br>";
echo " string rev:".strrev($str)."</br>";
echo " ucwords:" .ucwords($str)."</br>";
echo " lcfirst:" .lcfirst($str);
?> output:
Length of the string is: 19
word count:3
string rev: TIhseran ot emoclew
ucwords: Welcome To NareshIT
lcfirst: welcome to nareshIT
Ex2: todemonstrate functions :substring, string replace, strtoupper ,strtolower,strpos
<?php
$str ="happy new year";
echo(substr($str,3))."</br>";
echo str_replace("world", "India", "Hello world!")."</br>";
echo strtoupper($str)."</br>";
echo strtolower($str);
echo strpos("I like java, I like php too!","php");
?>Output:
py new year
Hello India!
HAPPY NEW YEAR
happy new year
20
Functions:
 A function is a block of code written in a program to perform some specific
task.
 A function will be executed by a call to the function.we can call a function by its name.
 In PHP there are thousands of built-in functions which we can directly use in our
program/script.
 PHP also supports user defined functions, where we can define our own functions.

<?php
function function_name()
{
// function code statements;
}
?>
Call a function
When a function doesn’t have any parameter, you can call the function by using its name
followed by parentheses like this:
<?php

function_name();
Ex:
<?php
// defining the function
function greetings()
{
echo "Very Happy New Year 2022";
}
greetings();
}
•Built-in functions: PHP provides us with a huge collection of built-in library functions. These
functions are already coded and stored in form of functions.
• To use those we just need to call them as per our requirements like, var_dump, fopen(),
print_r() etc.
•User Defined Functions: we can define our own functions in our program and use those
functions.
•Using this we can create our own packages of code and use it wherever necessary by simply
calling it.
Advantages of User-defined Functions
 Code Reusability: functions are defined only once and can be invoked many times.
 Less Code: It saves a lot of code because you don't need to write the logic many times.
 Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application.
PHP Function Arguments
 Information can be passed to functions through arguments. An argument is
nothing but a variable.
 You can pass any number of arguments to a function but separated by comma.
 PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-
length argument list.
Syntax: Function with parameters
<?php
function function_name(parameter1, parameter2)
{
// function code statements
}
?>
<?php
function welcome_user($username)
{
echo 'Welcome ' . $username;
}
The welcome_user() function has a parameter $username.
It displays a welcome message to the user by concatenating the Welcome message with
$username.
Parameter passing to Functions
PHP allows us two ways in which an argument can be passed into a function: 
•call by value: On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains unchanged.
•That means a duplicate of the original value is passed as an argument.
•call by reference: On passing arguments as pass by reference, the original value is passed.
Therefore, the original value gets altered.
•In pass by reference we actually pass the address of the value, where it is stored using
ampersand sign(&).
Example :call by value.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Ex: todemonstrate call by reference:
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
PHP Function: Default Argument Value
We can specify a default argument value in function. While calling PHP function if
you don't specify any argument, it will take the default argument.
<?php
// function with default parameter
function def($str, $num=12)
{
echo "$str is $num years old \n";
}
// Calling the function
def("Ram", 15);
// In this call, the default value 12
// will be considered
def("sita");

?>
Return a value
A function can return a value. To return a value from a function, you use the return statement:
return value;
Ex:
<?php
function sum($num1, $num2)
{
$product = $num1 * $num2 ;

return $product;
}
$returnvalue = sum(2, 3);
echo "The product is $returnvalue";
?>
output: The product is 6
Control statements
 PHP provides a control statements enabling developers to develop different logic to execute
in different conditions.
 A control statement is used in a programming language to control the flow of the program.
 Control statements are the statements that are executed randomly and repeatedly.
 They are useful to write better and complex programs
 controls statement like if statement, if-else statement, break statement, continue statement,
for loop, while loop, do while loop.
Control statements
1.Condition statements
2.Looping statements
3.Jumping statements
1.Condition statements
While writing programs/scripts, there will be scenarios where you want to execute a particular
statement only
if some condition is satisfied. In such situations we use Conditional statements.
In PHP, there are 5 different types of Conditional Statements.
if statements
if...else statements
if...elseif...else statements
nested if
switch statement
if statement
When we want to execute some code when a condition is true, then we use if statement.
Syntax:
if(condition)
{
// code to be executed if 'condition' is true
}
Ex:
<?php
$age = 20;
if($age >= 18)
{
echo "You are allowed to vote";
}
?>
2. if else statement
When we want to execute some code when a condition is true,
and some other code when that condition is false, then we use the if...else .
Syntax:
if(condition) Ex:
{
// code to be executed if 'condition' is true
}
else
{
// code to be executed if 'condition' is false
}
3.The if...else...elseif statement
When we want to execute different code for different set of conditions,
and we have more than 2 possible conditions, then we use if...elseif...else pair.
Syntax:
if(condition1)
{
// code to be executed if 'condition1' is true
}
elseif(condition2)
{
// code to be executed if 'condition2' is true
}
else
{
/* code to be executed if both 'condition1'
and 'condition2' are false */
}
4.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.
if (condition)
{
//code to be executed if condition is true
if (condition)
{
//code to be executed if condition is true
}
}
5.switch statement is used to execute one statement from multiple condition.
A switch statement is used to perform different actions, based on different conditions.
Syntax
switch(expression)
{ Note:
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;
}
Ex: TO ILLUSTRATE SWITCH STATMENT
<?php
$car = "Jaguar";
switch($car)
{
case "Audi":
echo "Audi is amazing";
break;
case "Mercedes":
echo "Mercedes is mind blowing";
break;
case "Jaguar":
echo "Jaguar is the best";
break;
default:
echo "$car is Ok";
}
Loops:
When you need to execute a block of code or statements several number of times then you
need to use looping concept..
In computer programming, loops are used to to execute a block of code several number of
times . For example, if you want to show a message 100 times, then rather than typing the
same code 100 times, you can use a loop.
Advantage with looping statement
Reduce length of Code
take less memory space.
Burden on the developer is reducing.
Time consuming process to execute the program is reduced.
1.while
2.dowhile
3.for
1.while loop is used to run a block of code repeatedly until a certain condition is true.
 When the number of iteration is not fixed then while loop is used.
 In while loop first check the condition if condition is true then control goes inside the loop
body otherwise goes outside of the body.
Syntax:
<?php
while(condition)
{
/*
execute this code till the
condition is true
*/
}
?>
2.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.
 do..while loop is used where you need to execute code at least once.

<?php
do {
/*
execute this code till the
condition is true
*/
} while(condition)
3.The for loop is used when you know in advance how many times the script should run.
 In php for loops execute a block of code specified number of times.
 For loop contains 3 parts Initialization, Condition and Increment or Decrements
Syntax:
<?php
for(initialization; condition; increment/decrement)
{
/*
execute this code till the
condition is true
*/
}
?>
4.The foreach loop in PHP is used to access key-value pairs of an array.
This loop only works with arrays and you do not have to initialize any loop counter or set any
condition for exiting from the loop,
everything is done implicitly(internally) by the loop.
Syntax
foreach ($array as $value)
{
code to be executed;
}

Note:
every loop iteration, the value of the current array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
break
 The break keyword immediately ends the execution of the loop or switch structure.
 The break statement can also be used to jump out of a loop.
 The break statement can be used in all types of loops such as while, do-while, for, foreach loop, and
also with switch case.
Syntax
Ex:
<?php
for($i=1;$i<=10;$i++)
{
echo "$i <br/>";
if($i==5)
{
break;
}
}
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
The continue statement can be used with all types of loops such as - for, while, do-while, and foreach
loop
syntax:
continue;
<?php
$list = ["apple", "banana", "cherry"];
foreach ($list as $value) {
if ($value == "banana")
{
continue;
}
echo "I love to eat {$value}fruit";
echo "</br>";
}
Expression:
Almost everything in a PHP script is an expression. Anything that has a value is an expression.
In a typical assignment statement ($x=100), a literal value, a function or operands processed by
operators is an expression, anything that appears to the right of assignment operator (=).

Syntax

$x=100; //100 is an expression


$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expression
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression
PHP Form Handling
What is form?
An HTML form allows a user to enter data and data can send to a server for processing.
An HTML form contains form elements and Form elements are an input element like textbox ,
label , button , radio button ,check box and list box etc.
 When we develop a website or a web application, we often have to create forms to take input
from users, like a Login form or a Registration form.
 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
we use $_POST.
What is The Input Element?
Input element is defining by an <input> tag. These elements are using within a <form> element
to specify input controls that help the user to input data.
<form> this form element of html will send data to the desired url (location)

Ex:<form action=“welcome.php“ method=“get”>


What is The Type Attribute on an <input> Element?
The type attribute is using to define the type of <input> element to display.
Ex: <input type=“text” name ‘t1> //textbox
Attributes of Form Tag

Action: By using this attribute we can specify the pagename in which page we can redirect the
form value

Method: we can specify the type of method we are using to send the form values to the server
 There are two ways the browser client can send information to the web server.
 The GET Method
 The POST Method
 
The GET Method
 The GET method sends the encoded user information appended to the page request.
 The page and the encoded information are separated by the ? character.
 Ex:http://www.test.com/index.htm?name1=value1&name2=value2
PHP GET Form
 Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL)
 GET also has limits on the amount of information to send. The limitation is about 2000
characters
 Get request is the default form request.
 GET may be used for sending non-sensitive data
 GET should NEVER be used for sending passwords or other sensitive information!
 GET can’t upload the file
The PHP provides The $_GET Super global Variable
 The $_GET variable is used to get values from an html form when GET method is used
Syntax
$variable_name = $_GET["field_name"];
Ex to create form with fname and age by using get method
display.html
<html>
<body bgcolor="yellow">
<center> <h1>welcome to home Page </h1></center>
<form action="welcome.php" method="get">
Name: <input type="text" name="fname"></br>
Age: <input type="text" name="age"></br></br>
<input type="submit">
</form>
</body>
</html>
Ex to create php program to read form data by using get method
Welcome.php
<html>
<body bgcolor="pink">
<center> <h1>welcome to Mywebsite</h1></center>
<?php
echo "welcome".$_GET["fname"]."</br>";
echo "your age is". $_GET["age"]; Here notice in url: username and age is visiblein url
?>
</body>
</html>
PHP POST FORM
 The POST method transfers information via HTTP headers to server.
 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.
 Information sent from a form with the POST method is not visible to others or in url.
 POST  has no limits on the amount of information to send.
 POST can upload files to server.
 POST is highly secured.
The PHP provides $_POST Super global Variable
 The $_POST variable is used to get values from an html form when
POST method is used.
Syntax
$variable_name = $_POST["field_name"];
Ex to create login form by using post method
<html>
<body bgcolor="yellow">
<h1> Login Form </h1>
<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>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
</body>
</html>
Ex to create php program to read form data by using post method
login.php
<html>
<body bgcolor="yellow">
<h1> get login data by using post method </h1>
<?php
$name=$_POST["name"];
$password=$_POST["password"];
echo "Welcome: $name, your password is: $password";
?> In URL It is not visible user name and password
</body>
</html>
Reading data from web form controls like text boxes, radio buttons,checkboxes and listbox
Reading data from web form controls like text boxes
What is textbox?
It is html form element in which allows user to enter single line of text in to textbox.
Ex: name, password
The default width of the text field /textbox is 20 characters.
Ex:<input type="text“ name’”t1> defines a text field.
What is Name Attribute of an <input> Element?
The name attribute defines the name of an <input> element. With this attribute, form elements
can send their values to a server when we submit the form-data using a form.
Ex:
Write an html program to design login form by using textbox
<html>
<body bgcolor="yellow">
<center> <h1> Login Page</h1></center>
<form action="welcome1.php" method="post">
Name: <input type="text" name="fname"></br>
Password: <input type="password" name="pass"></br>
<input type="submit“ name=“ok” value=“submit”>
</form>
</body>
</html>
Ex To read data from Textbox/text field
Continue in next slide
Write a php program to read data from textbox/text field
<html>
<body bgcolor="pink">
<center> <h1>Reading data from text box</h1></center>
<?php
echo "welcome".$_GET["fname"]."</br>";
echo "your password is". $_GET[“pass"];
?>
</body>
</html>
Reading Data from check boxes
The checkbox element in HTML allows us to select multiple items from the group of values.
When creating a checkbox form in HTML, the input tag is used and contains
the type and name attributes.
-The type attribute is set to "Checkbox" for Checkboxes.
-The name attribute is the name of each individual checkbox.
If you want to select a checkbox by default, you can use the line checked="checked" for the
given checkbox.
Ex:
<input type="checkbox" name="checkbox_name" value="checkox_value">
Checkboxes are used in questionnaires where a user can select more than one option from a list
of choices.

In order to get the checkbox values, you can use the foreach() method.
Write an html program to design checkbox
<html>
<body bgcolor="green">
<h1> Entering Data with check boxes
</h1>
<form method="post" action="checkbox.php">
<b> Myfavorite Fruit is </b> <br>
<input type="checkbox" name="check1" value="mango"> mango <br>
<input type="checkbox" name="check2" value="apple"> apple <br>
<input type="checkbox" name="check3" value="grapes"> grapes <br>
<input type="submit" value="submit">
</form>
</body>
</html>
Ex1:Write a php program to read data from checkbox
<html>
<body bgcolor="red">
<h1> Reading Data from checkbox </h1>
<?php
$ch1= $_POST['check1'];
$ch2= $_POST['check2'];
$ch3= $_POST['check3'];
if(isset($ch1))
{
echo "your favorite fruit is:". $ch1. "<br>";
}
if(isset($ch2))
{
echo "your favorite fruit is:". $ch2. "<br>";
}
if(isset($ch3))
{
echo "your favorite fruit is:". $ch3. "<br>";
}
?>
</body>
</html>

Output:
Reading Data from checkbox
your favorite fruit is: mango
your favorite fruit is: apple
your favorite fruit is: grapes
Ex 2: write a html program to create checkbox array
<html>
<body bgcolor="yellow">
<h1> Entering Data with check boxes
</h1>
<form action="checkphp.php" method="post">
<input type="checkbox" name="check_list[]" value="C/C++"><label>C/C++</label><br/>
<input type="checkbox" name="check_list[]" value="Java"><label>Java</label><br/>
<input type="checkbox" name="check_list[]" value="PHP"><label>PHP</label><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Ex2:Write a php program to read data from checkbox array using foreach loop
<?php
echo "Read data from checkbox “. ”<br”;
if(isset($_POST['submit']))
{
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected)
{
echo $selected."</br>";
}
}
?> output:
Read data from checkbox
C/C++
Java
PHP
Radio Button: It is the form element which allows the user to select only one option from the
available choices
When creating a radio button form in HTML, the input tag is used and contains the type, name,
and value attributes.

-The type attribute is set to "Radio" for Radio buttons


-The name attribute is set to the collective or group name of all the radio buttons. All the radio
buttons in a certain group will all have the same name attribute
-The value attribute is set to the name of each indivdual element of the radio buttons
Ex: <input type=“radio” name=“radio”>
Write an html program to illustrate radio button
<html>
<body bgcolor="yellow">
<h1> Entering Data with Radio Button </h1>
<form method="post" action="gender.php">
<b> Please Select the Gender is </b> <br>
<input type="radio" name="radios" value="Male">Male <br>
<input type="radio" name="radios" value="Female"> Female <br>
<input type="submit" value="submit">
</form>
</body>
</html>
Write a php program to read data from radio button
<html>
<body bgcolor="red">
<h1> Reading Data from radio button </h1>
<?php
echo "You selected gender is:";
if(isset($_POST["radios"]))
{
echo $_POST["radios"];
}
else
echo "select any one";
?>
</body> Reading Data from radio button
You selected gender is: Male
</html>
List Box: The list box allows a user to select one or more options from the list of options.
Ex: List of countries , List of states
There are 2 distinct type of list boxes in which we retrieve data from.
The first is a list box that only allows one option to be selected.
The second is a list box in which multiple options can be selected.
Syntax
To create a list box, use the HTML element <select>
<select Name="Name_of_list_box" Size="Number_of_options">
<option> List item 1 </option>
<option> List item 2 </option>
<option> List item 3 </option>
<option> List item N </option>
</select>
Write an html program to design listbox
<html>
<body bgcolor="yellow">
<h1> Entering Data in List boxes
</h1>
<form method="POST" action="mullist.php">
<select name="countries[]" multiple>
<option>India</option>
<option>us</option>
<option>Australia</option>
</select><br><br>
<input type="submit" value="send">
</form>
</body>
</html>
Write a php program to read data from listbox
<html>
<body bgcolor="red">
<h1>Reading Data from List box</h1>
<?php
if(isset($_POST['countries']) )
{
$values=$_POST['countries'];
foreach($values as $selected)
{
echo $selected."<br>";
}
}?>
</body>
</html>
Cookie:
A cookie is a small file with a maximum size of 4KB that the web server stores on the client browser.
cookies are used mainly tracking the pages visited by a user
Ex: To store username etc.
Cookie is used to identify a user.
 Cookie is created at server side and saved to client browser. Each time when
client sends request to the server, cookie is embedded with request. Such way,
cookie can be received at the server side.
 PHP transparently supports HTTP cookies. Using PHP, you can both create and retrieve cookie
values.
 It is less secure
Realworld Use of Cookies
1.To store user information like when he/she visited, what pages were visited on
the website etc, so that next time the user visits your website you can provide a
better user experience.
2.A cookie can contain any type of information such as the time when you visited the website, the
items that you added into your shopping basket, all the links you clicked in website, etc.,
3.You can use cookies to store number of visits or view counter.
Creating a Cookie in PHP
A cookie is created in php using setcookie() function. Here only the name parameter is required.
All other parameters are optional.
syntax
setcookie(name, value, expire, path, domain, secure)
 The first argument which defines the name of the cookie is mandatory,
rest all are optional arguments.
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.
There are three steps involved in identifying returning users −
•Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
•Browser stores this information on local machine for future use.
•When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
Accessing Cookie Values:
$_COOKIE
 To access a cookie we use the $_COOKIE global variable, and can use the isset() method to
check whether the cookie is set or not.
Ex:$value=$_COOKIE["CookieName"];//returns cookie value  
 It is an associative array that contains a record of all the cookies values sent by the browser
in the current request. The records are stored as a list where the cookie name is used as the
key.
Note:
 you can use $HTTP_COOKIE_VARS to access the cookie
 So if we want to create a cookie to store the name of the user who visited
your website, and set an expiration time, then we can do it like this,
The cookie will expire after 30 days (86400 * 30).
 setcookie("CookieName", "CookieValue", time()+1*60*60);//
using expiry in 1 hour(1*60*60 seconds or 3600 seconds)  
Ex :To create the cookie
<?php
setcookie("name", "Ravikumar");
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body bgcolor="yellow">
<?php echo "Cookie created"?>
</body>
</html>
Ex :To access the cookie
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body bgcolor="pink">
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
Deleting Cookie with PHP
To delete a cookie, use the setcookie() function by passing the cookie name and other arguments
but an expiration date is required to be set is must.
<?php
// set the expiration date to one hour ago
setcookie("user", "kirankumar", time() - 3600);
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
<body>
<html>
Sessions:
 PHP session is used to store and pass information from one page to another temporarily (until
user close the website). A session is a way to store information to be used across multiple
pages.
 Session is not limited by any size limit, you can store any information in the session,
irrespective of its size.
 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.
 In case of cookie, the information are stored in user computer but in case of session
information is not stored on the users computer.

 Sessions are stored at server side.


 So it is more secure.
Why use session in PHP
 The web server does not know who you are or what you do, because the HTTP address
doesn't maintain state.
 Session variables solve this problem by storing user information to be used across multiple
pages (e.g. username, favorite color etc)
 By default, session variables last until the user closes the browser. So Session variables hold
information about one single user, and are available to all pages in one application.
Note: The defaut time out for session time out or expired time is 30-180 minutes depending on
your PHP Installation.
Realworld Use of Session
1.When a user logs into their account on any web application, a session is created for them, and
in the session their username or userid or some other unique identifier is stored, which is then
used on the consecutive webpages to show information specific to that user. On logout, the
session is destroyed.
How to Create the session: PHP session_start() function

 PHP session_start() function is used to start the session.


 It starts a new session. It returns existing session if session is created already.
 If session is not available, it creates and returns new session.

Example
<?php
session_start();
?>
Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal array.
The stored data can be accessed during lifetime of a session.
Below is the PHP code to store a session with two session variables Rollno and Name:
<?php
session_start();
$_SESSION["Rollno"] = "509";
$_SESSION["Name"] = "kiran";
?>
Accessing Session Data:
PHP $_SESSION Global variable
PHP $_SESSION is an associative array that contains all session variables.
It is used to set and get session variable values.
Data stored in sessions can be easily accessed by firstly calling session_start() and then by
passing the corresponding key to the $_SESSION associative array.
<?php

session_start();

echo “student name :” . $_SESSION["Name"] . “<br>”;

echo “ Roll number :”. $_SESSION["Rollno"] . “<br>”;

?>
Destroying Certain Session Data:
To delete only a certain session data,the unset feature can be used

with the corresponding session variable in the $_SESSION associative


array.
The PHP code to unset only the “Rollno” session variable from the
associative session array:
<?php
session_start();
if(isset($_SESSION["Name"])){
unset($_SESSION["Rollno"]);
}
?>
Destroying Complete Session:
The session_destroy() function is used to completely destroy a session.
The session_destroy() function does not require any argument.
<?php
session_start();
session_destroy();
?>

We use these functions destroy() on pages like logout or checkout in


case of an eCommerce website to clean the session variable off the
user specific data and to eventually destroy the current session.
PHP program to create session[storing data in session] createsession.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "cherry";
echo "Session information are set successfully.<br/>";
?> <a href="getsession.php">Visit next page</a>
</body>
</html>
PHP program to read a session variable data in another page [getsession.php]
<?php
session_start();
?>
<html>
<body>
<h1> welcome to amazon</h1>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>
PHP program to destroy a session variable data
<?php
session_start();
?>
<html>
<body>
<?php
session_unset();
session_destroy();
echo "session destroyed";
?>
</body> </html>
 
 
PHP File Uploading
PHP allows you to upload single and multiple files through few lines of code only.
PHP file upload features allows you to upload binary and text files both.
What kind of Files we can upload?
We can upload files like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as
executables files and a wide range of other file types.
In PHP, we have full control over the file that is being uploaded. we can authenticate the file and
decide whether to accept or reject.
PHP $_FILES
The PHP global $_FILES contains all the information of file.
By the help of $_FILES global, we can get file name, file type, file size, temp file name and errors
associated with file.
$_FILES['filename']['name']
returns file name.
$_FILES['filename']['type']
returns MIME type of the file.
$_FILES['filename']['size']
returns size of the file (in bytes).
$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.
$_FILES['filename']['error']
returns error code associated with this file.
HTML code snippet: Below is the HTML source code for the HTML form for uploading the file to
the server.
In the HTML <form> tag, we are using “enctype=’multipart/form-data” which is an encoding
type that allows files to be sent through a POST method.
Without this encoding, the files cannot be sent through the POST method. We must use this
enctype if you want to allow users to upload a file through a form.
move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location.
The move_uploaded_file() function checks internally if the file is uploaded thorough the POST
request. It moves the file if it is uploaded through the POST request.
Syntax
1.bool move_uploaded_file ( string $filename , string $destination )  
Ex to illustrate fileuploading of text file
Step1: create one text file and write some text in that file[hello.text]
Step2: create upload.html file to upload the file which you created
<html>
<body bgcolor="yellow">
<form method="post" action="upload.php" enctype="multipart/form-data">
UPLoad File:<input type="file" name="userfile">
<br>
<h1>
file uploading </h1>
<input type="submit" value="submit">
</form>
</body>
</html>
Step3: create php file to read the text file which was uploaded
<?php
$handle=fopen($_FILES['userfile']['tmp_name'],"r");
while(!feof($handle))
{
$text=fgets($handle);
echo $text, "<br>";
}
fclose($handle);
?> output:
hi h r u
my name is
cherry
Database

DBMS: Collection of programs (s/w) written to manage the Database.


Database: A collection of interrelated data or collection of information in secondary storage is
called database.
Database is a collection of Database objects. Database we are using to create tables,
views, stored procedures.
Ex: oracle, Mysql etc.
Mysql
Table: Table is a collection of rows and columns.
Mysql Database: is an open source relational database Management system supports
number of objects like Tables, views etc.
Mysql is implemented by mysql AB Corporation in 1995.Now it is maintained by Oracle
Corporation.
MysQL, pronounced either "My S-Q-L" or "My Sequel,". It is based on the structure query
language (SQL), which is used for adding, removing, and modifying information in the database.
Query
query is a request or question for information from a database.
Ex: select *from emp:
By using above query we can get employee information from
the table emp.
Nested query: query with in another Query is called Nested query.
PHP to connect Mysql Database
PHP is providing php_mysql.dll library with no of functionalities to connect with Mysql
database.
 PHP You can connect to Mysql Database.
 PHP you can perform DDL (Data Definition language) operations.
Like Create Alter Drop
 PHP You can perform DML (Data Manipulation language) operations.
Like Insert Update Delete
 PHP You can perform DQL (DataQuery Language) operations.
Like Select
 The Default username of mysql database is “root” and it does not contain any “password”.
PHP Admin
It is a Graphical User Interface used to connect with Mysql Database.
It is available with WAMP Server download.
The url address to open phpmyadmin is
http://localhost/phpmyadmin
By using Phpmyadmin
We can create tables ,insert records in table
We can execute our sql statements
We can change the structure of the table and also delete the table structure.
MySql Interaction with PHP
PHP 5.0 is providing php_mysql.dll library to connect to mysql database and providing more
functions.
PHP 5 and later can work with a MySQL database using:
•MySQLi extension (the "i" stands for improved)
•PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in
2012.
MySQLi and PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL
databases.
So, if you have to switch your project to use another database, PDO makes the process easy.
Both are object-oriented, but MySQLi also offers a procedural API.
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are
very important for web application security.
How to Opening /establishing the connection with Mysql:
 PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database.
By using this we can create a connection between php program and mysql database.

mysqli: my Structured Query Language.


I stands for Improved
It contains 3 arguments
1. ServerName 2.username 3.password.

Syntax: mysqli_connect ($servername, $username, $password);


Ex: <?php
$servername = “localhost”;
$Username = “root”;
$Password = ‘’”;
$conn = mysqli_connect($Hostname, $Username, $Password);
 ?>
Closing the connection:

 PHP mysqli_close()
 PHP mysqli_close() function is used to disconnect with MySQL database.
Syntax
 mysqli_close($conn);  

If PDO then close the connection like below


PHP PDO:
$conn = null;
PHP MySQL Create Database
Since PHP 4.3, mysql_create_db() function is deprecated.
Now it is recommended to use one of the 2 alternatives.
•mysqli_query()
•PDO::__query()
mysqli_query():
By using this you can execute a sql query in mysql database.
It contains two arguments.
1. Sql statement 2. Connection id
mysqli_query($conn, $sql):
 
mysqli_select_db:
 To select a database from mysql the server arguments are
Database name and connection id
Ex: mysqli_select_db(“kiran”,$conn);

mysqli_fetch_row:
 By using this we can fetch a record from resultset
 Executing simple Queries:
1. Creating a Database in Mysql 
The Create DataBase statement is used to create a database in Mysql. 
The following syntax is used to create a database named "kiran”:
Ex: create database kiran;
The data types that will be used are :
1.VARCHAR: Holds a variable-length string that can contain letters, numbers, and special
characters. The maximum size is specified in parenthesis.
2.INT :The INTEGER data type accepts numeric values with an implied scale of zero. It stores any
integer value between -2147483648 to 2147483647.
The attributes that are used along with data types in this article are:
3.NOT NULL: Each row must contain a value for that column, null values are not allowed.
4.PRIMARY KEY: The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
3.AUTO_INCREMENT :If a column in a table is AUTO_INCREMENT then we do not have to insert
data in that column, it is automatically inserted in the table.
2.Create a Table
The create table statement is used to create a table in MySQL.
Here is a sample query to create a table User, with columns userid, email, password and fullname.
Sytnax:
CREATE TABLE table_name 
(
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);
Ex:// sql query to create table
$sql = "CREATE TABLE User
(
userid INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
fullname VARCHAR(50)
)";
.
3.Insert data into Table
Once a table is created the next step is to enter data into table.
INSERT INTO statement is used to insert new rows in a database table.
TO enter data into table we have to follow certain rules:
 If the value to be inserted is string, we must enclose it in quotes.
 Numeric value must not be enclosed in quotes.

Multiple SQL statements must be executed with the mysqli_multi_query() function.


Note that each SQL statement must be separated by a semicolon.
SYNTAX :
INSERT INTO TABLE_NAME (column1, column2, column3, ... columnN)
VALUES (value1, value2, value3, ...valueN);
Note:
Here, column1, column2, column3, …columnN are the names of the columns
in the table into which you want to insert the data.
Ex:
$sql = "INSERT INTO User (email, password, fullname)
VALUES (‘raj@gmail.com', ‘CMR', ‘rajkumar’)”;

Note:
You may not need to specify the column(s) name in the SQL query if you are
adding values for all the columns of the table. But make sure the order of the
values is in the same order as the columns in the table.
4.Delete data from Table
The DELETE statement is used to delete records from a database table
// sql query to delete data into table
Syntax: delete from table_name where colume_name=column_value;
Ex:
$sql = "DELETE FROM User WHERE userid=1";
5.Update data in a MY-SQL DataBase

The MySQL UPDATE statement is used to update existing records in a table in a MySQL database.

It can be used to update one or more field at the same time.

It can be used to specify any condition using the WHERE clause.

Syntax: update table_name SET column1=value1,column2=value2 where condition; 

Ex: $sql = "update emp12 set lastname='rashwick' where eid=1";

Note:If you omit the WHERE clause, all records in the table will be updated!
6.Select Data From a MySQL Database :

The SELECT statement is used to select data from one or more tables:

Ex: $sql = "select eid, firstname, lastname,email from emp12";

$result = mysqli_query($conn, $sql);


There are two other MySQLi functions used in select query.
•mysqli_num_rows(mysqli_result $result): returns number of rows.
•mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array.
•Each key of the array represents the column name of the table. It return NULL if there are no
more rows.
Write a php program how to connect to database and creating database in mysql
<?php
$Hostname = “localhost”;
$Username = “root”;
$Password = ‘’”;
$conn = mysqli_connect($Hostname, $Username, $Password); // create connection
if (!$conn)
{
echo "Connection failed";
}
echo "Connected successfully"."<br>";
// Create database
$sql ="create database login";
write a php program how to connect to database and creating table in database
<?php
$Hostname =“localhost”;
$Username =“root”;
$Password =‘’”;
$dbname="login";
$conn=mysqli_connect($Hostname, $Username, $Password,$dbname);
if (!$conn)
{
echo "Connection failed";
}
echo "Connected successfully"."<br>";
// sql to create table
$sql = "create table user(
empid int(6) unsigned AUTO_INCREMENT PRIMARY KEY,
firstname varchar(30) NOT NULL,
lastname varchar(30) NOT NULL,
email varchar(50)
)";
if (mysqli_query($conn, $sql))
{
echo "Table created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>
write a php program how to connect to database and insert data in to database
<?php
$Hostname =“localhost”;
$Username =“root”;
$Password =‘’”;
$dbname="login";
$conn=mysqli_connect($Hostname, $Username, $Password,$dbname);
if (!$conn)
{
echo "Connection failed";
}
echo "Connected successfully"."<br>";
/ sql to insert data in to table
$sql = "insert into user(empid,firstname, lastname, email)
values(509,'raj', 'kumar', 'rajkumar509@gmail.com')";
if (mysqli_query($conn, $sql))
{
echo "data inserted successfully";
}
else
{
echo "Error creating inserting data: " . mysqli_error($conn);
}

mysqli_close($conn);
?>
write a php program how to connect to database and delete a record from database
<?php
$Hostname =“localhost”;
$Username =“root”;
$Password =“”;
$dbname =“login”;
// Create connection
$conn = mysqli_connect($Hostname,$Username,$Password,$dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql ="delete from user where empid=510";
if (mysqli_query($conn,$sql))
{
echo "Record deleted successfully";
}
else
{
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
write a php program how to connect to database and updata data in database
<?php
$Hostname = "localhost";
$Username = "root";
$Password = "";
$dbname = "kiran";
// Create connection
$conn = mysqli_connect($Hostname, $Username, $Password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "update user set lastname=‘sri’ where empid=562";

if (mysqli_query($conn, $sql))
{
echo "Record updated successfully";
}
else
{
echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>
write a php progrma how to connect to database and select data from database
<html>
<body bgcolor="yellow">
<?php
$Hostname ="localhost";
$Username ="root";
$Password =‘’”;
$dbname="kiran";
$conn=mysqli_connect($Hostname, $Username, $Password,$dbname);
if (!$conn)
{
echo "Connection failed";
}
echo "Connected successfully"."<br>";
$sql ="select *from user"; // select data from table
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "eid:" .$row["empid"]. "first name:".
$row["firstname"]."lastname:".$row["lastname"]."email:".$row["email"]." <br>";

} }
else
{
echo "0 results";
}
mysqli_close($conn);
?>
</body> </html>
File:
 A collection of data or information that has a name, called the filename.
 Almost all information stored in a computer must be in a file.
 computer programs work with files. This is because files help in storing information
permanently.

Types of files 

Files can be stored data in two ways:


 Text files.
 Binary files. 
Text files:

 A text file (also called ASCII files) stores information in ASCII characters.


 A text file contains human-readable characters.
 A user can read the contents of a text file or edit it using a text editor

Examples of text files


 A text document
Common extensions that are text file formats:
 Web standards: html, xml, css
 Source code: c, cpp, js, java
 Documents: txt.doc
Binary File :

 A binary file is a file that contains information in the same format in which the information is held in
memory i.e. in the binary form
Ex: of binary files
 A JPEG image

Common extensions that are binary file formats:


 Images: jpg, bmp, 
 Videos: mp4
 Audio: mp3, .
 Documents: pdf, doc

 
File Handling:
 File handling is needed for any web application. For some tasks to be done file needs to be
processed.
 File handling starts with creating a file, reading its content, writing into a file ,Appending data
into an existing file ,deleting a file and finally closing the file.
 By using File Handling we can store Data on the Server in PHP
 PHP File System provides us some important functions to create file, read file , write file,
append file, delete file and close file.

Uses of File in Applications


•Oftenly data is stored in for of JSON files, and Php code has to read the file and then display the
data on web page.
•In some simple applications, no database is used, rather data is stored in files.
•In some web applications, you may have to prepare a file for user to download, in that case Php
code will create a file, write data in it and then allow the user to download it.
Php provides pre-defined functions for all these operations
Create a File: fopen()
Open a File: fopen()
Read a File: fread()
Write to a File: fwrite()
Append to a File: fwrite()
Close a File: fclose()
Delete a File: unlink()
To create a new file or to open an existing file, we use the fopen() function provided by PHP

1. Opening Files using fopen()


fopen(): The fopen() function is used to open a file.
Syntax
fopen(filename,mode);

Ex:

<?php

$file = fopen(“demo.txt”,'w');

?>

 filename: is the name of the file you are opening


 mode: indicates how you want to open the file to read from it or to write to it.
Some of the modes:

 ‘r’ : Open for read only


 ‘r+’ : Open for reading and writing
 ‘w’: Opens the file for writing only.
 ‘w+’: Opens the file for reading and writing only.
 ‘a’: Opens the file for writing only.
 ’a+’ :Opens the file for reading and writing only.

Note:
 when you open any file you should should get handle,which represents an open file.
 From then we can use this handle to work with the file
 You can read from it using the various data-reading functions

 
2.Closing a File:file is closed using fclose() function. Its argument is file which
needs to be closed
• When you open any file and work with it at the end you must close it.
 Syntax:
fclose($file)

Ex:

<?php

$file = fopen("demo.txt", 'r');

//some code to be executed

fclose($file);

?>
3.Reading a file:  After file is opened using fopen() the contents of data are read
using fread()

fread(): The PHP fread() function is used to read the content of the file.

The first parameter is the file pointer and the other is the file size in bytes.

Syntax: fread ($file , int $length ) 

fgets(): The PHP fgets() function is used to read single line from the file.
fgetc(): The PHP fgetc() function is used to read single character from the file.
feof() function can be used to check if the “End-Of-File” (EOF) has been reached.
Ex to read data from the textfile
<?php
echo “Reading data from file”;
$file=fopen("D:\\one.text","r");
while(!feof($file))
{
$text=fread($file,50);
echo $text,"<br>";
}
fclose($file);
echo “file successfully read”;
?>
4: Writing to file: The fwrite() function is used to write to a file. The first parameter
of fwrite() contains the name of the file to write to and the second parameter is the string to be
written.

To use fwrite() function to write content to a file, we first need to open the file in write or
append mode.

• The previous data of the file will be erased if u open file in a ‘w’ mode
• The previous data will not be erased if u open file in a ‘a’ mode
Syntax:
 fwrite ( $file ,string $text ) 
of the file.
Ex to write a content in to a file
<?php
$file = fopen(“D:\\demo.text", "w")
$text = "this is web technologies";
fwrite($file, $text);
fclose($file);
echo “file written successfully”
?>
5.Append to File

• The PHP fwrite() function is used to write and append data into file.
• You can append data into file by using a or a+ mode in fopen() function
Note:
 If you use a mode, it will not erase the data of the file. It will write the data at the end
Ex to illustrate append data in to a file.
<?php
$myfile = fopen(“D:\\movies.text, “a+”)
$movie_name = "The Titanic \n";
fwrite($myfile, $movie_name);
$movie_name = " The Mummy \n";
fwrite($myfile, $movie_name);
fclose($myfile);
echo "file written successfully";
?>
6: Deleting a file:

 we can delete any file using unlink() function. The unlink() function accepts one argument
only: file name

Syntax :  unlink ( string $filename)

 $filename represents the name of the file to be deleted.


Ex to illustrate delete a file
<?php
$status=unlink("D:\\one.text");
if($status)
{
echo "File deleted successfully";
}else
{
echo "Sorry!";
}
?>
List Directories
PHP Directory
The directory functions allow you to retrieve information about directories and their contents.
 1.The scandir() function lists the files and directories which are present inside a specified
directory.
Syntax:
scandir(directory, sorting_order, context);
directory: It is a mandatory parameter that specifies the path.
2.The opendir() function in PHP is an inbuilt function which is used to open a directory handle.
The opendir() function and it returns a directory handle resource on success, or FALSE on failure.
Syntax:
opendir($path, $context)
$path : It is a mandatory parameter which specifies the path of the directory to be opened.
3.The readdir() function in PHP is an inbuilt function which is used to return the name of the next
entry in a directory. The method returns the filenames in the order as they are stored in the
filenamesystem.
Syntax:
readdir(dir_handle)
dir_handle : It is a mandatory parameter which specifies the handle resource previously opened
by the opendir() function.
4.The closedir()function in PHP is an built in function which is used to Closes a directory handle.
Syntax:
closedir($dir_handle)
5. The chdir() function changes the current directory.
Syntax:
chdir(directory)
Ex to list files of directory
<?php
// Specifying directory
$mydir = 'D:\\uiux';
// Scanning files in a given directory in ascending order
$myfiles = scandir($mydir);
// Displaying the files in the directory
print_r($myfiles);
?>
END

You might also like