0% found this document useful (0 votes)
10 views24 pages

Unit1 WT

The document provides an overview of PHP, a server-side scripting language used for web development, highlighting its simplicity, efficiency, and flexibility. It covers key concepts such as variable declaration, data types, control structures, and file handling, as well as the syntax and common uses of PHP. Additionally, it explains variable scope, naming rules, and different data types including integers, floats, booleans, strings, arrays, and objects.

Uploaded by

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

Unit1 WT

The document provides an overview of PHP, a server-side scripting language used for web development, highlighting its simplicity, efficiency, and flexibility. It covers key concepts such as variable declaration, data types, control structures, and file handling, as well as the syntax and common uses of PHP. Additionally, it explains variable scope, naming rules, and different data types including integers, floats, booleans, strings, arrays, and objects.

Uploaded by

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

UNIT- I Characteristics of PHP:

Introduction to PHP:
Simplicity
Declaring variables,
Efficiency
data types, arrays, strings,
operators, expressions, Security
controlstructures, Flexibility
functions, Familiarity
Reading data from web form controls like text boxes, radio buttons, lists etc., All PHP code must be included inside one of the three special markup tags are recognized
Handling File Uploads. Connecting to database (MySQL as reference), executing by the PHP Parser.
simple queries,handling results,
Handling sessions and cookies
File Handling in PHP: File operations like opening, closing, reading, writing,
appending, deleting etc. on text and binary files, listing directories.

Most common tag is the <?php...?>

PHP INTRODUCTION SYNTAX OVERVIEW:


Canonical PHP tags The most universally effective PHP tag style is:
<?php...?>
Short-open (SGML-style) tags Short or short-open tags look like this:
<?...?>
HTML script tags HTML script tags look like this:
PHP is a recursive acronym for "PHP: Hypertext Preprocessor". <script language="PHP">...</script>
PHP is a server side scripting language that is embedded in HTML. PHP scripts are
executed on the server PHP - VARIABLE TYPES
It is used to manage dynamic content, databases, session tracking, even build entire e- The main way to store information in the middle of a PHP program is by using a variable.
commerce sites. Here are the most important things to know about variables in PHP.
PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL,
A variable is used to store information.
Generic ODBC, Microsoft SQL Server , etc.)
PHP is an open source software. All variables in PHP are denoted with a leading dollar sign
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on ($). The value of a variable is the value of its most recent
the Unix side. The MySQL server, once started, executes even very complex queries with assignment.
huge result sets in record-setting time. Variables are assigned with the = operator, with the variable on the left-hand side and
PHP supports a large number of major protocols such as POP3, IMAP, and
the expression to be evaluated on the right.
LDAP. PHP is forgiving: PHP language tries to be as forgiving as possible.
Variables can, but do not need, to be declared before
PHP Syntax is C-Like.
assignment. Variables used before they are assigned have
Common uses of PHP: default values.
PHP performs system functions, i.e. from files on a system it can create, open, read, write,
and close them. The other uses of PHP are: PHP does a good job of automatically converting types from one to another when
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can necessary.
send data, return data to the user. PHP variables are Perl- like.
You add, delete, and modify elements within your database thru PHP. Syntax: $var_name = value;
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your
website. It can encrypt data.
Eg: creating a variable containing a string, and a variable containing a number:
A variable declared within a function has a LOCAL SCOPE and can only be accessed
<?php within that function:
$txt="HelloWorld!"; Example
$x=16; <?php
?> function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
PHP is a Loosely Typed Language: }
myTest(); // using x outside the function will generate an
In PHP, a variable does not need to be declared before adding a value to it.
error echo "<p>Variable x outside function is: $x</p>";
You do not have to tell PHP which data type the variable is ?>
PHP automatically converts the variable to the correct data type, depending on its value. You can have local variables with the same name in different functions, because local
variables are only recognized by the function in which they are declared.
Naming Rules for Variables
A variable name must start with a letter or an underscore "_"
PHP The global Keyword
A variable name can only contain alpha- numeric characters and underscores (a-z,
A-Z, 0-9, and _ ) The global keyword is used to access a global variable from within a function. To do this,
A variable name should not contain spaces. If a variable name is more than one word, it use the global keyword before the variables (inside the function):
should be separated with an underscore ($my_string), or with capitalization/Camel Example
notation ($myString) <?php
$x = 5; $y = 10;
PHP Variables Scope function myTest()
In PHP, variables can be declared anywhere in the script. The scope of a variable is the {
part of the script where the variable can be referenced / used. PHP has three different global $x, $y;
variable scopes: $y = $x+ $y; }
local myTest();
global echo $y; // outputs 15
static ?>

Global and Local Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be accessed PHP also stores all global variables in an array called $GLOBALS[index]. The index holds
outside a function: the name of the variable. This array is also accessible from within functions and can be used
Example to update global variables directly. The example above can be rewritten like this:
<?php Example
$x = 5; // global scope <?php
function myTest() { $x = 5;
// using x inside this function will generate an $y = 10;
error echo "<p>Variable x inside function is: function myTest() {
$x</p>"; $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
} }
myTest(); myTest();
echo "<p>Variable x outside function is: $x</p>"; echo $y; // outputs 15
?> ?>
PHP The static Keyword Variable Naming
Normally, when a function is completed / executed, all of its variables are deleted. Rules for naming a variable is-
However, sometimes we want a local variable NOT to be deleted. We need it fo r a further Variable names must begin with a letter or underscore character.
job. A variable name can consist of numbers, letters, underscores but you cannot use characters like
To do this, use the static keyword when you first declare the variable: + , - , % , ( , ) . & , etc
Example There is no size limit for variables.
<?php PHP - Data Types:
function myTest() PHP has a total of eight data types which we use to construct our variables:
{ static $x = 0;
echo $x; Integers: are whole numbers, without a decimal point, like 4195.
$x++; Doubles: are floating-point numbers, like 3.14159 or 49.1. Scalar
} types Booleans: have only two possible values either true or false.
myTest(); Strings: are sequences of characters, like 'PHP supports string operations.'
myTest(); Output: 0 1 2 Arrays: are named and indexed collections of other values.
myTest(); ?> Objects: are instances ofprogrammer-defined classes. Compound
types NULL: is a special type that only has one value:NULL.
Then, each time the function is called, that variable will still have the information it Resources: are special variables that hold references to resources external Special types
contained from the last time the function was called. to PHP (such as database connections).
Note: The variable is still local to the function.
The first four are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the
simple types cannot.
PHP Integers
Integers are primitive data types. They are whole numbers, without a decimal point, like
4195. They are the simplest type. They correspond to simple whole numbers, both positive
and negative {..., -2, -1, 0, 1, 2, ...}.
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Decimal format is the default, octal integers are specified with a leading 0, and
hexadecimals have a leading 0x.
Ex: $v = 12345;
$var1 = -12345 + 12345;
notation.php
<?php
$var1 = 31; $var2 = 031; $var3 =

0x31; echo "$var1\n$var2\n$var3";


?>
The default notation is the decimal. The script shows these three numbers in decimal. In
Java and C, if an integer value is bigger than the maximum value allowed, integer overflow
happens. PHP works differently. In PHP, the integer becomes a float number. Floating point
numbers have greater boundaries. In 32bit system, an integer value size is four bytes. The
maximum integer value is 2147483647.
boundary.php
<?php
$var = PHP_INT_MAX;
echo var_dump($var);
$var++;
echo var_dump($var);
?>
We assign a maximum integer value to the $var variable. We increase the variable by one.
And we compare the contents.

As we have mentioned previously, internally, the number becomes a floating point value.
var_dump(): The PHP var_dump() function returns the data type and value.
PHP Doubles or Floating point numbers
Floating point numbers represent real numbers in computing. Real numbers measure
continuous quantities like weight, height or speed. Floating point numbers in PHP can be
larger than integers and they can have a decimal point. The size of a float is platform
dependent.
We can use various syntaxes to create floating point values.
The $d variable is assigned a
<?php large number, so it is
$a = 1.245; automatically converted to
$b = 1.2e3; float type.
$c = 2E-10;
$d = 1264275425335735;
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?> This is the output of beside scrip

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true; $y = false;
Booleans are often used in conditional testing.
<?php
$male = False;
$r = rand(0, 1);
$male = $r ? True: False; if
($male) {
echo "We will use name John\n";
} else {
echo "We will use name Victoria\n";
} ?> ?> output: 6
Tip: The first character position in a string is 0 (not 1).
The script uses a random integer generator to simulate our case. $r = rand(0, 1);
Replace Text within a String
The rand( ) function returns a random number from the given integer boundaries 0 or 1.
The PHP str_replace() function replaces some characters with some other characters in a
$male = $r? True: False;
string. The example below replaces the text "world" with "Dolly":
We use the ternary operator to set a $male variable. The variable is based on the random $r
value. If $r equals to 1, the $male variable is set to True. If $r equals to 0, the $male variable
is set to False.

PHP Strings
String is a data type representing textual data in computer programs. Probably the single
most important data type in programming.
<?php
$a = "PHP ";
$b = 'PERL';
echo $a . $b; ?>
Output: PHP PERL
We can use single quotes and double quotes to create string literals.
The script outputs two strings to the console. The \n is a special sequence, a new line.
The escape-sequence replacements are −
\n is replaced by the newline character
\r is replaced by the carriage-return
character \t is replaced by the tab
character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
The Concatenation Operator
There is only one string operator in PHP.
The concatenation operator ( . ) is used to put two string values together. To concatenate
two string variables together, use the concatenation operator:
<?php
$txt1="Hello Kalpana!";
$txt2="What a nice day!"; echo
$txt1 . " " . $txt2;
?> O/P: Hello Kalpana! What a nice day!
Search for a Specific Text within a String
The PHP strpos() function searches for a specific text within a string. If a match is found,
the function returns the character position of the first match. If no match is found, it
will return FALSE. The example below searches for the text "world" in the string "Hello
world!":
Example
<?php
echo strpos("Hello world!", "world");
$my_var = null;
Example A variable that has been assigned NULL has the following properties −
<?php It evaluates to FALSE in a Boolean context.
echo str_replace("world", "Kalpana", "Hello world!"); It returns FALSE when tested with IsSet() function.
?> Output: Hello Kalpana!
The strlen() function: Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
The strlen() function is used to return the length of a string. Let's find the length of a string: Variables can also be emptied by setting the value to NULL:
Eg: <?php
echo strlen("Hello world!"); ?> The output of the code above will be: 12 Example1
<?php
PHP Array $x = "Hello world!";
Array is a complex data type which handles a collection of elements. Each of the elements $x = null; var_dump($x);
can be accessed by an index. An array stores multiple values in one single variable. In the ?>
following example $cars is an array. The PHP var_dump() function returns the data type
and value: PHP Resource
Example The special resource type is not an actual data type. It is the storing of a reference to
<?php functions and resources external to PHP. A common example of using the resource data
$cars = array("Volvo","BMW","Toyota"); type is a database call. Resources are handlers to opened files, database connections or
print_r($cars); image canvas areas. We will not talk about the resource type here, since it is an advanced
var_dump($cars); topic.
?> constant() function
The array keyword is used to create a collection of elements. In our case we have names.
As indicated by the name, this function will return the value of the constant. This is useful
The print_r function prints human readable information about a variable to the console.
when you want to retrieve value of a constant, but you do not know its name, i.e. It is
stored in a variable or returned by a function.constant() example

PHP Object <?php


An object is a data type which stores data and information on how to process that data. In define("MINSIZE", 50);
PHP, an object must be explicitly declared. First we must declare a class of object. For this, echo MINSIZE;
we use the class keyword. A class is a structure that can contain properties and methods: echo constant("MINSIZE"); // same thing as the previous line
?>
Example
<?php class Output: 50 50
Car { Only scalar data (boolean, integer, float and string) can be contained in constants.
function Car() {
PHP - Operators:
$this->model = "VW";
What is Operator?
} }
$herbie = new Car(); // create an object Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called
echo $herbie->model; // show object properties operands and + is called operator. PHP language supports following type of operators.
?>
Output: VW
PHP NULL
NULL is a special data type that only has one value: NULL. To give a variable the NULL
value, simply assign it like this −
Ex: $my_var = NULL; Arithmetic Operators:
The special constant NULL is capitalized by convention, but actually it is case insensitive;
you could just as well have typed − There are following arithmetic operators supported by PHP language:
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example and (or) Called Logical AND operator. If both the operands ($A and $B) is true.
+ Adds two operands $A + $B will give 30 && are true then then condition becomes true. ($A && $B) is true.
- Subtracts second operand from the first $A - $B will give -10 or (or) || Called Logical OR Operator. If any of the two ($A or $B) is
* Multiply both operands $A *$B will give 200 operands are non zero then then condition true. ($A || $B) is
/ Divide numerator by denumerator $B / $A will give 2 becomes true. true.
% Modulus Operator and remainder of an integer $B % $A will give 0 ! Called Logical NOT Operator. Use to reverses the !( $A && $B) is false.
after division logical state of its operand. If a condition is true
** Exponentiation ($x to the $y'th power) $A ** $B then Logical NOT operator will make false.
Increment/Decrement operators Assignment Operators:
Operator Description Example There are following assignment operators supported by PHP language:
++ Increment operator, increases integer value by one $A++ - 11 / ++$A Operator Description Example
-- Decrement operator, decreases integer value by $A-- will give 9 / --$A = Simple assignment operator, Assigns values from $C = $A + $B
one right side operands to left side operand
Comparison Operators: += Add AND assignment operator, It adds right $C += $A is equivalent
operand to the left operand and assign the to $C = $C + $A
There are following comparison operators supported by PHP language Assume variable A result to left operand
holds 10 and variable B holds 20 then: -= Subtract AND assignment operator, It subtracts $C -= $A is equivalent
Operator Description Example right operand from the left operand and assign to $C = $C - $A
== Checks if the value of two operands are equal or ($A==$B) is not true. the result to left operand
not *= Multiply AND assignment operator, It multiplies $C *= $A is equivalent
=== Identical(Returns true if $A is equal to $B, and $A === $B right operand with the left operand and assign to $C = $C * $A
they are of the same type) the result to left operand
!= Checks if the values of two operands are equal or ($A != $B) is true. /= Divide AND assignment operator, It divides left $C /= $A is equivalent
not, if values are not equal then condition becomes operand with the right operand and assign the to $C = $C / $A
true. result to left operand
<> Returns true if $x is not equal to $y $A <> $B %= Modulus AND assignment operator, It takes $C %= $A is
!== Not identical (Returns true if $A is not equal to $B, $A !== $B modulus using two operands and assign the equivalent
or they are not of the same type) result to left operand to
> Checks if the value of left operand is greater than ($A > $B) is not true. $C = $C % $A
the Conditional Operator
value of right operand, if yes then condition There is one more operator called conditional operator. This first evaluates an expression
becomes true. for a true or false value and then execute one of the two given statements depending upon
< Checks if the value of left operand is less (A < B) the result of the evaluation.
is true. Than the value of right operand, if yes
then condition becomes true. The conditional operator has this syntax:
>= Checks if the value of left operand is greater than or ($A >= $B) is not true. Operator Description Example
equal to the value of right operand, if yes then ?: Conditional Expression If Condition is true Then X: valu Y
returns true. ? value Otherwise e
<= Checks if the value of left operand is less than or equal($A <= $B) is PHP String Operators
true. to the value of right operand, if yes then condition
PHP has two operators that are specially designed for strings.
becomes true.
Logical Operators: Operator Description Example
. Concatenation $txt1 . $txt2 (Concatenation of $txt1 and
There are following logical operators supported by PHP language $txt2)
Assume variable A holds 10 and variable B holds 20 then: .= Concatenation assignment $txt1 .= $txt2 (Appends $txt2 to $txt1)
Operator Description Example
PHP Array Operators
The PHP array operators are used to compare arrays.
Category Operator Associativity
Operator Description Example Unary ! ++ -- Right to left
+ Union $x + $y (Union of $x and $y) Multiplicative */% Left to right
== Equality $x == $y (Returns true if $x and $y have the same key/value Additive +- Left to right
pairs) Relational < <= > >= Left to right
=== Identity $x === $y (Returns true if $x and $y have the same key/value Equality == != Left to right
pairs in the same order and of the same types) Logical AND && Left to right
!= or <> Inequality $x != $y or $x <> $y Returns true if $x is not equal to $y Logical OR || Left to right
!== Non-identity $x !== $y (Returns true if $x is not identical to $y) Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left
Precedence of PHP Operators
Operator precedence determines the grouping of terms in an expression. This affects how
Ex:<!DOCTYPE html> <!DOCTYPE html> <!DOCTYPE html>
an expression is evaluated. Certain operators have higher precedence than others; for
<html> <html> <html>
example, the multiplication operator has higher precedence than the addition operator − <body> <body> <body>
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher <?php <?php <?php
precedence than + so it first get multiplied with 3*2 and then adds into 7. Ans:13 $x = 10; $x = 100; $x = 100;
$y = 6; $y = 50; $y = 50;
Here operators with the highest precedence appear at the top of the table; those with the echo $x + $y; var_dump($x > $y); // if ($x == 100 xor $y == 80) {
lowest appear at the bottom. Within an expression, higher precedence operators will be ?> returns true because $x is echo "Hello world!";
evaluated first. </body> greater than $ y }
</html> ?> ?>
O/P: 16 O/P: bool(true) O/P: Hello world!

PHP -Decision Making


The if, elseif ...else and switch statements are used to take decision based on the different
condition. You can use conditional statements in your code to make your decisions. PHP
supports following three decision making statements –
Syntax EX: <html> The If...Else Statement
if (condition) <body> If you want to execute some code if a condition is true and another code if a
code to be executed if condition is true; <?php condition is false, use the if else statement.
else $d=date("D"); The elseif Statement
code to be executed if condition is false; if ($d=="Fri")
If you want to execute some code if one of the several conditions is true use the elseif
echo "Have a nice weekend!";
Example statement
else
The following example will output "Have a Syntax EX: <html>
echo "Have a nice day!";
nice weekend!" if the current day is Friday,
?> if (condition) <body>
Otherwise, it will output "Have a nice day!":
</body> </html> code to be executed if condition is true; <?php
elseif (condition) $d=date("D");
code to be executed if condition is true; if ($d=="Fri")
else echo "Have a nice weekend!";
code to be executed if condition is false; elseif ($d=="Sun")
Example echo "Have a nice Sunday!";
The following example will output "Have a else
nice weekend!" if the current day is Friday, echo "Have a nice day!";
and "Have a nice Sunday!" if the current ?>
day is Sunday. Otherwise, it will output </body>
"Have a nice day!" </html>

The Switch Statement


If you want to select one of many blocks of code to be executed, use the Switch
statement. The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax Example
switch (expression) The switch statement works in an
{ unusual way. First it evaluates given
case label1: expression then seeks a lable to match
code to be executed if expression = label1; the resulting value. If a matching value is
break; found then the code associated with the
case matching label will be executed or if
label2: none of the lable matches then statement
code to be executed if expression = label2; will execute any specified default code.
break
;
default:
code to be executed
if expression is different
from both label1 and
label2;
}

PHP -Loop Types


Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
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.
while − loops through a block of code if and as long as a specified condition is true.
We will discuss about continue and break keywords used to control the loops execution.
do. while − loops through a block of code once, and then repeats the loop as long as a The for loop statement
special condition is true. The for statement is used when you know how many times you want to execute a
statement or a block of statements.
Syntax

The initializer is used to set the start value for the counter of the number of loop iterations.
A variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two
variables on eachpass
` of the loop −

This will produce the following result –


At the end of the loop a=50 and b=25
The while loop statement
The while statement will execute a block of code if and as long as a test expression is true. If
the test expression is true then the code block will be executed. After the code has executed
the test expression will again be evaluated and the loop will continue until the test expression is
found to befalse.
Syntax

Example
This example decrements a variable value on each iteration of
the loop and the counter increments until it reaches 10 when
the evaluation is false and the loop ends.
<html>
<body>
<?php { </body> </html>
$i = 0; code to be executed; This will produce the following result −
} Value is 1
Example Value is 2
$num = 50; while( Value is 3
$i < 10) Try out beside example to list out the
values of an array. Value is 4
{ Value is 5
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?> </body> </html>
This will produce the following result –

The do...while loopstatement


The do...while statement will execute a block of code at least once. It then will repeat the
loop as long as a condition is true.

Syntax
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10 −
<html> }while( $i < 10 );
<body> echo ("Loop stopped at i = $i" );
<?php ?>
$i = 0; $num = 0; do{ </body>
$i++; </html>
O/P: Loop stopped at i = 10

The foreach loop statement <html>


The foreach statement is used to loop <body>
through arrays. For each pass the value of <?php
the current array element is assigned to $array = array( 1, 2, 3, 4, 5);
$value and the array pointer is moved by foreach( $array as $value )
one and in the next pass next element will {
be processed. echo "Value is $value <br />";
Syntax }
foreach (array as value) ?>
Creating a PHP Function
The break statement Calling a PHP Function
The PHP break keyword is used to terminate the execution of a loop prematurely. The
break statement is situated inside the statement block. If gives you full control and In fact you hardly need to create your own PHP function because there are already more
whenever you want to exit from the loop you can come out. After coming out of a loop than 1000 of built- in library functions created for different area and you just need to call
immediate statement to the loop will be executed. them according to your requirement.
Example Creating PHP Function
In the following example condition test becomes true It‘s very easy to create your own PHP function. Suppose you want to create a PHP function
when the counter value reaches 3 and loop terminates. which will simply write a simple message on your browser when you will call it. Following
<?php example creates a function called writeMessage() and then calls it just after creating it.
$i = 0;
echo "Have a nice time Kalpana!";
while( $i< 10) {
} /* Calling a PHP Function */
$i++; writeMessage();
if( $i == 3 )break; } ?>
echo ("Loop stopped at i = $i" ); </body>
?> O/P: Loop stopped at i=3 </html>
The continue statement
The PHP continue keyword is used to halt the current iteration of
a loop but it does not terminate the loop. Just like the break statement
the continue statement is situated inside the statement block PHP Functions with Parameters
containing the code that the loop executes, preceded by a conditional PHP gives you option to pass your parameters inside a function. You can pass as many as
test. For the pass encountering continue statement, rest of the loop parameters you‘re like. These parameters work like variables inside your function.
code is skipped and next pass starts. Following example takes two integer parameters and add them together and then print
them.
Example
In the following example loop prints the value of array but for which condition becomes <html>
true it just skip the code and next value is printed. <head> <title>Writing PHP Function with Parameters</title> </head>
<html> <body>
<body> <?php
<?php function addFunction($num1, $num2)
$nos = array( 1, 2, 3, 4, 5); {
foreach( $nos as $value ) $sum = $num1 + $num2;
{ This will produce the following result − echo "Sum of the two numbers is : $sum";
if( $value == 3 ) continue; }
echo "Value is $value <br />"; addFunction(10, 20);
} ?> </body> </html>
Output: Sum of the two numbers is : 30
?>
</body>
</html> Passing Arguments by Reference
It is possible to pass arguments to functions by reference. This means that a reference to
PHP – Functions the variable is manipulated by the function rather than a copy of the variable's value. Any
PHP functions are similar to other programming languages. A function is a piece of code changes made to an argument in these cases will change the value of the original variable.
which takes one more input in the form of parameter and does some processing and You can pass an argument by reference by adding an ampersand to the variable name in
returns a value. You already have seen many functions like fopen() and fread() etc. They either the function call or the function definition.
are built- in functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you –
</body> </html>
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10; addFive(
$orignum );
echo "O riginal Value is $orignum<br />";
addSix( $orignum );
echo "O riginal Value is $orignum<br />";
?>
</body>
</html>

PHP Functions returning value


A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling
code. You can return more than one value from a function using return array(1,2,3,4).
<html> <head> <title>Writing PHP Function which returns value</title> </head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2; return
$sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?> </body> </html>

Setting Default Values for Function Parameters


You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html> <head> <title>Writing PHP Function which returns value</title> </head>
<body>
<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
Dynamic Function Calls
It is possible to assign function names as strings to variables and then treat these
variables exactly as you would the function name itself.

<html> <html>
<head> <head>
<title>Dynamic Function Calls</title> <title>Dynamic Function Calls</title>
</head> </head>
<body> <body>
<?php <?php
function sayHello() function add($x,$y) The PHP default variable $_PHP_SELF is used for the PHP script name and when you
{ { click "submit" button then same PHP script will be called and will produce followingresult
echo "Hello<br />"; echo "addition=" . ($x+$y);
} } The method = "POST" is used to post user data to the server script.
$function_holder = "sayHello"; $function_holder = "add"; PHP Forms and User Input:
$function_holder(); $function_holder(20,30); The PHP $_GET and $_POST variables are used to retrieve information from forms, like
?> </body> </html> ?> </body> </html> user input.
Output: Hello PHP - GET & POST Methods
Output: addition=50 There are two ways the browser client can send information to the web server.
PHP Default Argument Value The GET Method
The following example shows how to use a default parameter. If we call the function The POST Method
setHeight() without arguments it takes the default value as argument: Before the browser sends the information, it encodes it using a scheme called URL
encoding or URL Parameters. In this scheme, name/value pairs are joined with equal
Example
<?php
function setHeight($minheight = 50) { echo
"The height is : $minheight \t"; signs and different pairs are separated by the ampersand.
}
The GET Method
setHeight(350);
The GET method sends the encoded user information appended to the page request. The
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?> page and the encoded information are separated by the ?character.
O/P: 350 50 135 80 The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
PHP -Web Concepts and Reading data from WEB The GET method is restricted to send upto 1024 characters only.
Identifying Browser & Platform Never use GET method if you have password or other sensitive information to be sent
to the server.
PHP creates some useful environment variables that can be seen in the phpinfo.php GET can't be used to send binary data, like images or word documents, to the server.
page that was used to setup the PHP environment. One of the environment variables set by The PHP provides $_GET associative array to access all the sent information using GET
PHP is HTTP_USER_AGENT which identifies the user's browser and operating system. method.
Using HTML Formwith name validation in PHP: test.php
$_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.

PHP -File Uploading


A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHPscript.
Information in the phpinfo.php page describes the temporary directory that is used for
file uploads as upload_tmp_dir and the maximum permitted size of files that can be
uploaded is stated as upload_max_filesize. These parameters are set into PHP
configuration file php.ini

The process of uploading a file follows these steps −


The user opens the page containing a HTML form featuring a text files, a browse
button and a submit button.
The user clicks the browse button and selects a file to upload from the local PC.
The full path to the selected file appears in the text filed then the user clicks the submit
button.
The POSTMethod The selected file is sent to the temporary directory on the server.
The POST method transfers information via HTTP headers or HTTP Parameters. The The PHP script that was specified as the form handler in the form's action attr ibute
information is encoded as described in case of GET method and put into a header called checks that the file has arrived and then copies the file into an intended directory.
QUERY_STRING. The PHP script confirms the success to the user.
The POST method does not have any restriction on data size to be As usual when writing files it is necessary for both temporary and final locations to have
sent. The POST method can be used to send ASCII as well as binary permissions set that enable file writing. If either is set to be read-only then process will
data. fail. An uploaded file could be a text file or image file or any document.
The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure. Creating an upload form
The PHP provides $_POST associative array to access all the sent information using POST The following HTML code below creates an up loader form. This form is having method
method. attribute set to post and enctype attribute is set to multipart/form-data
PHP Form Handling There is one global PHP variable called $_FILES. This variable is an associate double
Example : The example below contains an HTML form with two input fields and a submit dimension array and keeps all the information related to uploaded file. So if the value
button: assigned to the input's name attribute in uploading form was file, then PHP would create
following five variables –
$_FILES['file']['tmp_name'] the uploaded file in the temporary dir on the web server.
$_FILES['file']['name'] − the actual name of the uploaded file.
$_FILES['file']['size'] − the size in bytes of the uploaded file.
$_FILES['file']['type'] − the MIME type of the uploaded file.
$_FILES['file']['error'] − the error code associated with this file upload.
Example: Below example should allow upload images and gives back result as
uploaded file information.
When a user fills out the form above and click on the submit button, the form data is
sent to a PHP file, called "welcome.php": its looks like this:
Connecting to database (MySQL as reference), executing simple
queries,handling results
MySQL is a database system used 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
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter: My

The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and
rows.

Databases are useful for storing information categorically. A company may have a database with the following tables:

Employees
Products
Customers
Orders

PHP + MySQL Database System


PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)

Open a Connection to 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";
?>

A database consists of one or more tables.

You will need special CREATE privileges to create or to delete a MySQL database.
<?php The SQL query must be quoted in PHP
$servername = "localhost"; String values inside the SQL query must be quoted
$username = "username"; Numeric values must not be quoted
$password = "password"; The word NULL must not be quoted
// Create connection
$conn = new mysqli($servername, $username, $password); <?php
// Check connection $servername = "localhost";
if ($conn->connect_error) { $username = "username";
die("Connection failed: " . $conn->connect_error); $password = "password";
} $dbname = "myDB";

// Create database // Create connection


$sql = "CREATE DATABASE myDB"; $conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->query($sql) === TRUE) { // Check connection
echo "Database created successfully"; if ($conn->connect_error) {
} else { die("Connection failed: " . $conn->connect_error);
echo "Error creating database: " . $conn->error; }
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
$conn->close(); VALUES ('John', 'Doe', '[email protected]')";
?>
The CREATE TABLE statement is used to create a table in MySQL. if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
<?php } else {
$servername = "localhost"; echo "Error: " . $sql . "<br>" . $conn->error;
$username = "username"; }
$password = "password";
$dbname = "myDB"; $conn->close();
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection Multiple SQL statements must be executed with the mysqli_multi_query() function.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); The following examples add three new records to the "MyGuests" table:
}
<?php
// sql to create table $servername = "localhost";
$sql = "CREATE TABLE MyGuests ( $username = "username";
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, $password = "password";
firstname VARCHAR(30) NOT NULL, $dbname = "myDB";
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50), // Create connection
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP $conn = new mysqli($servername, $username, $password, $dbname);
)"; // Check connection
if ($conn->connect_error) {
if ($conn->query($sql) === TRUE) { die("Connection failed: " . $conn->connect_error);
echo "Table MyGuests created successfully"; }
} else {
echo "Error creating table: " . $conn->error; $sql = "INSERT INTO MyGuests (firstname, lastname, email)
} VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
$conn->close(); VALUES ('Mary', 'Moe', '[email protected]');";
?> $sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";
After a database and a table have been created, we can start adding data in them.
if ($conn->multi_query($sql) === TRUE) {
Here are some syntax rules to follow: echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error; called separately.
}

$conn->close();
?> Here is the detail of all the arguments −
Name − This sets the name of the cookie and is stored in an environment variable
The SELECT statement is used to select data from one or more tables: called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value − This sets the value of the named variable and is the content that you
SELECT column_name(s) FROM table_name actually want to store.
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
<?php After this time cookie will become inaccessible. If this parameter is not set then
$servername = "localhost"; cookie will automatically expire when the Web Browser is closed.
$username = "username"; Path − This specifies the directories for which the cookie is valid. A single forward
$password = "password";
$dbname = "myDB";
slash character permits the cookie to be valid for all directories.
Domain − This can be used to specify the domain name in very large domains and
// Create connection must contain at least two periods to be valid. All cookies are only valid for the host
$conn = new mysqli($servername, $username, $password, $dbname); and domain which created them.
// Check connection Security − This can be set to 1 to specify that the cookie should only be sent by
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent
} by regular HTTP.
Following example will create two cookies name and age these cookies will be expired
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql); after one hour.

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

PHP -Cookies
Cookies are text files stored on the client computer and they are kept of use tracking
purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
Setting Cookies with PHP
PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag. For each cookie this function has to be
Accessing Cookies with PHP
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or Deleting Cookie with PHP
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above Officially, to delete a cookie you should call setcookie() with the name argument only but
example. this does not always work well, however, and should not be relied on.

You can use isset() function to check if a cookie is set or not. It is safest to set the cookie with a date that has already expired –
PHP - Session
When you work with an application, you open it, do some changes, and then you close it.
This is much like a Session.
Session ID is stored as a cookie on the client box or passed along through URL's.
The values are actually stored at the server and are accessed via the session id from your
cookie. On the client side the session ID expires when connection is broken.
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.
Session variable values are stored in the 'superglobal' associative array '$_SESSION'

Start a PHP Session


A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
demo_session1.php Modify a PHP Session Variable
<?php To change a session variable, just Get PHP Session Variable Values
// Start the session overwrite it:
Next, we create another page called "demo_session2.php". From this page, we will
session_start(); access the session information we set on the first page ("demo_session1.php").
?> <?php
<html> session_start(); Notice that session variables are not passed individually to each new page, instead they are
<body> ?> retrieved from the session we open at the beginning of each page (session_start()).
<?php <html> <?php
// Set session variables <?php session_start();
$_SESSION["favcolor"] = "green"; $_SESSION["favcolor"] = "yellow"; ?>
$_SESSION["favanimal"] = "cat"; print_r($_SESSION); ?> </html> <!DOCTYPE html>
echo "Session variables are set."; <html>
?> <body>
</body> </html> <?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();
?>
<html>
<body>
<?php
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?> </body> </html>

Difference between a session and a cookie


The main difference between a session and a cookie is that session data is stored on
the server, whereas cookies store data in the visitor's browser.
Sessions are more secure than cookies as it is stored in server. Cookie can be turn off
from browser.
Sessions Cookies
1Sessions are server-side files that contain user Cookies are client-side files that Password: <input type="password" name="pw"><br>
information contain <input type="submit" value="Login">
user information </form>
2Session Max life time is 1440 Seconds(24 We have to set cookie max life time </body>
Minutes) as defined in php.ini file manually with php code with setcookie </html>
in php.ini on line 1604 you can find function. checklogin.php
; http://php.net/session.gc- setcookie("email",
maxlifetime '[email protected]', time()+3600); /* <?php
session.gc_maxlifetime = 1440 expire in 1 hour */ Expire time : I hour $uid = $_POST['uid'];
You can edit this value if you need custom after current time $pw = $_POST['pw'];
session life. if($uid == 'arun' and $pw == 'arun123')
3In php $_SESSION super global variable is In php $_COOKIE super global {
used to manage session. variable is used to manage cookie. session_start();
4Before using $_SESSION, you have to write You don't need to start Cookie as It is $_SESSION['sid']=
session_start(); In that way session will start stored in your local machine. session_id();
5You can store as much data as you like within Official MAX Cookie size is 4KB header("location:
in sessions.(default is 128MB.) securepage.php");
memory_limit= 128M }
php.ini line 479 ;http://php.net/memory- limit ?>
6Session is dependent on COOKIE. Because when you start session with session_start() securepage.php
then SESSIONID named key will be set in COOKIE with Unique Identifier Value for
your system. <?php
7session_destroy(); is used to "Destroys all There is no function named session_start();
if($_SESSION['sid'
data registered to a session", and if you unsetcookie()
]==session_id())
want to unset some key's of SESSION then use time()-3600);//expire before 1hour
{
unset() function. In that way you unset cookie(Set
cookie in previous time) echo "Welcome to you<br>";
unset($_SESSION["key1"],
echo "<a href='logout.php'>Logout</a>";
$_SESSION["key2"])
}
8Session ends when user closes his browser. Cookie ends depends on the life time
else
you set for it.
{
9 A session is a group of information on the Cookies are used to identify sessions. header("location:login.php");
server
}
that is associated with the cookie information.
?>
Write a Program to create simple Login and Logout example using sessions. logout.php
login.php
<html> <?php
<head> echo"Lo
<title>Login Form</title> gged out
</head> scuccess
<body> fully";
<h2>Login Form</h2> session_
<form method="post" action="checklogin.php"> start();
User Id: <input type="text" name="uid"><br> session_
destroy( Tip: The fread() and the fclose() functions will be explained below.
);
setcookie(PHPSESSID,session_id(),time()-1); The file may be opened in one of the following modes:
?>
Modes Description

File Handling in PHP: File operations like opening, closing, r Open a file for read only. File pointer starts at the beginning of the file
reading, writing, appending, deleting etc. on text and binary
files, listing directories. w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. F

a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of

PHP Manipulating Files x Creates a new file for write only. Returns FALSE and an error if file already exists

PHP has several functions for creating, reading, uploading, and editing files. r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist.

a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end o
PHP readfile() Function x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
The readfile() function reads a file and writes it to the output buffer.

Assume we have a text file called "webdictionary.txt", stored on the server, that looks like PHP Read File - fread()
this:
The fread() function reads from an open file.
AJAX = Asynchronous JavaScript and XML
The first parameter of fread() contains the name of the file to read from and the second
CSS = Cascading Style Sheets
parameter specifies the maximum number of bytes to read.
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
The following PHP code reads the "webdictionary.txt" file to the end:
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language fread($myfile,filesize("webdictionary.txt"));

PHP Open File - fopen() PHP Close File - fclose()


A better method to open files is with the fopen() function. This function gives you more
options than the readfile() function. The fclose() function is used to close an open file.

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); The fclose() requires the name of the file (or a variable that holds the filename) we want to
echo fread($myfile,filesize("webdictionary.txt")); close:
fclose($myfile);
?>
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed.... PHP Create File - fopen()
fclose($myfile);
?> 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

PHP Read Single Line - fgets() for writing (w) or appending (a).

The fgets() function is used to read a single line from a file. $myfile = fopen("testfile.txt", "w")

The example below outputs the first line of the "webdictionary.txt" file:
PHP Write to File - fwrite()
The fwrite() function is used to write to a file.
Example
The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); The example below writes a couple of names into a new file called "newfile.txt":
echo fgets($myfile);
fclose($myfile);
?> <?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
PHP Read Single Character - fgetc() $txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
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: PHP Append Text
You can append data to a file by using the "a" mode. The "a" mode appends text to the end of
Example the file, while the "w" mode overrides (and erases) the old content of the file.

In the example below we open our existing file "newfile.txt", and append some text to it
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file <?php
while(!feof($myfile)) { $myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
echo fgetc($myfile); $txt = "Donald Duck\n";
} fwrite($myfile, $txt);
fclose($myfile); $txt = "Goofy Goof\n";
?> fwrite($myfile, $txt);
fclose($myfile);
?>
PHP Delete File - unlink() opendir() Opens a directory handle

In PHP, the unlink() function is used to delete a file from the file system. It accepts a readdir() Returns an entry from a directory handle
single argument, which is the path to the file that needs to be deleted.
rewinddir() Resets a directory handle
Here is the syntax of the unlink() function:
scandir() Returns an array of files and directories of a specified directory
bool unlink ( string $filename [, resource $context ] )

Here is an example of using the unlink() function to delete a file:

<?php$file_path = '/path/to/file.txt';if (file_exists($file_path)) { if (unlink($file_path)) {


echo "File deleted successfully."; } else { echo "Unable to delete the file."; }} else { echo
"File does not exist.";}?>
Explanation

In this example, we first check if the file exists using the file_exists() function. If the
file exists, we attempt to delete it using the unlink() function. If the unlink() function
returns true, we display a success message. If it returns false, we display an error
message.

It is important to note that the unlink() function permanently deletes the file, so be
careful when using it. Once a file is deleted using unlink(), it cannot be recovered.

Conclusion
File handling in PHP involves opening, reading, writing, and manipulating files stored on
a file system.
The fopen() function is used to open a file for reading, writing, or appending.
The fwrite() function is used to write to a file, while the fread() function is used to read
from a file.
The fgets() function can be used to read a single line from a file.
The fclose() function should be used to close a file after reading or writing to it.

PHP Directory Functions


Function Description

chdir() Changes the current directory

chroot() Changes the root directory

closedir() Closes a directory handle

dir() Returns an instance of the Directory class

getcwd() Returns the current working directory

You might also like