0% found this document useful (0 votes)
35 views70 pages

WT Unit 1

Uploaded by

Kundan Kumar
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)
35 views70 pages

WT Unit 1

Uploaded by

Kundan Kumar
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/ 70

INDEX

Sl no Content Pg no
1 Introduction to PHP 1-2
Overview of PHP
Characteristics of PHP
Advantages of PHP
Disadvantages of PHP

2 Declaring variables 2-5


Variable
Scope of variables
Local variables
Global variables
Static Variables

3 Data types 5-12


Scalar types
Compound types
Special types

4 Array 12-16
Indexed arrays
Associative arrays
Multidimensional arrays
5 Strings 17-18
6 Operator 18-23

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators

Categorizing operators

 Unary Operators
 Binary Operators
 Ternary Operators

Operator Precedence and Associativity


7 Expressions 24-24
8 Control structures 24-35
9 Functions 35-38
10 Reading data from web form controls like text boxes, radio buttons, 38-44
lists etc.
11 Handling File Uploads 45-46
12 Connecting to database (MySQL as reference) 47-51
Executing simple queries
Handling results
13 Handling sessions and cookies 51-55
14 File Handling in PHP 55-63
File operations like opening,
 closing,
 reading,
 writing,
 appending,
 deleting,
 etc. on text and binary files,
 listing directories.
INDEX FOR PROGRAMS

CODE No. CODE DESCRIPTION Pg no.

C 1.1 Code for a simple PHP Script 2

C 1.2 PHP Code for demonstrating scope of local variables 3

C 1.3 PHP Code for demonstrating scope of global variables 4

C 1.4 PHP Code for demonstrating scope of static variables 4

C 1.5 PHP Boolean Type Example Program 6

C 1.6 PHP Code for Integer Type 6

C 1.7 PHP Floating Point Type Example 8

C 1.8 PHP String Type ExampleProgram 9

C 1.9 PHP Array Type Example 9

C 1.10 Code for PHP Object Type 11

C 1.11 PHP Code for NULL Type 12

C 1.12 PHP program to demonstrate indexed array. 13

C 1.13 PHP program to demonstrate associative array. 14

C 1.14 PHP program to demonstrate associative array values 15

using foreach loop

C 1.15 PHP code snippet to create a two-dimensional array and 16

store elements in it.


C 1.16 PHP code to demonstrate the working of single quote 17

and double quote

C 1.17 PHP code “if” statement. 25

C 1.18 PHP Code for if else condition 26

C 1.19 PHP code for if else if else statement 27

C 1.20 PHP code for switch statement 29

C 1.21 PHP code for demonstrating “while” loop 31

C 1.22 PHP code for the “do-while” loop 32

C 1.23 PHP code for “for” loop 33

C 1.24 PHP code for “foreach loop” 34

C 1.25 PHP program for User Defined Function in PHP 35

C 1.26 PHP code for passing argument to a function. 36

C 1.27 PHP code to demonstrate Call by Value 37

C 1.28 PHP code to demonstrate the PHP Call by Reference 37

C 1.29 HTML code for reading input value from the user 39

C 1.30 HTML code for Radio button 40

C 1.31 Html code for demonstrating the working of “SUBMIT” 41

button

C 1.32 Complete PHP program to read input values 43


C 1.33 PHP and HTML code for uploading a file 46

C 1.34 PHP code for connecing for MySQL 48

C 1.35 PHP code to Create a MySQL Database 49

C 1.36 PHP code to Create a MySQL Table 49

C 1.37 PHP Code to check whether table is created or not. 49

C 1.38 PHP code to Insert Data Into MySQL 49

C 1.39 PHP Code to check whether data/record is inserted into 50

table properly or not.

C 1.40 PHP code to check whether a record is deleted or not. 50

C 1.41 PHP code to check whether a record is updated or not. 51

C 1.42 PHP code for creating a Session 52

C 1.43 PHP code to delete a session 53

C 1.44 PHP code to create a Cookie 54

C 1.45 PHP code to get the value of cookie 54

C 1.46 PHP code to delete a cookie 55

C 1.47 PHP file_exists function to determine if a file exists. 57

C 1.48 PHP code for reading the content of a file using fread() 59

C 1.49 PHP code to open a file in read mode 60

C 1.50 PHP code to demonstrate the working of opening of a 60


file in read mode using fgetc()

C 1.51 PHP code to append the data using fwrite() function 61

C 1.52 PHP code to delete a file using unlink. 62

C 1.53 PHP code to list files in a given directory using scandir 62

C 1.54 PHP code for reading a binary file 63


CSE Dept., CMREC

Introduction to PHP

PHP is a server scripting language, and a powerful tool for making dynamic
and interactive Web pages.

PHP was originally created by Rasmus Lerdorf in 1995, who added web forms that
communicate with database

PHP is a widely-used, free, and efficient alternative to competitors such


as Microsoft's ASP.

Overview of PHP

 PHP is an acronym for "PHP: Hypertext Preprocessor"


 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use

Characteristic features of PHP

 PHP can generate dynamic page content


 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in the database
 PHP can be used to control user-access
 PHP can encrypt data

Advantages of PHP

 Open source: It is developed and maintained by a large group of


PHP developers, this will help in creating a support community,
abundant extension library.
 Speed: It is relative fast since it uses much system resource.
 Easy to use: It uses C like syntax, so for those who are familiar with C, it's
very easy for them to pick up and it is very easy to create website scripts.
 Stable: Since it is maintained by many developers, so when bugs are found,
it can be quickly fixed.
 Powerful library support: Functional modules such as PDF, Graph etc
can be easily found

Page 1
CSE Dept., CMREC

 Built-in database connection modules: Database connection is easy using


PHP, since many websites are data/content driven, so we will use database
frequently, this will largely reduce the development time of web apps.
 Can be run on many platforms, including Windows, Linux and
Mac, it's easy for users to find hosting service providers.

Disadvantages of PHP

 Security : Since it is open sourced, so all people can see the source code, if
there are bugs in the source code, it can be used by people to explore the
weakness of PHP.
 Not suitable for large applications: Hard to maintain since it is not
very modular.
 Weak type: Implicit conversion may surprise unwary programmers and
lead to unexpected bugs. For example, the strings "1000" and "1e3"
compare equal because they are implicitly cast to floating point
numbers.

C 1.1 Code for a simple PHP Script

<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>

OUTPUT: My first PHP script!

Declaring variables

Variable: A variable in PHP is a name of memory location that holds data.

A variable is a temporary storage that is used to store data temporarily.

In PHP, a variable is declared using $ sign followed by variable name.


Page 2
CSE Dept., CMREC

Syntax of declaring a variable in PHP is given below:

$variablename=value;
Rules for variables declaration

 Variable always starts with the $ sign, followed by the variable name.
 Variable name must start with a letter or the underscore character.
 Variable name cannot start with a number.
 Variable name can only allow alpha-numeric characters and underscores
(A- z, 0-9, and _ ) other special character not allowed.
 Variable names are case sensitive ($var and $VAR are two
different variables).

Scope of variables:
Scope can be defined as the range of availability a variable has to the program
in which it
is declared. PHP variables can be one of four scope types:
 Local variables
 Global variables
 Static variables

Local variables
A variable declared in a function is considered local.
C 1.2 PHP Code for demonstrating scope of local variables

<?php
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x.";
}
assignx();
print "\$x outside of function is $x.";
?>
This will produce the following result.
$x inside function is 0.
Global$xoutsidevariablesoffunction is 4.

Page 3
CSE Dept., CMREC

A global variable can be accessed in any part of the program.

C 1.3 PHP Code for demonstrating scope of global variables


<?php
$somevar = 15; function addit() { GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
This will produce the following result. Somevar is 16

Static Variables

In contrast to the variables declared as function parameters, which are destroyed on


the function's exit, a static variable will not lose its value when the function exits
and will still hold that value should the function be called again. C 1.4 PHP Code
for demonstrating scope of static variables

<?php
function keep_track() { STATIC $count = 0;
$count++; print $count; print " ";
}
keep_track(); keep_track(); keep_track();
?>
This will produce the following result.

Page 4
CSE Dept., CMREC

1
2
3

Data types
PHP has built-in Data Types which is divided into three catagories Scalar
types,Compound types and Special types. PHP has total eight (8) different data
types to work with.
Scalar types

 boolean
 integer
 float
 string

Compound types

 array
 object

Special types

 resources
 NULL

Boolean Type
In PHP the boolean data type is a primitive data type they have only two
possible values true and false. This is a fundamental data type and very common
in computer programs.

C 1.5 PHP Boolean Type Example Program

Page 5
CSE Dept., CMREC

<?php

$isVisited = False;

$isVisited = userVisited();

if ($isVisited) {

echo "User visited";

} else {

echo "User did not visited";

?>

Integer Type
Integer is a whole number. PHP integer is the same as the long data type in C. It is
a number between -2,147,483,648 and +2,147,483,647. Integers can be specified
in three different notations in PHP. Decimal, hexadecimal and octal. Octal values
are preceded by 0, hexadecimal by 0x.
Rules for integers

 Integer must have at least one digit (0-9)


 Integer must not have a decimal point
 Integer can be either positive or negative
 Integer cannot contain comma or blanks

C 1.6 PHP Code for Integer Type

Page 6
CSE Dept., CMREC

<?php

$w = 2300;

var_dump($w);

$x = -560; // This is negative

number var_dump($x);

$y = 0x2C; // This hexadecimal

number var_dump($y);

$z = 047; // This octal

number var_dump($z);

?>

This will produce following result

int(2300)

int(-560)

int(44)

int(22)

Floating Point Numbers


Float may contain any decimal number or a number in exponential form.Floating
point numbers in PHP can be larger than integers. PHP recognizes two types of
floating point numbers. The first is a simple numeric literal with a decimal point
and second is a floating-point number written in scientific notation.

Page 7
CSE Dept., CMREC

C 1.7 PHP Floating Point Type Example

<?php

$var1 = 2.786;

$var2 = 2.2e3;

$var3 = 1E-10;

$var4 = 12345678923445;

var_dump($var1);

var_dump($var2);

var_dump($var3);

var_dump($var4);

?>

This will produce following result

float(2.786)

float(2200)

float(1.0E-10)

float(12345678923445)

String Type
String is a series of single characters such as "Hello PHP". Most of working with
Web pages is about working with strings. In PHP a string must be delimited by one
of four syntaxes: single quotes, double quotes, heredocs, and nowdocs.

Page 8
CSE Dept., CMREC

C 1.8 PHP String Type ExampleProgram


<?php

$var1 = "My First PHP Program!"; echo $var1;


$var1 = 'My Second PHP Program!'; echo $var1;
?>

This will produce following result:

My First PHP Program! My Second PHP Program!

Array Type
In simple word array is complex data type which hold collection of related
data elements.Each of the elements can be accessed by an index.
C 1.9 PHP Array Type Example

<?php

$months = array("June", "July", "August", "September", "October");

print_r($months);

?>

This will produce following result

Array

[0] => June

[1] => July

[2] => August

[3] => September

[4] => October

Page 9
CSE Dept., CMREC

Object Type
In simple word object are instances of class definitions. Objects are user defined
data types normaly used to define properties/attributes of object. First we need
to declear a class of object that can contain properties and methods.

Page 10
CSE Dept., CMREC

C 1.10 Code for PHP Object Type


<?php

class Books{

var $price; /* Member variables

*/ var $title;

function setPrice($price_par){ /* Member functions */

$this->price = $price_par;

function getPrice(){

echo "Book Price: $" .$this->price ."<br/>";

function setTitle($title_par){

$this->title = $title_par;

function getTitle(){

echo "Title: ".$this->title . "<br/>";

$book = new Books(); // creating instance of class Book

$book->setTitle("PHP Tutorials Book"); // setting properties values

$book->setPrice(123);

$book->getTitle(); // show properties

$book->getPrice();

?>

Page 11
CSE Dept., CMREC

This will produce following result


Title: PHP Tutorials Book
Book Price: $123

Resource Type
Resources are special data types. They hold a reference to an external
resource (such as database connections).
NULL Type
NULL is a special type that only have one possible value and that's null. This type
is also treated as a language constant in PHP and is case-insensitive. PHP considers
all undefined variables to be of type NULL.
C 1.11 PHP Code for NULL Type

<?php

$var="Hello world!";

$var=null;

var_dump($var);

?>

This will produce following result

NULL

Array:
An array is a data structure that stores one or more similar type of values in
a single value.
In PHP, the array() function is used to create an array:

array();

Page 12
CSE Dept., CMREC

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

 Indexed arrays

PHP index is represented by number which starts from 0.Number, string and
object can be stored 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: index can be assigned automatically (index always starts at 0)

$cars = array("Volvo", "BMW", "Toyota");

2nd way: index can be assigned manually

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

C 1.12 PHP program to demonstrate indexed array.


<!DOCTYPE html>

<html>

<body>

<?php

$cars = array("Volvo", "BMW", "Toyota");

echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

?>

</body>

</html>

Page 13
CSE Dept., CMREC

Output:

I like Volvo, BMW, Toyota

In the above example, the PHP creates an indexed array named $cars,
assigns three elements to it, and then prints a text containing the
array values:

Associative arrays

Associative arrays are arrays that use named keys that are assigned to them.

There are two ways to create an associative array:

1st way: $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

2nd way: $age['Peter'] = "35";


$age['Ben'] = "37";
$age['Joe'] = "43";

C 1.13 PHP program to demonstrate associative array.


<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is " . $age['Pet

</body>
</html>

output:

Peter is 35 years old.

Page 14
CSE Dept., CMREC

C 1.14 PHP program to demonstrate associative array values using


foreach loop

<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";
}
?>

</body>
</html>

output:

Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43

Multidimensional arrays

A multidimensional array is an array containing one or more arrays.

 For a two-dimensional array two indices are needed to select an element


 For a three-dimensional array three indices are needed to select an element

Page 15
CSE Dept., CMREC

C 1.15 PHP code snippet to create a two-dimensional array and store elements in
it.

$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

<!DOCTYPE html>
<html>
<body>
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";

echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";

echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";

echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";


?>
</body>
</html>
OUTPUT:
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.

#NOTE: The above elements can be retrieved through for loop.

Page 16
CSE Dept., CMREC

PHP string

A PHP string is a sequence of characters i.e. used to store and manipulate text.
There are 2 ways to specify string in PHP.

 Single quoted: A single-quoted string preserves its content as it is. It does


not interpret escape sequences, e.g., '\n' will be treated as a back-slash
followed by n (2 characters); not the newline character
 Double quoted: A double-quoted string performs variable substitution (or
variable evaluation) and interprets all escape sequences starting with
backslash \ (such as \t for tab, \n for newline and \r for carriage return, \" for
double-quote, \\ for backslash, etc.).

C 1.16 PHP code to demonstrate the working of single quote and double quote

<?php

$count = 5;

echo "<p>The count is $count.\n</p>";// Substitutes variable with its value echo '<p>The count is $count.
echo '<p>The count is '.$count.'.</p>'; // Use string concatenation (.) echo '<p>The count is ', $count, '.</

Page 17
CSE Dept., CMREC

OUTPUT:

The count is 5.[newline]


The count is $count.\n
The count is 5.
The count is 5.
The count is 5.

OPERATORS:

PHP Operator is a symbol i.e used to perform operations on operands.

PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators

 Arithmetic operators: The PHP arithmetic operators are used with


numeric values to perform common arithmetical operations, such as
addition, subtraction, multiplication etc.

Page 18
CSE Dept., CMREC

Assignment operators: The PHP assignment operators are used with


numeric values to write a value to a variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set
to the value of the assignment expression on the right.

Comparison operators:

The PHP comparison operators are used to compare two values (number or string):

Page 19
CSE Dept., CMREC

Increment/Decrement operators

 The PHP increment operators are used to increment a variable's value.


 The PHP decrement operators are used to decrement a variable's value.

Logical operators

The PHP logical operators are used to combine conditional statements.

Page 20
CSE Dept., CMREC

String operators

PHP has two operators that are specially designed for strings.

Array operators

The PHP array operators are used to compare arrays.

Operators can be categorized on behalf of operands. They can be categorized in 3


forms:

Page 21
CSE Dept., CMREC

o Unary Operators: works on single operands such as ++, -- etc.


o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

In general, operators have a set precedence, or order, in which they are evaluated.
Operators also have associativity, which is the order in which operators of the
same precedence are evaluated. This order is generally left to right (called left for
short), right to left (called right for short), or not relevant.

Operator Precedence

The order in which operators in an expression are evaluated depends on


their relative precedence. For example, consider

2+4*3
The addition and multiplication operators have different precedence, with
multiplication higher than addition. So the multiplication happens before
the addition, giving 2 + 12, or 14, as the answer.

To force a particular order, operands can be grouped with the appropriate operator in
parentheses. In our previous example, to get the value 18, use this expression:

(2 + 4) * 3
In this table, operators with the lowest precedence are at the bottom, and
precedence decreases going down in the table.

Page 22
CSE Dept., CMREC

Operators
Additional Associativity non
Information
clone new —associative left
clone and new

array ()

” arithmetic right

++ —— (int) (float) (strinq) (array) (object) (bool) @ increment/decrement and types right

ins t ance
types non-associative
of

logical (negation) right

arithmetic left
/96

arithmetic and string concatenation left


+-

bitwise (shift) left

comparison non—associative

comparison non-associative

bitwise AND left

bitwise FOR left

bitwise OR left

logical AND left


&&

logical OR left

ternary left

as siqnment right

logical left
and
logical left
xor

logical left
or
many uses (comma) left

Page 23
CSE Dept., CMREC

EXPRESSIONS: An expression is a combination of variables, literal values


and operators, that can be evaluated to produce a value.

The simplest expressions are literal values and variables. A literal value
evaluates to itself, while a variable evaluates to the value stored in the variable.

More complex expressions can be formed using simple expressions and operators.
A statement in PHP is any expression that is followed by a semicolon (;).

Any sequence of valid PHP statements that is enclosed by the PHP tags is a valid
PHP program.

$greeting = "Welcome to PHP!";

CONTROL STRUCTURES:

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 - The if Statement

The if statement executes some code if one condition is true.

Syntax
if (condition) {
code to be executed if condition is true;
}

The example below will output "Have a good day!" if the current time (HOUR)
is less than 20:

Page 24
CSE Dept., CMREC

C 1.17 PHP code “if” statement.


<!DOCTYPE html>
<html>
<body>

<?php
$ t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>

</body>
</html>

OUTPUT:
Have a good day!

PHP - The if...else Statement

The if. . .else statement executes some code if a condition is true and another code
if that condition is false.

Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

The example below will output "Have a good day!" if the current time is less
than 20, and "Have a good night!" otherwise:

Page 25
CSE Dept., CMREC

C 1.18 PHP Code for if else condition

<!DOCTYPE html>

<html>

<body>

<?php

$t = date("H");

if ($t < "20") {

echo "Have a good day!";

} else {

echo "Have a good night!";

?>

</body>

</html>

OUTPUT:

Have a good day!

PHP - The elseif...else Statement


if...
The if else statement executes different codes for more than two
elseif.......
conditions.

Page 26
CSE Dept., CMREC

Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}

The example below will output "Have a good morning!" if the current time is
less than 10, and "Have a good day!" if the current time is less than 20.
Otherwise it will output "Have a good night!":

C 1.19 PHP code for if else if else statement

<!DOCTYPE html>
<html>
<body>

<?php
$t = date("H");
echo "<p>The hour (of the server) is ". $t;
echo ", and will give the following message:</p>";

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

</body>
</html>

Page 27
CSE Dept., CMREC

OUTPUT:

The hour (of the server) is 04, and will give the following message:

Have a good morning!

PHP switch Statement


The switch statement is used to perform different actions based on
different conditions.

Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

First we have a single expression n (most often a variable), that is evaluated


once. The value of the expression is then compared with the values for each case
in the structure.
If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.

Page 28
CSE Dept., CMREC

C 1.20 PHP code for switch statement

<!DOCTYPE html>
<html>
<body>

<?php
$favcolor = "red";

switch ($favcolor) { case "red":


echo "Your favorite color is red!"; break;
case "blue":
echo "Your favorite color is blue!"; break;
case "green":
echo "Your favorite color is green!"; break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

</body>
</html>

OUTPUT:
Your favorite color is red!

Page 29
CSE Dept., CMREC

PHP Loops

Often when a code is written, the programmer wants the same block of code to run
over and over again in a row. Instead of adding several almost equal code-lines in a
script, we can use loops to perform a task like this.

In PHP, we have the following looping statements:

 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

The PHP while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax
while (condition is true) {
code to be executed;
}

The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will
continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase
by 1 each time the loop runs ($x++):

Page 30
CSE Dept., CMREC

C 1.21 PHP code for demonstrating “while” loop

<!DOCTYPE html>
<html>
<body>

<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>

</body>
</html>

Output:
The number is:
1 The number is:
2 The number is:
3 The number is:
4 The number is:
5

The PHP do...while Loop

The do...while loop will always execute the block of code once, it will then
check the condition, and repeat the loop while the specified condition is true.

Syntax
do {
code to be executed;
} while (condition is true);

The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop
will write some output, and then increment the variable $x with 1. Then the

Page 31
CSE Dept., CMREC

condition is checked (is $x less than, or equal to 5?), and the loop will continue
to run as long as $x is less than, or equal to 5:

C 1.22 PHP code for the “do-while” loop

<!DOCTYPE html>
<html>
<body>

<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

</body>
</html>

Output:
The number is:
1 The number
is: 2 The
number is: 3 The
number is: 4
The number is:
5

In a do while loop the condition is tested AFTER executing the statements


within the loop. This means that the do while loop would execute its statements
at least once, even if the condition is false the first time.

Page 32
CSE Dept., CMREC

The PHP for Loop

The for loop is used when the programmer knows in advance how many times the
script should run.

Syntax

for (init counter; test counter; increment counter) {


code to be executed;
}

Parameters:

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value

C 1.23 PHP code for “for” loop

<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>";
}
?>

</body>
</html>

Page 33
CSE Dept., CMREC

OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.

Syntax
foreach ($array as $value) {
code to be executed;
}

For every loop iteration, the value of the current array element is assigned
to $value and the array pointer is moved by one, until it reaches the last
array element.

C 1.24 PHP code for “foreach loop”


<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) { echo "$value <br>";


}
?>
</body>
</html>

Page 34
CSE Dept., CMREC

Output:
red
green
blue
yellow

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.

 A function is a block of statements that can be used repeatedly in a program.


 A function will not execute immediately when a page loads.
 A function will be executed by a call to the

function. Creating a User Defined Function in PHP

A user defined function declaration starts with the word "function":

Syntax
function functionName() {
code to be executed;
}

C 1.25 PHP program for User Defined Function in PHP

<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() { echo "Hello world!";
}
writeMsg();
?>
</body>
</html>

Page 35
CSE Dept., CMREC

Output:
Hello world!

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like


a variable.

Arguments are specified after the function name, inside the parentheses.
Any number of arguments can be added, separated by a comma.

C 1.26 PHP code for passing argument to a function.


<!DOCTYPE html>
<html>
<body>

<?php
function familyName($fname) { echo "$fname Stark.<br>";
}

familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyN


?>

</body>
</html> Output: Jani Stark Hege Stark Stale Stark
Kai Jim Stark Borge Stark

Page 36
CSE Dept., CMREC

PHP Call By Value

PHP allows a programmer 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.

C 1.27 PHP code to demonstrate Call by Value

<?php

function adder($str2) {
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello

PHP Call By Reference

In case of PHP call by reference, actual value is modified if it is modified inside


the function. In such case, use & (ampersand) symbol with formal arguments. The
& represents reference of the variable.
C 1.28 PHP code to demonstrate the PHP Call by Reference

<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
Output:
11
Page 37
CSE Dept., CMREC

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 there is no need to write the logic many
times. By the use of function, 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.

Reading data from web form controls like text boxes, radio buttons, lists etc.
The <form> Element

The HTML <form> element defines a form that is used to collect user input:

<form>
.
form elements
.
</form>

An HTML form contains form elements.

Form elements are different types of input elements, like text fields,
checkboxes, radio buttons, submit buttons, and more.

The <input> Element

The <input> element is the most important form element.

The <input> element can be displayed in several ways, depending


on the type attribute.

Page 38
CSE Dept., CMREC

C 1.29 HTML code for reading input value from the user

<!DOCTYPE html>
<html>
<body>

<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>
</body>
</html> output: First name:

Last name:

Radio Button Input

<input type="radio"> defines a radio button.

Radio buttons let a user select ONE of a limited number of choices:

Page 39
CSE Dept., CMREC

C 1.30 HTML code for Radio button

<!DOCTYPE html>

<html>

<body>

<form>

<input type="radio" name="gender" value="male" checked> Male<br>


<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other

</form>

</body>

</html>

Output:

Male
Female Other

The Submit Button

<input type="submit"> defines a button for submitting the form data to a form-
handler.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form's action attribute:

Page 40
CSE Dept., CMREC

C 1.31 Html code for demonstrating the working of “SUBMIT” button

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php"> First name:<br>


<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>

<p>If user clicks the "Submit" button, the form-data will be sent to a page called "/action_page.

</body>
</html> output: First name:
Mickey
Last name:
Mouse

Submit

If user clicks the "Submit" button, the form-data will be sent to a page
called "/action_page.php".

Page 41
CSE Dept., CMREC

The Action Attribute

The action attribute defines the action to be performed when the form is submitted.

Normally, the form data is sent to a web page on the server when the user clicks on
the submit button.

In the example above, the form data is sent to a page on the server called
"/action_page.php". This page contains a server-side script that handles the form
data:

Syntax

<form action="/action_page.php">

If the action attribute is omitted, the action is set to the current page.

The Target Attribute

The target attribute specifies if the submitted result will open in a new
browser tab, a frame, or in the current window.

The default value is "_self" which means the form will be submitted in the
current window.

To make the form result open in a new browser tab, use the value "_blank":

Syntax

<form action="/action_page.php" target="_blank">

The Method Attribute

The method attribute specifies the HTTP method (GET or POST) to be used
when submitting the form data:

<form action="/action_page.php" method="get">

or

<form action="/action_page.php" method="post">

Page 42
CSE Dept., CMREC

C 1.32 Complete PHP program to read input values

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_S ELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span> <br><br>

E-mail: <input type="text" name="email" value="<?php echo $email;?>">


<span class="error">* <?php echo $emailErr;?></span> <br><br>
Website: <input type="text" name="website" value="<?php echo
$website;?>"> <span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $com
ment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo
$genderErr;?></span> <br><br>
<input type="submit"
name="submit" value="Submit">
</form>

Contd…

Page 43
CSE Dept., CMREC

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

OUTPUT:

PHP Form Validation Example

* required field.

Name: *

E-mail: *

Website:

Comment:

Gender: Female Male *

Submit

Page 44
CSE Dept., CMREC

Handling File Uploads

PHP allows to upload single and multiple files through few lines of code only.

PHP file upload features allows to upload binary and text files both. Moreover, a
programmer can have the full control over the file to be uploaded through PHP
authentication and file operation functions.

PHP $_FILES

The PHP global $_FILES contains all the information of file. By the help of
$_FILES global, the programmer can get file name, file type, file size, temp file
name and errors associated with file.

Here, assume that file name is filename.

$_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.

Page 45
CSE Dept., CMREC

C 1.33 PHP and HTML code for uploading a file

File: uploadform.html
<form action="uploader.php" method="post" enctype="multipart/form-data">
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/> </form>

File: uploader.php
<?php
$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);

if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path))
{ echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>

Page 46
CSE Dept., CMREC

Connecting to database (MySQL as reference)

MySql:

 MySQL is a open-source database system (free to download and use) on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms, supports many operating systems
with many languages like PHP, PERL, C, C++, JAVA, etc.
 MySQL is quicker than other databases so it can work well even with the large data set.

Benefits of using PHP and MySql:

 Dynamic: Since MySql is implemented at server side and PHP is a server side scripting
language, dynamic pages with customized features can be created.

 User friendly: PHP provides a user-friendly and interactive website or web application
and also enables visitors to freely interact while producing a very flexible and
dynamic content.

 Ease of use: PHP and MySql are easy to learn as compared to the
other programming languages. The PHP syntax can easily be parsed.

 HTML embedded codes: PHP is no doubt a stable and cross-platform compatible


language. And because of its ability to decode HTML, there is no need to have
separate coding for PHP.
 Cost effective: PHP along with MySql implementation is very cost-effective. It is worth
knowing that PHP/MYSQL combo runs perfectly well on low cost, low end hardware.

 Interoperability: The advantage of PHP is its interoperability with multiple


operating systems and servers. PHP solves the portability issues with one or
more use of the operating systems.

Page 47
CSE Dept., CMREC

Establishing a Connection to MySQL

Before data in the MySQL database can be accessed,connect PHP program to the server.

C 1.34 PHP code for connecing for MySQL

<?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";
?>

PHP mysql_close()

PHP mysql_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false.
Syntax:
mysql_close($conn);

Page 48
CSE Dept., CMREC

C 1.35 PHP code to Create a MySQL Database

$sql = "CREATE DATABASE myDB";


if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

C 1.36 PHP code to Create a MySQL Table

$sql = "CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY
KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL,

reg_date TIMESTAMP
)"; email VARCHAR(50),

C 1.37 PHP Code to check whether table is created or not.

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


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

C 1.38 PHP code to Insert Data Into MySQL


//After a database and a table have been created, start adding data in them.
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')";

Page 49
CSE Dept., CMREC

C 1.39 PHP Code to check whether data/record is inserted into table properly or not.

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


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;

Select Data From a MySQL Database


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

Syntax
SELECT * FROM table_name

$sql = "SELECT id, firstname, lastname FROM MyGuests";

Delete Data From a MySQL Table


The DELETE statement is used to delete records from a table

$sql = "DELETE FROM MyGuests WHERE id=3";

C 1.40 PHP code to check whether a record with id=3 is deleted or not.
if ($conn->query($sql) === TRUE) { echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;

Update Data In a MySQL


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

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

Page 50
CSE Dept., CMREC

C 1.41PHP code to check whether a record with lastname='Sam' is updated or not.


if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;

Handling sessions and cookies


SESSION:

 A session is a global variable stored on the server.


 Each session is assigned a unique id which is used to retrieve stored values.
 Whenever a session is created, a cookie containing the unique session id is stored on the
user’s computer and returned with every request to the server.
 Sessions have the capacity to store relatively large data compared to cookies.
 The session values are automatically deleted when the browser is closed.
 Session variables are stored in the $_SESSION array variable.

Fig: PHP Session

Page 51
CSE Dept., CMREC

Creating a Session

In order to create a session, the PHP session_start function must be first called and then store
user values in the $_SESSION array variable.

C 1.42 PHP code for creating a Session

<?php

session_start(); //start the PHP_session

function if(isset($_SESSION['page_count']))

$_SESSION['page_count'] += 1;

else

$_SESSION['page_count'] = 1;

echo 'You are visitor number ' .


$_SESSION['page_count']; ?>

Output:

You are visitor number 1

Destroying Session Variables

The session_destroy() function is used to destroy the whole Php session variables.

In order to destroy only a session single item, use the unset() function.

Page 52
CSE Dept., CMREC

C 1.43 PHP code to delete a session

<?php
session_destroy(); //destroy entire session
?>
<?php
unset($_SESSION['product']); //destroy product session item
?>

 session_destroy removes all the session data including cookies associated with the session.
 unset only frees the individual session variables.

PHP Cookies

Http is a stateless protocol. cookies allow us to track the state of the application using small
files stored on the user’s computer.

The path were the cookies are stored depends on the browser.

Definition: A cookie is a small file with the maximum size of 4KB that the web server stores
on the client computer.

It is used to recognize the user.

Once a cookie has been set, all page requests that follow return the cookie name and value.

A cookie can only be read from the domain that it has been issued from.

Fig: Working of a PHP Cookie

Page 53
CSE Dept., CMREC

Here,

1) A user requests for a page that stores cookies

2) The server sets the cookie on the user’s computer

3) Other page requests from the user will return the cookie name and value

Syntax

setcookie(name, value, expire, path, domain, secure, http_only);

Creating Cookies

C 1.44 PHP code to create a Cookie

<?php

setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);

?>

where,

 Php“setcookie” is the PHP function used to create the cookie.


 “cookie_name” is the name of the cookie that the server will use when retrieving
its value from the $_COOKIE array variable. It’s mandatory.
 “cookie_value” is the value of the cookie and its mandatory
 “[expiry_time]” is optional; it can be used to set the expiry time for the cookie

Retrieving the Cookie value

Create another file named “cookies_read.php” with the following code.

C 1.45 PHP code to get the value of cookie


<?php

print_r($_COOKIE); //output the contents of the cookie array variable

?>

Output:

Array ( [PHPSESSID] => h5onbf7pctbr0t68adugdp2611 [user_name] => RAM )

Page 54
CSE Dept., CMREC

Delete Cookies

 In order to destroy a cookie before its expiry time, then set the expiry time to a time
that has already passed.
 Create a new filed named cookie_destroy.php with the following code

C 1.46 PHP code to delete a cookie

<?php

setcookie("user_name", "SAM", time() - 360,'/');

?>

File Handling in PHP:


File Operations like opening, Closing, Reading, Writing,Appending, Deleting etc. on text and
Binary files, Listing directories.

FILE: A file is simply a resource for storing information on a computer.

Files are usually used to store information such as;

 Configuration settings of a program


 Simple data such as contact names against the phone numbers.
 Images, Pictures, Photos, etc.

PHP files Functions

PHP provides a convenient way of working with files via its rich collection of built in functions.

Operating systems such as Windows and MAC OS are not case


sensitive while Linux or Unix operating systems are case sensitive.

Adopting a naming conversion such as lower case letters only for file naming is a good
practice that ensures maximum cross platform compatibility.

Page 55
CSE Dept., CMREC

PHP File_exists Function

This function is used to determine whether a file exists or not.

 It comes in handy when we want to know if a file exists or not before processing it.
 This function can also be used when creating a new file and user wants to ensure that
the file does not already exist on the server.

The file_exist function has the following syntax.

<?php

file_exists($filename);

?>

HERE,

 “file_exists()” is the PHP function that returns true if the file exists and false if it does
not exist.
 “$file_name” is the path and name of the file to be checked

Page 56
CSE Dept., CMREC

C 1.47 PHP code uses file_exists function to determine if the file my_settings.txt exists.
<?php

if (file_exists('my_settings.txt'))

echo 'file found!';

else

echo 'my_settings.txt does not exist';

?>

PHP fopen Function

The fopen function is used to open files. It has the following syntax

<?php

fopen($file_name,$mode,$use_include_path,$context);

?>

HERE,

 “fopen” is the PHP open file function


 “$file_name” is the name of the file to be opened
 “$mode” is the mode in which the file should be opened

Page 57
CSE Dept., CMREC

PHP fwrite() function

The fwrite() function is used to write files.

It has the following syntax

<?php

fwrite($handle, $string, $length);

?>

HERE,

 “fwrite” is the PHP function for writing to files


 “$handle” is the file pointer resource
 “$string” is the data to be written in the file.
 “$length” is optional, can be used to specify the maximum file length.

PHP Read File

PHP provides various functions to read data from file. There are different functions that allows to
read all file data, read data line by line and read data character by character.

Page 58
CSE Dept., CMREC

The available PHP file read functions are given below.

 fread()
 fgets()
 fgetc()

C 1.48 PHP code for reading the content of a file using fread()

<?php

$filename = "c:\\file1.txt";

$fp = fopen($filename, "r");//open file in read mode

$contents = fread($fp, filesize($filename));//read file echo "<pre>$contents</pre>";//printing data of file fclose($fp


?>

Output:

this is first line this is another line this is third line

Page 59
CSE Dept., CMREC

PHP Read File - fgets()

The PHP fgets() function is used to read single line from the file.

C 1.49 PHP code to open a file in read mode


<?php

$fp = fopen("c:\\file1.txt", "r");//open file in read mode echo fgets($fp);


fclose($fp);

?>

Output

This is first line

PHP Read File - fgetc()

The PHP fgetc() function is used to read single character from the file. To get all data using
fgetc() function, use !feof() function inside the while loop.

C 1.50 PHP code to demonstrate the working of opening of a file in read mode using fgetc()

<?php

$fp = fopen("c:\\file1.txt", "r");//open file in read mode while(!

feof($fp)) {

echo fgetc($fp);

fclose($fp);

?>

Output:

this is first line this is another line this is third line

Page 60
CSE Dept., CMREC

Difference between readfile() and fread():

• Function readfile() => is a simple function used to read the data from a file without
doing any further text processing like calculating the size of data.
• Function fread() => also do the same thing but with the difference that the
programmer can specify the size of the data to be read from the file. This can be
helpful when there are larger files and user wants to read some chunks of data from it.

PHP fclose() function

Is is used to close a file in php which is already open

It has the following syntax.

<?php

fclose($handle); ?>

 “fclose” is the PHP function for closing an open file


 “$handle” is the file pointer resource.

PHP append to File - fwrite()

The PHP fwrite() function is used to write and append data into file.

C 1.51 PHP code to append the data using fwrite() function


<?php

$fp = fopen('data.txt', 'a');//opens file in append mode fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data'); fclose($fp);
echo "File appended successfully";

?>

Output: data.txt

welcome to php file write this is additional text appending data

Page 61
CSE Dept., CMREC

Deleting a file

The unlink function is used to delete the file. The code below illustrates the implementation.

C 1.52 PHP code to delete a file using unlink.


<?php

if (!unlink('my_settings_backup.txt'))

echo "Could not delete file";

else

echo "File 'my_settings_backup.txt' successfully deleted";

?>

Listing file PHP

C 1.53 PHP code to list files in a given directory using scandir


<?php
$dir= '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1); print_r($files1); print_r($files2);
?>

• use 0 for ascending order, and 1 for descending order.


• The print_r PHP function is used to return an array in a human readable form.

Page 62
CSE Dept., CMREC

Binary file reading


• A binary file cannot be read as it is in raw binary format in language.
• PHP uses a unique function called unpack().

C 1.54 PHP code for reading a binary file

<?php
$fp = fopen("file", "rb");
$data = fread($fp, 4);
// 4 is the byte size of a whole on a 32-bit PC.
$number = unpack("i", $data);
echo $number[1];
?>

$fp=resource handle, 4=length(in bytes)

unpack():Returns an associative array containing unpacked elements of binary string.

Summary of file functions

Page 63

You might also like