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

UG-OSS-U4

This document provides an overview of PHP, an open-source, server-side scripting language used for web development. It covers PHP's features, syntax, and applications, including server-side scripting, command line scripting, and desktop applications. Additionally, it explains PHP's operators, variables, and the importance of commenting code for better understanding.

Uploaded by

Vimal Cheyyar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

UG-OSS-U4

This document provides an overview of PHP, an open-source, server-side scripting language used for web development. It covers PHP's features, syntax, and applications, including server-side scripting, command line scripting, and desktop applications. Additionally, it explains PHP's operators, variables, and the importance of commenting code for better understanding.

Uploaded by

Vimal Cheyyar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

OPEN SOURCE SOFTWARE

UNIT IV: PHP


PHP Introduction–General Syntactic Characteristics–PHP Scripting–Commenting your code–
Primitives, Operations and Expressions–PHP Variables–Operations and Expressions Control
Statement–Array–Functions–Basic Form Processing–File and Folder Access–Cooking–Sessions–
Database Access with PHO

PHP Introduction
PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. PHP is well suited for web development. Therefore, it is used to
develop web applications (an application that executes on the server and generates the dynamic
page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP
7.4.0 is the latest version of PHP, which was released on 28 November.

Some important points need to be noticed about PHP are as followed:


 PHP stands for Hypertext Preprocessor.
 PHP is an interpreted language, i.e., there is no need for compilation.
 PHP is faster than other scripting languages, for example, ASP and JSP.
 PHP is a server-side scripting language, which is used to manage the dynamic content of
the website.
 PHP can be embedded into HTML.
 PHP is an object-oriented language.
 PHP is an open-source scripting language.
 PHP is simple and easy to learn language.

Why use PHP


PHP is a server-side scripting language, which is used to design the dynamic web applications
with MySQL database.
 It handles dynamic content, database as well as session tracking for the website.
 You can create sessions in PHP.
 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 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. For example - Registration form.
PHP Features
PHP is very popular language because of its simplicity and open source.
There are some important features of PHP given below:
 Performance:
PHP script is executed much faster than those scripts which are written in other languages such
as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.
 Open Source:
PHP source code and software are freely available on the web. You can develop all the versions of
PHP according to your requirement without paying any cost. All its components are free to
download and use.
 Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it.
 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, ODBC, etc.
 Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at runtime.
E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
 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 it contains on its value.
 Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS,
etc.
 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. It has maximum control over the websites like you can make changes
easily whenever you want.
 A Helpful PHP Community:
It has a large community of developers who regularly updates documentation, tutorials, online
help, and FAQs. Learning PHP from the communities is one of the significant benefits.

General Syntactic Characteristics


 PHP code can be embedded in the XHTML document. The code must be enclosed with in
<?php and >
 If the PHP script is stored in some another file and if it needs to be referred then include
construct is used. For instance:
Include("myfile.inc")
 The Variable names in PHP begin with the $ sign.

Following are some reserved keywords that are used in PHP.

and Default false if or this


break do For include require true
case else foreach list return var
class elseif function new static virtual
continue extends global not switch while
xor

 The Comments in PHP can be #, //, /* ...*/


 The PHP statements are terminated by semicolon.
 Open some suitable text editor like Notepad and type the following code. save your code
buy the extension .php.
 It is expected that the PHP code must be stored in htdocs folder of Apache.
 As I have installed xampp, I have got the directory c:\xampp\htdocs. I have created a
folder named php-example inside the htdocs and stored all my PHP documents in that
folder.
 Hence when I want to get the output of the PHP code I always give the URL.

http://localhost/php-examples/programName.php
The http://localhost refers to the path c:\xampp\htdocs

Example Program
Following is the first example of PHP script

PHP DOCUMENT [FirstCode.php]

<html>
<head>
<title> PHP Demo </title>
</head>
<body>
<?php
$i=10;
echo"<h3> Welcome to first PHP Document </h3>";
echo "The value of variable is = $i";
?>
</body>
</html>

PHP Scripting
PHP runs on different operating systems, like Windows, UNIX, Linux and supports
different databases like MySQL, Microsoft Access, and Oracle. PHP can not only collect form data,
but it can also create, read, write, delete, and close files on the server.
It can be easily embedded in HTML. PHP code is embedded in HTML with tags <?php ?>.
PHP is one of the easier programming languages to learn. PHP features a solid ecosystem of
resources for beginners and it encompasses a syntax that is forgiving to beginners.

Applications of PHP Scripts


 Server-Side Scripting
 Command Line Scripting
 Desktop Applications

 Where to use PHP code?


You can use PHP to create dynamic web pages, collect form data, and send or receive
cookies.
 Applications of PHP Scripts
Let us see how many ways PHP scripting is used.
 Server-Side Scripting
Server side scripting is the first purpose of PHP. All you need to start working on a
desktop PC with PHP is a PHP Parser, a webserver (such as Apache) and a web browser like
Google Chrome.
 Command Line Scripting
If you want to use PHP programming on Linux or task scheduler on Windows, then you
don’t really need a web server, but only a PHP Parser. This is called “command line scripting”.
 Desktop Applications
Although, PHP is not a suitable language for development of desktop applications, but it
supports some advanced features like PHP-GTK which is basically an extension of PHP. PHP-GTK
provides object-oriented user interface.
PHP programming enables you to choose not only the operating system of your choice but
also allows you to have choices to use a web server that you are familiar with. It also enables
beginners and professionals to write scripts in their own ways as it allows procedural as well as
object-oriented programming.
PHP not only enables you to output HTML but also lets you include images, PDFs, videos,
and sounds. PHP can auto-generate XHTML and XML files.
PHP provides support to protocols like LDAP, HTTP, COM, POP3, etc. It also supports
WDDX complex data exchange.

Commenting your code


Comments are important parts of the code. Comments provide useful information that
will help you and other developers understand the meaning of the code more quickly later.

PHP supports two types of comments:


 One-line comments
 Multi-line comments

One-line comments
The one-line comment is placed at the end of the line or at the current block.
A one-line comment starts with the pound (#) or double forward-slash (//). The rest of the text
after the (//) is ignored by the PHP interpreter.

The following example uses the // for a one-line comment:


<?php
$rate = 100;
$hours = 173;
$payout = $hours * $rate; // payout calculation

And the following example uses the # for a one-line comment:


<?php
$title = 'PHP comment'; # set default title

Multi-line comments
A Multi-line comment start with /* and end with */. For example:
<?php
/*
This is an example of a multi-line comment,
which can span multiple lines.
*/Code language: HTML, XML (xml)
In practice, you use the multi-line comment when you need to span comments multiple lines.

Primitives, Operations and Expressions


PHP Operator is a symbol i.e used to perform operations on operands. In simple words,
operators are used to perform operations on variables or values.

For example:
$num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.

PHP Operators can be categorized in following forms:


 Arithmetic Operators
 Assignment Operators
 Bitwise Operators
 Comparison Operators
 Incrementing/Decrementing Operators
 Logical Operators
 String Operators
 Array Operators

We can also categorize operators on behalf of operands.


They can be categorized in 3 forms:
 Unary Operators: works on single operands such as ++, -- etc.
 Binary Operators: works on two operands such as binary +, -, *, / etc.
 Ternary Operators: works on three operands such as "?:".
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as
addition, subtraction, etc. with numeric values.

Operator Name Example Explanation


+ Addition $a + $b Sum of operands
- Subtraction $a - $b Difference of operands
* Multiplication $a * $b Product of operands
/ Division $a / $b Quotient of operands
% Modulus $a % $b Remainder of operands
** Exponentiation $a ** $b $a raised to the power $b
The exponentiation (**) operator has been introduced in PHP 5.6.

Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment
operator is "=".
Name Example Explanation
Operator
The value of right operand is assigned to the left
= Assign $a = $b
operand.
+= Add then Assign $a += $b Addition same as $a = $a + $b
Subtract then
-= $a -= $b Subtraction same as $a = $a - $b
Assign
*= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b
Divide then Assign
/= $a /= $b Find quotient same as $a = $a / $b
(quotient)
Divide then Assign
%= $a %= $b Find remainder same as $a = $a % $b
(remainder)

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.
Operator Name Example Explanation
Bits that are 1 in both $a and $b are set to 1, otherwise
& And $a & $b
0.
| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1
^ Xor (Exclusive or) $a ^ $b Bits that are 1 in 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 operand by $b number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of
comparison operators are given:

Operator Name Example Explanation


== Equal $a == $b Return TRUE if $a is equal to $b
Return TRUE if $a is equal to $b, and they are of same
=== Identical $a === $b
data type
Return TRUE if $a is not equal to $b, and they are not of
!== Not identical $a !== $b
same data type
!= Not equal $a != $b Return TRUE if $a is not equal to $b
<> Not equal $a <> $b Return TRUE if $a is not equal to $b
< Less than $a < $b Return TRUE if $a is less than $b
> Greater than $a > $b Return TRUE if $a is greater than $b
Less than or equal
<= $a <= $b Return TRUE if $a is less than or equal $b
to
Greater than or
>= $a >= $b Return TRUE if $a is greater than or equal $b
equal to
Return -1 if $a is less than $b
<=> Spaceship $a <=>$b Return 0 if $a is equal $b
Return 1 if $a is greater than $b

Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a
variable.

Operator Name Example Explanation


++$a Increment the value of $a by one, then return $a
++ Increment
$a++ Return $a, then increment the value of $a by one
--$a Decrement the value of $a by one, then return $a
-- decrement
$a-- Return $a, then decrement the value of $a by one

Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
Operator Name Example Explanation
and And $a and $b Return TRUE if both $a and $b are true
Or Or $a or $b Return TRUE if either $a or $b is true
xor Xor $a xor $b Return TRUE if 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
String Operators
The string operators are used to perform the operation on strings. There are two string
operators in PHP, which are given below:

Operator Name Example Explanation


. Concatenation $a . $b Concatenate both $a and $b
Concatenation and First concatenate $a and $b, then assign the
.= $a .= $b
Assignment concatenated string to $a, e.g. $a = $a . $b
Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the
values of arrays.

Operator Name Example Explanation


+ Union $a + $y Union of $a and $b
== Equality $a == $b Return TRUE if $a and $b have same key/value pair
!= Inequality $a != $b Return TRUE if $a is not equal to $b
Return TRUE if $a and $b have same key/value pair of same
=== Identity $a === $b
type in same order
Non-
!== $a !== $b Return TRUE if $a is not identical to $b
Identity
<> Inequality $a <> $b Return TRUE if $a is not equal to $b

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.

PHP supports the following data types:


 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

PHP Variable: Declaring string, integer, and float


Let's see the example to store string, integer, and float values in PHP variables.
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>

Output:
string is: hello string
integer is: 200
float is: 44.6

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.

Operations and Expressions Control Statement


PHP Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:


 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed

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
if(condition){
//code to be executed
}
Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
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
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Example
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
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
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}
Example
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
Output:
B Grade

PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.
Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}

Important points to be noticed about switch case:


1. The default is an optional statement. Even it is not important, that default must always be
the last statement.
2. There can be only one default in a switch statement. More than one default may lead to a
Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of
statement.
4. The break statement is optional to use in switch. If break is not used, all the statements
will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and less
readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.

PHP Switch Example


<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
number is equal to 20

PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use
loops.
Loops are used to execute the same block of code again and again, as long as a certain condition
is true.
In PHP, we have the following loop types:
 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

PHP For Loop


PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop. This means for
loop is used when you already know how many times you want to execute a block of code.
It allows users to put all the loop related statements in one place. See in the syntax given below:
Syntax
for(initialization; condition; increment/decrement){
//code to be executed
}
initialization - Initialize the loop counter value. The initial value of the for loop is done only
once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the condition is
false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.
Increment/decrement - It increments or decrements the value of the variable.

Example
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
Output:
1
2
3
4
5
6
7
8
9
10

PHP For Each Loop


The foreach loop is used to traverse the array elements. It works only on array and object. It will
issue an error if you try to use it with the variables of different data type.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate
the elements of an array.
In foreach loop, we don't need to increment the value.
Syntax
foreach( $array as $var ){
//code to be executed
}
?>
Example
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr ){
echo "Season is: $arr<br />";
}
?>
Output:
Season is: summer
Season is: winter
Season is: spring
Season is: autumn

PHP While Loop


PHP while loop can be used to traverse set of code like for loop. The while loop executes a block
of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from the
body of loop.
It should be used if the number of iterations is not known.
The while loop is also called an Entry control loop because the condition is checked before
entering the loop body. This means that first the condition is checked. If the condition is true, the
block of code will be executed.
Syntax
while(condition){
//code to be executed
}
Alternative Syntax
while(condition):
//code to be executed
endwhile;

PHP While Loop Example


<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:
1
2
3
4
5
6
7
8
9
10

PHP do-while loop


PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop
is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several times. If you have
to execute the loop at least once and the number of iterations is not even fixed, it is
recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked after executing the
code.
The do-while loop is very much similar to the while loop except the condition check. The main
difference between both loops is that while loop checks the condition at the beginning, whereas
do-while loop checks the condition at the end of the loop.
Syntax
do{
//code to be executed
}while(condition);
Example
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
Output:
1
2
3
4
5
6
7
8
9
10

PHP Break
PHP break statement breaks the execution of the current for, while, do-while, switch, and for-
each loop. If you use break inside inner loop, it breaks the execution of inner loop only.
The break keyword immediately ends the execution of the loop or switch structure. It breaks the
current flow of the program at the specified condition and program control resumes at the next
statements outside the 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
jump statement;
break;

PHP Break: inside loop


Let's see a simple example to break the execution of for loop if value of i is equal to 5.
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>
Output:
1
2
3
4
5
PHP continue statement
The PHP continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition.
The continue statement is used within looping and switch control structure when you
immediately jump to the next iteration.
The continue statement can be used with all types of loops such as - for, while, do-while, and
foreach loop. The continue statement allows the user to skip the execution of the code for the
specified condition.
Syntax
The syntax for the continue statement is given below:
jump-statement;
continue;
PHP Continue Example with for loop
<?php
//outer loop
for ($i =1; $i<=3; $i++) {
//inner loop
for ($j=1; $j<=3; $j++) {
if (!($i == $j) ) {
continue; //skip when i and j does not have same values
}
echo $i.$j;
echo "</br>";
}
}
?>
Output:
11
22
33

Array
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and object
in the PHP array. All PHP array elements are assigned to an index number by default.
There are two ways to define indexed array:
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";

Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
OUTPUT
Season are: summer, winter, spring and autumn

<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example
File: arrayassociative1.php
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

File: arrayassociative2.php
<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to store tabular data
in an array. PHP multidimensional array can be represented in the form of matrix which is
represented by row * column.
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

PHP Multidimensional Array Example


Let's see a simple example of PHP multidimensional array to display following tabular data. In
this example, we are displaying 3 rows and 3 columns.

Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000

<?php
$emp = array
(
array(1,"sonoo",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/>";
}
?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000

PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list
and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times, like in
other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use
of function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application because every logic is divided in the form of functions.
PHP User-defined Functions
We can declare and call user-defined functions easily. Let's see the syntax to declare user-defined
functions.
Syntax
function functionname(){
//code to be executed
}
PHP Functions Example
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
Hello PHP Function
PHP Function Arguments
We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and
Variable-length argument list.
Let's see the example to pass single argument in PHP function.
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>

Output:
Hello Sonoo
Hello Vimal
Hello John
Let's see the example to pass two argument in PHP function.
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference


Value passed to the function doesn't modify the actual value by default (call by value). But we can
do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need to
use ampersand (&) symbol before the argument name.
Let's see a simple example of call by reference in PHP.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello Call By Reference

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. Let's see a simple example of using
default argument value in PHP function.
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John

PHP Function: Returning Value


Let's see an example of PHP function that returns value.
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27

PHP Call By Value


PHP allows you to call function by value and reference both. In case of PHP call by value, actual
value is not modified if it is modified inside the function.
Let's understand the concept of call by value by the help of examples.
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with 'Call
By Value' string. But, printing $str variable results 'Hello' only. It is because changes are done in
the local variable $str2 only. It doesn't reflect to $str variable.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello

Basic Form Processing


We can create and use forms in PHP. To get form data, we need to use PHP super global $_GET
and $_POST.
The form request may be get or post. To retrieve data from get request, we need to use $_GET,
for post request $_POST.
GET vs. POST
Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 =>
value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and
values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are super global, which means that
they are always accessible, regardless of scope - and you can access them from any function,
class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?


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. However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

File: form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>

When to use POST?


Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send.
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.
File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password variable
echo "Welcome: $name, your password is: $password";
?>

File and Folder Access


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()


A better method to open files is with the fopen() function. This function gives you more options
than the readfile() function.
The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened. The following example also
generates a message if the fopen() function is unable to open the specified file:

Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:

Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
Open a file for write only. Erases the contents of the file or creates a new file if it
w
doesn't exist. File pointer starts at the beginning of the file
Open a file for write only. The existing data in file is preserved. File pointer starts at
a
the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
Open a file for read/write. Erases the contents of the file or creates a new file if it
w+
doesn't exist. File pointer starts at the beginning of the file
Open a file for read/write. The existing data in file is preserved. File pointer starts at
a+
the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists

PHP Read File - fread()


The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second
parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));

PHP Close File - fclose()


The fclose() function is used to close an open file.
It's a good programming practice to close all files after you have finished with them. You don't
want an open file running around on your server taking up resources!
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>

PHP Read Single Line - fgets()


The fgets() function is used to read a single line from a file.
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>

PHP Check End-Of-File - feof()


The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>

PHP Read Single Character - fgetc()


The fgetc() function is used to read a single character from a file.
The example below reads the "webdictionary.txt" file character by character, until end-of-file is
reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>

PHP File Create/Write


PHP Create File - fopen()
The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is
created using the same function used to open files.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for
writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The file will be created in the same
directory where the PHP code resides:
Example
$myfile = fopen("testfile.txt", "w")

PHP File Permissions


If you are having errors when trying to get this code to run, check that you have granted your
PHP file access to write information to the hard drive.

PHP Write to File - fwrite()


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.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the
string $txt that first contained "John Doe" and second contained "Jane Doe". After we finished
writing, we closed the file using the fclose() function.
If we open the "newfile.txt" file it would look like this:
John Doe
Jane Doe

PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an existing
file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just
wrote is present:
Mickey Mouse
Minnie Mouse

PHP Cookies
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the 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.
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.

PHP setcookie() function


PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can
access it by $_COOKIE superglobal variable.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
PHP Create/Retrieve a Cookie
The following example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use
the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:

Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

Check if Cookies are Enabled


The following example creates a small script that checks whether cookies are enabled. First, try
to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>

PHP Sessions
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.
When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: 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.

Tip: If you need a permanent storage, you may want to store the data in a database.

Start a PHP Session


A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

Get PHP Session Variable Values


Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>

Destroy a PHP Session


To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

PHP Connect to MySQL


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"

Example (MySQLi Object-Oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Close the Connection


The connection will be closed automatically when the script ends. To close the connection
before, use the following:

MySQLi Object-Oriented:
$conn->close();

You might also like