Sei sulla pagina 1di 64

CORPORATE TRAINING BOOK – PHP

1. OBJECTIVE
The objective of the PHP manual is to learn the core logics of php and any one can able to create a
website using php technology in a efficient and simple way. This book includes more real time
examples for better understanding of the features

2. INTRODUCTION
PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.

2.1 WHAT IS PHP


 PHP (recursive acronym for PHP: Hypertext Pre-processor) is a widely-used open source
general-purpose scripting language that is especially suited for web development and can
be embedded into HTML.
 PHP scripts are executed on the server
 PHP is free to download and use
 It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
 PHP Syntax is C-Like.

Example: An introductory example


<?php
echo "Hi, I'm a PHP script!"; // Output: Hi, I'm a PHP script!
?>

2.2 WHAT CAN PHP DO

 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 your database
 PHP can be used to control user-access
 PHP can encrypt data

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 1


CORPORATE TRAINING BOOK – PHP

3. TYPES

3.1 INTRODUCTION

PHP supports eight primitive types.


 Four scalar types:
boolean
integer
float (floating-point number, aka double)
string

 Three compound types:


array
object
callable

 And finally two special types:


resource
NULL

3.2 BOOLEAN

This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.

Syntax

To specify a boolean literal, use the constants TRUE or FALSE. Both are case-insensitive.

<?php

$foo = True; // assign the value TRUE to $foo

?>

3.3 INTEGERS
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
 An integer must have at least one digit
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based -
prefixed with 0x) or octal (8-based - prefixed with 0)

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 2


CORPORATE TRAINING BOOK – PHP

Integer literals
<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
?>

Example:
<?php
$x = 5985;
var_dump($x);
?>
Output:
int(5985)

3.4 FLOATING NUMBERS


Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified
using any of the following syntaxes:
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>

A float (floating point number) is a number with a decimal point or a number in exponential form.

<?php
$x = 10.365;
var_dump($x);
?>
Output:
float(10.365)

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 3


CORPORATE TRAINING BOOK – PHP

3.5 STRINGS
A string is series of characters, where a character is the same as a byte. This means that PHP only
supports a 256-character set, and hence does not offer native Unicode support.
Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables
with their values as well as specially interpreting certain character sequences.

Example:
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";
print($literally);
?>This will produce the following result
My $variable will not print!\n
My name will print

PHP String Functions

1) Get The Length of a String


The PHP strlen() function returns the length of a string.
The example below returns the length of the string "Hello world!":
<?php
echo strlen("Hello world!");
?>
Outputs
12

2) Count The Number of Words in a String


The PHP str_word_count() function counts the number of words in a string:
Example

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 4


CORPORATE TRAINING BOOK – PHP

<?php
echo str_word_count("Hello world!");
?
Outputs
2

3) Reverse a String
The PHP strrev() function reverses a string:
Example
<?php
echo strrev("Hello world!");
?>
Outputs
!dlrow olleH

4) 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");
?>
Outputs
6

3.6 ARRAYS
 An array is a data structure that stores one or more similar type of values in a single value.
 An array stores multiple values in one single variable
 An array in PHP is actually an ordered map. A map is a type that associates values to keys.
This type is optimized for several different uses; it can be treated as an array, list (vector),
hash table (an implementation of a map), dictionary, collection, stack, queue, and probably
more.
 As array values can be other arrays, trees and multidimensional arrays are also possible.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 5


CORPORATE TRAINING BOOK – PHP

Syntax
Specifying with array();
An array can be created using the array() language construct. It takes any number of comma-
separated key => value pairs as arguments.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
The comma after the last array element is optional and can be omitted. This is usually done for
single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other
hand the trailing comma is commonly used, as it allows easier addition of new elements at the end.

Example: A simple array


<?php
$array = array(
"foo" => "bar",
"bar" => "foo"
);
The key can either be an integer or a string. The value can be of any type.
There are three different kind of arrays and each array value is accessed using an ID c which is
called array index.

Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
Associative array − An array with strings as index. This stores element values in association with
key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are accessed using
multiple indices

4. VARIABLES

4.1 BASICS
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP:

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 6


CORPORATE TRAINING BOOK – PHP

 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in advance whether
it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.

4.2 PREDEFINED VARIABLES


PHP provides a large number of predefined variables to any script which it runs. PHP provides an
additional set of predefined arrays containing variables from the web server the environment, and
user input.
Predefined Variables & Superglobals:
 Superglobals — Superglobals are built-in variables that are always available in all scopes
 $GLOBALS — References all variables available in global scope
 $_SERVER — Server and execution environment information
 $_GET — HTTP GET variables
 $_POST — HTTP POST variables
 $_FILES — HTTP File Upload variables
 $_REQUEST — HTTP Request variables
 $_SESSION — Session variables
 $_ENV — Environment variables
 $_COOKIE — HTTP Cookies
 $php_errormsg — The previous error message
 $HTTP_RAW_POST_DATA — Raw POST data
 $http_response_header — HTTP response headers
 $argc — The number of arguments passed to script
 $argv — Array of arguments passed to script

4.3 VARIABLE SCOPE


The scope of a variable is the context within which it is defined. For the most part all PHP variables
only have a single scope. This single scope spans included and required files as well.

For example:

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 7


CORPORATE TRAINING BOOK – PHP

<?php

$a = 1;

include 'b.inc';

?>

Here the $a variable will be available within the included b.inc script. However, within user-defined
functions a local function scope is introduced. Any variable used inside a function is by default
limited to the local function scope.

For example:

<?php
$a = 1;
/* global scope */
function test()
{
echo $a;
/* reference to local scope variable */
}
test();
?>

Output:

4.4 VARIABLE VARIABLES


Sometimes it is convenient to be able to have variable variable names. That is, a variable name
which can be set and used dynamically. A normal variable is set with a statement such as:
<?php
$a = 'hello';
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In
the above example, hello, can be used as the name of a variable by using two dollar signs.
i.e.

<?php

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 8


CORPORATE TRAINING BOOK – PHP

$$a = 'world';

?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents
"hello" and $hello with contents "world". Therefore, this statement:

<?php

echo "$a ${$a}";

?>

produces the exact same output as:

<?php

echo "$a $hello";

?>

i.e. they both produce: hello world.

4.5 VARIABLES FROM EXTERNAL SOURCES


HTML Forms (GET and POST)
When a form is submitted to a PHP script, the information from that form is automatically made
available to the script. There are few ways to access this information, for example:
Example 1 - A simple HTML form
<form action="foo.php" method="post">
Name: <input type="text" name="username" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>
There are only two ways to access data from your HTML forms. Currently available methods are
listed below:

Example 2 - Accessing data from a simple POST HTML form


<?php
echo $_POST['username'];
echo $_REQUEST['username'];

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 9


CORPORATE TRAINING BOOK – PHP

5. OPERATORS

An operator is something that takes one or more values (or expressions, in programming jargon)
and yields another value (so that the construction itself becomes an expression).
Operators can be grouped according to the number of values they take. Unary operators take only
one value, for example ! (the logical not operator) or ++ (the increment operator). Binary operators
take two values, such as the familiar arithmetical operators + (plus) and - (minus), and the majority
of PHP operators fall into this category. Finally, there is a single ternary operator, ? :, which takes
three values; this is usually referred to simply as "the ternary operator" (although it could perhaps
more properly be called the conditional operator).

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 10


CORPORATE TRAINING BOOK – PHP

5.1 OPERATOR PRECEDENCE

The precedence of an operator specifies how "tightly" it binds two expressions together. For
example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*")
operator has a higher precedence than the addition ("+") operator. Parentheses may be used to
force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.
When operators have equal precedence their associatively decides how the operators are grouped.
For example "-" is left-associative, so 1 - 2 - 3 is grouped as (1 - 2) - 3 and evaluates to -4. "=" on
the other hand is right-associative, so $a = $b = $c is grouped as $a = ($b = $c).
Operators of equal precedence that are non-associative cannot be used next to each other, for
example 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other hand is legal, because
the == operator has lesser precedence than the <= operator.

5.2 ARITHMATIC OPERATORS


The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.

Name Example

Sum of $a and $b.


<?php
Addition $a = 10; $b = 6;
echo $a + $b; // 16
?>

Difference of $a and $b.


<?php
Subtraction $a = 10; $b = 6;
echo $a - $b; // 4
?>

Multiplication Product of $a and $b.


<?php
$a = 10; $b = 6;
echo $a * $b; // 16
?>

Division Quotient of $a and $b.


<?php
$a = 10; $b = 6;
echo $a / $b; // 1.666666

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 11


CORPORATE TRAINING BOOK – PHP

?>

Modulo Remainder of $a divided by $b.


<?php
$a = 10; $b = 6;
echo $a % $b; // 4
?>

5.3 ASSIGNMENT OPERATORS

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to".
Don't. It really means that the left operand gets set to the value of the expression on the right (that
is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is
3. This allows you to do some tricky things:

<?php

$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

?>

In addition to the basic assignment operator, there are "combined operators" for all of the binary
arithmetic, array union and string operators that allow you to use a value in an expression and then
set its value to the result of that expression.

5.4 BITIWISE OPERATORS


Bitwise operators allow evaluation and manipulation of specific bits within an integer.

Name Example

Bits that are set in both $a and $b are set.


<?php
And $a=77; $b=198;
echo $a & $b; // 16
?>

Bits that are set in either $a or $b are set.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 12


CORPORATE TRAINING BOOK – PHP

<?php
Or (inclusive or) $a=5; $b=11;
echo $a | $b; // 15
?>

Bits that are set in $a or $b but not both are set.


<?php
Xor (exclusive or) $a=12; $b=11;
echo $a ^ $b; // 7
?>

Bits that are set in $a are not set, and vice versa.
<?php
Not $a=12; $b=10;
echo $a & ~ $b; // 4
?>

Shift the bits of $a $b steps to the left


<?php
Shift left $a=8; $b=3;
echo $a << $b; // 64
?>

Shift the bits of $a $b steps to the right


Shift right
<?php
$a=8; $b=3;
echo $a >> $b; // 1
?>

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros
shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is
not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an
operand is preserved.

5.5 COMPARISON OPERATORS


Comparison operators, as their name implies, allow you to compare two values.

Name Example

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 13


CORPORATE TRAINING BOOK – PHP

TRUE if $a is equal to $b after type juggling.


<?php
Equal $a = 300; $b = "300";
var_dump($a == $b); //bool(true)
?>

TRUE if $a is not equal to $b after type juggling.


<?php<br>
Not equal $a = 150; $b = "150";
var_dump($a != $b); // bool(false)
?>

TRUE if $a is not equal to $b, or they are not of the same type.
<?php
Not identical $a = 150; $b = "150";
var_dump($a !== $b); //bool(true)
?>

TRUE if $a is strictly less than $b.


Less than <?php
$a = 100; $b = 300;
var_dump($a<$b); //bool(true) ?>

TRUE if $a is strictly greater than $b


<?php
Greater than $a = 300; $b = 100;
var_dump($a>$b); //bool(true)
?>

Less than or TRUE if $a is less than or equal to $b.


equal to
<?php
$a = 300; $b = 100;

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 14


CORPORATE TRAINING BOOK – PHP

var_dump($a<=$b); // bool(false)
?>

Greater than <?php


or equal to
$a = 50; $b = 50;
var_dump($a >= $b); // returns true because $a is greater than or equal to
$y ?> //bool(true)

If you compare a number with a string or the comparison involves numerical strings, then each
string is converted to a number and the comparison performed numerically. These rules also apply
to the switch statement. The type conversion does not take place when the comparison is === or !
== as this involves comparing the type as well as the value.

5.6 EXECUTION OPERATORS


PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP
will attempt to execute the contents of the backticks as a shell command; the output will be
returned (i.e., it won't simply be dumped to output; it can be assigned to a variable).

<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>

5.7 INCREMENTING/DECREMENTING OPERATORS


PHP supports C-style pre- and post-increment and decrement operators.

Pre-increment Increments $a by one, then returns $a.

Post-increment Returns $a, then increments $a by one.

Pre-decrement Decrements $a by one, then returns $a.

Post-decrement Returns $a, then decrements $a by one.

Example:
<?php
$a = 10;

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 15


CORPORATE TRAINING BOOK – PHP

echo 'Value of $a is :'.$a;


echo '<br />After Pre-increment value of $a ( i.e. ++$a ) is: '.++$a;
$a = 20;
echo '<br />Value of $a is :'.$a;
echo '<br />After Post-increment value of $a ( i.e. $a++ ) is: '.$a++;
$a = 30;
echo '<br />Value of $a is :'.$a;
echo '<br />After Pre-decrement value of $a ( i.e. --$a ) is: '.--$a;
$a = 40;
echo '<br />Value of $a is :'.$a;
echo '<br />After Post-decrement value of $a ( i.e. $a-- ) is: '.$a--;
?>
Output:
Value of $a is :10
After Pre-increment value of $a ( i.e. ++$a ) is: 11
Value of $a is :20
After Post-increment value of $a ( i.e. $a++ ) is: 20
Value of $a is :30
After Pre-decrement value of $a ( i.e. --$a ) is: 29
Value of $a is :40
After Post-decrement value of $a ( i.e. $a-- ) is: 40

5.8 LOGICAL OPERATORS


The reason for the two different variations of "and" and "or" operators is that they operate at
different precedences.

Name Example

TRUE if both $a and $b are TRUE.


<?php $a = 100; $b = 50;
And if ($a == 100 and $b == 50) {
echo "Hello world!"; // Hello word!
}

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 16


CORPORATE TRAINING BOOK – PHP

?>

TRUE if either $a or $b is TRUE.


<?php $a = 100; $b = 50;
Or
if ($a == 100 or $b == 80) {
echo "Hello world!"; // Hello word!
}

?>

TRUE if either $a or $b is TRUE, but not both.


Xor <?php $a = 100; $b = 50;
if ($a == 100 xor $b == 80) {
echo "Hello world!"; } ?> // output: Hello world!"

TRUE if $a is not TRUE.


<?php
Not $a = 100;
if ($a !== 90) {
echo "Hello world!"; // Hello world!
}
?>

5.9 STRING OPERATORS


There are two string operators. The first is the concatenation operator ('.'), which returns the
concatenation of its right and left arguments.
The second is the concatenating assignment operator ('.='), which appends the argument on the
right side to the argument on the left side.

Example 1: Concatenation
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2; // Hello world!
?>

Example 2: Concatenation Assignment

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 17


CORPORATE TRAINING BOOK – PHP

<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2; // Hello world!
echo $txt1;
?>

5.10 ARRAY OPERATORS


The + operator returns the right-hand array appended to the left-hand array; for keys that exist in
both arrays, the elements from the left-hand array will be used, and the matching elements from
the right-hand array will be ignored.

Name Example

Union of $a and $b.


<?php $x = array("a" => "red", "b" => "green");
Union $y = array("c" => "blue", "d" => "yellow");
print_r($x + $y); // union of $x and $y
?>
Output: Array ( [a] => red [b] => green [c] => blue [d] => yellow )

Equality TRUE if $a and $b have the same key/value pairs.


<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
var_dump($x == $y);
?> // Output: bool(false)

TRUE if $a and $b have the same key/value pairs in the

<?php
$x = array("a" => "red", "b" => "green");
Identity
$y = array("c" => "blue", "d" => "yellow");
var_dump($x === $y);
?>
Output: bool(false)

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 18


CORPORATE TRAINING BOOK – PHP

TRUE if $a is not equal to $b.


<?php

$x = array("a" => "red", "b" => "green");


Inequality
$y = array("c" => "blue", "d" => "yellow");

var_dump($x != $y);
?> // Output: bool(true)

TRUE if $a is not equal to $b.


<?php
Inequality $x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
var_dump($x <> $y);
?> //output: bool(true)

TRUE if $a is not identical to $b.


<?php
$x = array("a" => "red", "b" => "green");
Non-identity
$y = array("c" => "blue", "d" => "yellow");
var_dump($x !== $y);
?>
Output: bool(true)

6. CONTROL STRUCTURES

The if construct is one of the most important features of many languages, PHP included. It allows
for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

6.1 IF
The if construct is one of the most important features of many languages, PHP included. It allows
for conditional execution of code fragments. PHP features an if structure that is similar to that of C:
if (expr)
statement

If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll
ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to
boolean' section. The following example would display a is bigger than b if $a is bigger than $b:
<?php
if ($a > $b)

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 19


CORPORATE TRAINING BOOK – PHP

echo "a is bigger than b";// It will display a is bigger than b if $a is bigger than $b
?>
Often you'd want to execute a statement if a certain condition is met, and a different statement if
the condition is not met. This is what else is for. else extends an if statement to execute a
statement in case the expression in the if statement evaluates to FALSE. For example, the
following code would display a is greater than b if $a is greater than $b, and a is NOT greater than
b otherwise:

<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
if ($t < "20") {
echo "Welcome in bigspire!";
}
?>
</body>

</html>

]
Welcome in bigspire!

6.2 ELSE

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition
is not met. This is what else is for. else extends an if statement to execute a statement in case the expression
in the if statement evaluates to FALSE. For example, the following code would display a is greater than b if $a
is greater than $b, and a is NOT greater than b otherwise:
<?php

if ($a > $b) {

echo "a is greater than b"; // It will display a is greater than b if $a is greater than $b

} else {

echo "a is NOT greater than b"; // It will display a is NOT greater than b if $a is greater than $b

?>

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 20


CORPORATE TRAINING BOOK – PHP

6.3 ELSEIF/ELSE IF
elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to
execute a different statement in case the original if expression evaluates to FALSE. However,
unlike else, it will execute that alternative expression only if the elseif conditional expression
evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b
or a is smaller than b:
<?php

if ($a > $b) {

echo "a is bigger than b"; // It will display a is bigger than b if $a>$b

} elseif ($a == $b) {

echo "a is equal to b"; // It will display a is bigger than b if $a==$b

} else {

echo "a is smaller than b"; // It will display a is bigger than b if $a<$b

There may be several elseifs within the same if statement. The first elseif expression (if any) that
evaluates to TRUE would be executed.

6.4 DO WHILE
do-while loops are very similar to while loops, except the truth expression is checked at the end of
each iteration instead of in the beginning. The main difference from regular while loops is that the
first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the
end of the iteration), whereas it may not necessarily run with a regular while loop (the truth
expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the
beginning, the loop execution would end immediately).

There is just one syntax for do-while loops:


<?php
$i = 0;
do {
echo $i;
} while ($i >= 0);
?>

Output:
0

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 21


CORPORATE TRAINING BOOK – PHP

6.5 FOR
for loops are the most complex loops in PHP. They behave like their C counterparts.
The syntax of a for loop is:
for (expr1; expr2; expr3)
statement
The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the
loop.In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop
continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the
loop ends.
At the end of each iteration, expr3 is evaluated (executed).

<?php
/* example 1 */

for ($i = 1; $i <= 10; $i++) {


echo $i;
}
?>

Output:
1
2
3
4
5
6
7
8
9
10

6.6 FOREACH
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays
and objects, and will issue an error when you try to use it on a variable with a different data type or
an uninitialized variable. There are two syntaxes:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement

Example:

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 22


CORPORATE TRAINING BOOK – PHP

<?php
$arr = array(
1,
2,
3,
4
);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)

// without an unset($value), $value is still a reference to the last item: $arr[3]

foreach ($arr as $key => $value) {


// $arr[3] will be updated with each value from $arr...
echo "{$key} => {$value} ";
print_r($arr);
}
// ...until ultimately the second-to-last value is copied onto the last value
// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

6.7 BREAK
break ends execution of the current for, foreach, while, do-while or switch structure.break accepts
an optional numeric argument which tells it how many nested enclosing structures are to be broken
out of. The default value is 1, only the immediate enclosing structure is broken out of.
Example:
<?php
$array1=array(100, 1100, 200, 400, 900);

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 23


CORPORATE TRAINING BOOK – PHP

$x1=0;
$sum=0
while ($x1<=4)
{
if ($sum>1500)
{
break;
}
$sum = $sum+$array1[$x1];
$x1=$x1+1;
}
echo $sum;
?>
Output:
1800

6.8 CONTINUE
Continue is used within looping structures to skip the rest of the current loop iteration and continue
execution at the condition evaluation and then the beginning of the next iteration.
Continue accepts an optional numeric argument which tells it how many levels of enclosing loops it
should skip to the end of. The default value is 1, thus skipping to the end of the current loop.

Example:
<?php

for ($i = 0; $i < 5; ++$i) {

if ($i == 2)

continue

print "$i\n";

?>

Output:
0
1
3

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 24


CORPORATE TRAINING BOOK – PHP

6.9 SWITCH
The switch statement is similar to a series of IF statements on the same expression. In many
occasions, you may want to compare the same variable (or expression) with many different values,
and execute a different piece of code depending on which value it equals to. This is exactly what
the switch statement is for.
Example:
<?php

if ($i == 0) {

echo "i equals 0"; // Case 0 will execute

} elseif ($i == 1) { // Case 1 will execute

echo "i equals 1";

} elseif ($i == 2) { // Case 2 will execute

echo "i equals 2";

switch ($i) {

case 0:

echo "i equals 0";

break;

case 1:

echo "i equals 1";

break;

case 2:

echo "i equals 2";

break;

?>

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 25


CORPORATE TRAINING BOOK – PHP

6.10 GOTO
The goto operator can be used to jump to another section in the program. The target point is
specified by a label followed by a colon, and the instruction is given as goto followed by the desired
target label. This is not a full unrestricted goto. The target label must be within the same file and
context, meaning that you cannot jump out of a function or method, nor can you jump into one. You
also cannot jump into any sort of loop or switch structure. You may jump out of these, and a
common use is to use a goto in place of a multi-level break.
Example:
<?php

goto a;

echo 'Foo';

a:

echo 'Bar';

?>

Output:

Bar

7. FUNCTIONS

PHP functions are similar to other programming languages. A function is a piece of code which
takes one more input in the form of parameter and does some processing and returns a value.

7.1 USER-DEFINED FUNCTIONS


A function may be defined using syntax such as the following:
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?>

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 26


CORPORATE TRAINING BOOK – PHP

7.2 FUNCTION ARGUMENTS


Information may be passed to functions via the argument list, which is a comma-delimited list of
expressions. The arguments are evaluated from left to right.
PHP supports passing arguments by value (the default), passing by reference, and default
argument values. Variable-length argument lists are also supported.

Example:
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0] + $input[1];
}
?>

7.3 RETURNING VALUES


Values are returned by using the optional return statement. Any type may be returned, including
arrays and objects. This causes the function to end its execution immediately and pass control
back to the line from which it was called.

Example:
<?php
function square($num)
{
return $num * $num;
}
echo square(4); // outputs '16'.
?>

7.4 VARIABLE FUNCTIONS


PHP supports the concept of variable functions. This means that if a variable name has
parentheses appended to it, PHP will look for a function with the same name as whatever the
variable evaluates to, and will attempt to execute it. Among other things, this can be used to
implement callbacks, function tables, and so forth.
Variable functions won't work with language constructs such as echo, print, unset(), isset(),
empty(), include, require and the like. Utilize wrapper functions to make use of any of these
constructs as variable functions.

<?php
function foo()

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 27


CORPORATE TRAINING BOOK – PHP

{
echo "In foo()<br />\n";
}

function bar($arg = '')


{
echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo


function echoit($string)
{
echo $string;
}

$func = 'foo';
$func(); // This calls foo()

$func = 'bar';
$func('test'); // This calls bar()

$func = 'echoit';
$func('test'); // This calls echoit()
?>

7.5 INTERNAL (BUILT-IN) FUNCTIONS


PHP comes standard with many functions and constructs. There are also functions that require
specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For
example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD
support. Or, to use mysql_connect(), PHP must be compiled with MySQL support. There are many
core functions that are included in every version of PHP, such as the string and variable functions.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 28


CORPORATE TRAINING BOOK – PHP

8. CLASSES AND OBJECTS

8.1 INTRODUCTION
Starting with PHP 5, the object model was rewritten to allow for better performance and more
features. This was a major change from PHP 4. PHP 5 has a full object model.

Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods,
additional magic methods, interfaces, cloning and type hinting.
PHP treats objects in the same way as references or handles, meaning that each variable contains
an object reference rather than a copy of the entire object.

8.2 THE BASICS


class

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair
of curly braces which enclose the definitions of the properties and methods belonging to the class.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 29


CORPORATE TRAINING BOOK – PHP

The class name can be any valid label, provided it is not a PHP reserved word. A valid class name
starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a
regular expression, it would be expressed thus: ^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$.
Example:

<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';

// method declaration
public function displayVar()
{
echo $this->var;
}
}

?>

Output:

a default value

8.3 CONSTRUCTORS AND DESTRUCTORS


Constructor:
PHP 5 allows developers to declare constructor methods for classes. Classes which have a
constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.
void __construct ([ mixed $args = "" [, $... ]] )

Example:
<?php
class A
{
function __construct()
{
$a = func_get_args();
$i = func_num_args();

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 30


CORPORATE TRAINING BOOK – PHP

if (method_exists($this,$f='__construct'.$i)) {
call_user_func_array(array($this,$f),$a);
}
}
function __construct1($a1)
{
echo('__construct with 1 param called: '.$a1.PHP_EOL);
}
function __construct2($a1,$a2)
{
echo('__construct with 2 params called: '.$a1.','.$a2.PHP_EOL);
}
function __construct3($a1,$a2,$a3)
{
echo('__construct with 3 params called: '.$a1.','.$a2.','.$a3.PHP_EOL);
}
}
$o = new A('sheep');
$o = new A('sheep','cat');
$o = new A('sheep','cat','dog');
?>

Output:
__construct with 1 param called: sheep
__construct with 2 params called: sheep,cat
__construct with 3 params called: sheep,cat,dog

Destructor:
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as
C++. The destructor method will be called as soon as there are no other references to a particular
object or in any order during the shutdown sequence.
void __destruct ( void )

Example:
<?php
class destruction {
var $name;

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 31


CORPORATE TRAINING BOOK – PHP

function destruction($name) {
$this->name = $name;
register_shutdown_function(array(&$this, "shutdown"));
}
function shutdown() {
echo 'shutdown: '.$this->name."\n";
}
function __destruct() {
echo 'destruct: '.$this->name."\n";
}
}
$a = new destruction('a: global 1');
function test() {
$b = new destruction('b: func 1');
$c = new destruction('c: func 2');
}
test();
$d = new destruction('d: global 2');
?>

Output:
shutdown: a: global 1
shutdown: b: func 1
shutdown: c: func 2
shutdown: d: global 2
destruct: b: func 1
destruct: c: func 2
destruct: d: global 2
destruct: a: global 1

8.4 VISIBILITY
The visibility of a property, a method or (as of PHP 7.1.0) a constant can be defined by prefixing the
declaration with the keywords public, protected or private. Class members declared public can be
accessed everywhere. Members declared protected can be accessed only within the class itself
and by inherited classes. Members declared as private may only be accessed by the class that
defines the member.

Property Visibility

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 32


CORPORATE TRAINING BOOK – PHP

Class properties must be defined as public, private, or protected. If declared using var, the property
will be defined as public.

Method Visibility
Class methods may be defined as public, private, or protected. Methods declared without any
explicit visibility keyword are defined as public.

Constant Visibility
Class constants may be defined as public, private, or protected. Constants declared without any
explicit visibility keyword are defined as public.

Visibility from other objects


Objects of the same type will have access to each others private and protected members even
though they are not the same instances. This is because the implementation specific details are
already known when inside those objects.

8.5 OBJECT INHERITANCE


Inheritance is a well-established programming principle, and PHP makes use of this principle in its
object model. This principle will affect the way many classes and objects relate to one another.

Example:
When you extend a class, the subclass inherits all of the public and protected methods from the
parent class. Unless a class overrides those methods, they will retain their original functionality.
This is useful for defining and abstracting functionality, and permits the implementation of additional
functionality in similar objects without the need to re-implement all of the shared functionality.

Example:
<?php

class Foo
{
public function printItem($string)
{
echo 'Foo: ' . $string . PHP_EOL;
}

public function printPHP()


{
echo 'PHP is great.' . PHP_EOL;
}

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 33


CORPORATE TRAINING BOOK – PHP

class Bar extends Foo


{
public function printItem($string)
{
echo 'Bar: ' . $string . PHP_EOL;
}
}

$foo = new Foo();


$bar = new Bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP(); // Output: 'PHP is great'
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP(); // Output: 'PHP is great'

?>

8.6 SCOPE RESOLUTION OPERATOR (::)


The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the
double colon, is a token that allows access to static, constant, and overridden properties or
methods of a class.
When referencing these items from outside the class definition, use the name of the class.
It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g.
self, parent and static).
Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon.
However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team
decided to call it. It actually does mean double-colon - in Hebrew!

Example:
<?php
class MyClass
{
const CONST_VALUE = 'A constant value';
}

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 34


CORPORATE TRAINING BOOK – PHP

$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0

echo MyClass::CONST_VALUE;
?>
Output:

A constant value'

8.7 STATIC KEYWORD


Declaring class properties or methods as static makes them accessible without needing an
instantiation of the class. A property declared as static cannot be accessed with an instantiated
class object (though a static method can).

Static methods:
Because static methods are callable without an instance of the object created, the pseudo-variable
$this is not available inside the method declared as static.

Example:
<?php
class Foo
{
public static function aStaticMethod()
{
// ...
}
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>

8.8 CLASS ABSTRACTION


PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be
instantiated, and any class that contains at least one abstract method must also be abstract.
Methods defined as abstract simply declare the method's signature - they cannot define the
implementation.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 35


CORPORATE TRAINING BOOK – PHP

When inheriting from an abstract class, all methods marked abstract in the parent's class
declaration must be defined by the child; additionally, these methods must be defined with the
same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the
function implementation must be defined as either protected or public, but not private. Furthermore
the signatures of the methods must match, i.e. the type hints and the number of required
arguments must be the same.
Example:
<?php
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);

// Common method
public function printOut()
{
print $this->getValue() . "\n";
}
}

class ConcreteClass1 extends AbstractClass


{
protected function getValue()
{
return "ConcreteClass1";
}

public function prefixValue($prefix)


{
return "{$prefix}ConcreteClass1";
}
}

class ConcreteClass2 extends AbstractClass


{

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 36


CORPORATE TRAINING BOOK – PHP

public function getValue()


{
return "ConcreteClass2";
}

public function prefixValue($prefix)


{
return "{$prefix}ConcreteClass2";
}
}

$class1 = new ConcreteClass1;


$class1->printOut();
echo $class1->prefixValue('FOO_') . "\n";

$class2 = new ConcreteClass2;


$class2->printOut();
echo $class2->prefixValue('FOO_') . "\n";
?>

Output:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

8.9 OBJECT INTERFACES


Object interfaces allow you to create code which specifies which methods a class must implement,
without having to define how these methods are handled.
Interfaces are defined in the same way as a class, but with the interface keyword replacing the
class keyword and without any of the methods having their contents defined.
All methods declared in an interface must be public; this is the nature of an interface.
Example:
<?php
// Declare the interface 'iTemplate'

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 37


CORPORATE TRAINING BOOK – PHP

interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}

// Implement the interface


// This will work
class Template implements iTemplate
{
private $vars = array();

public function setVariable($name, $var)


{
$this->vars[$name] = $var;
}

public function getHtml($template)


{
foreach ($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}

return $template;
}
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();

public function setVariable($name, $var)


{

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 38


CORPORATE TRAINING BOOK – PHP

$this->vars[$name] = $var;
}
}
?>

8.10 ANONYMOUS CLASSES

Anonymous classes are useful when simple, one-off objects need to be created.

Example:
<?php
class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}

var_dump(new class(10) extends SomeClass implements SomeInterface {


private $num;

public function __construct($num)


{
$this->num = $num;
}
use SomeTrait;
});
Output:
object(class@anonymous)#1 (1) {
["Command line code0x104c5b612":"class@anonymous":private]=>
int(10)
}

8.11 OVERLOADING
Overloading in PHP provides means to dynamically "create" properties and methods. These
dynamic entities are processed via magic methods one can establish in a class for various action
types.
The overloading methods are invoked when interacting with properties or methods that have not
been declared or are not visible in the current scope. The rest of this section will use the terms

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 39


CORPORATE TRAINING BOOK – PHP

"inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and
visibility.
Example:
<?php
class MethodTest
{
public function __call($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}
/** As of PHP 5.3.0 */
public static function __callStatic($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n";
}
}
$obj = new MethodTest;

$obj->runTest('in object context');

MethodTest::runTest('in static context'); // As of PHP 5.3.0

?>

Output:
Calling object method 'runTest' in object context
Calling static method 'runTest' in static context

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 40


CORPORATE TRAINING BOOK – PHP

9. SUPERGLOBALS

Superglobals — Superglobals are built-in variables that are always available in all scopes

9.1 $_GLOBALS
References all variables available in global scope

Description:
An associative array containing references to all variables which are currently defined in the global
scope of the script. The variable names are the keys of the array.

Example:
<?php
function test()
{
$foo = "local variable";

echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 41


CORPORATE TRAINING BOOK – PHP

echo '$foo in current scope: ' . $foo . "\n";


}

$foo = "Example content";


test();
?>

9.2 $_SERVER
$_SERVER is an array containing information such as headers, paths, and script locations. The
entries in this array are created by the web server. There is no guarantee that every web server will
provide any of these; servers may omit some, or provide others not listed here.

9.3 $_GET
An associative array of variables passed to the current script via the URL parameters.
$HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that
$HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such).

9.4 $_POST
An associative array of variables passed to the current script via the HTTP POST method when
using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the
request.
$HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that
$HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)

Example:
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 42


CORPORATE TRAINING BOOK – PHP

} else {
echo $name;
}
}
?>
</body>
</html>

9.5 $_COOKIE

9.6 $_SESSION

9.7 $_REQUEST
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

Example:
<html>
<body>
<form method="post" action="<?php
echo $_SERVER['PHP_SELF'];
?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 43


CORPORATE TRAINING BOOK – PHP

</body>
</html>

10. FEATURES

10.1 FILE HANDLING


File handling is an important part of any web application. You often need to open and process a file
for different tasks.

PHP readfile() Function


The readfile() function reads a file and writes it to the output buffer.

Example:
<?php
echo readfile("webdictionary.txt");
?>

PHP Open File - fopen()


A better method to open files is with the fopen() function. This function gives you more options than
the readfile() function.

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

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 44


CORPORATE TRAINING BOOK – PHP

?>

PHP Read File - fread()


The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.

Example:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>

PHP Read Single Line - fgets()


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

PHP Check End-Of-File - feof()


The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.

Example:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while (!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 45


CORPORATE TRAINING BOOK – PHP

PHP Read Single Character - fgetc()


The fgetc() function is used to read a single character from a file.

Example:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while (!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>

File system functions

chgrp Changes file group

chmod Changes file mode

chown Changes file owner

clearstatcache Clears file status cache

copy Copies file

delete See unlink or unset

dirname Returns a parent directory's path

disk_free_space Returns available space on filesystem or disk partition

disk_total_spac Returns the total size of a filesystem or disk partition


e

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 46


CORPORATE TRAINING BOOK – PHP

fclose Closes an open file pointer

fgetc Gets character from file pointer

fgets Gets line from file pointer

file Reads entire file into an array

filesize Gets file size

filetype Gets file type

fopen Opens file ofputcsv— Format line as CSV and write to file pointer

fputs Alias of fwrite

fread Binary-safe file read

fscanf Parses input from a file according to a format

fseek Seeks on a file pointer

fstat Gets information about a file using an open file pointer

ftruncate Truncates a file to a given length

fwrite Binary-safe file write

is_dir Tells whether the filename is a directory

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 47


CORPORATE TRAINING BOOK – PHP

is_executable Tells whether the filename is executable

is_readable Tells whether a file exists and is readable

is_uploaded_file Tells whether the file was uploaded via HTTP POST

mkdir Makes directory

move_uploaded Moves an uploaded file to a new location


_file

readfile Outputs a file

10.2 FILE UPLOADS

Multiple files can be uploaded using different name for input.


It is also possible to upload multiple files simultaneously and have the information organized
automatically in arrays for you. To do so, you need to use the same array submission syntax in the
HTML form as you do with multiple selects and checkboxes:
Example:
<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">


Select image to upload:
<input type="file" name="userfile" id="userfile">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

<?php
$uploaddir = 'uploads/'; // upload directory
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 48


CORPORATE TRAINING BOOK – PHP

$file = $_FILES['userfile']['name'];
$size = $_FILES['userfile']['size'];
$type = $_FILES['userfile']['type'];
// checking the file is attached or not
if(empty($file)){
$imgE = 'Not uploaded the image';
}
else{
// file extensions
$extensions = array('jpeg','jpg','png','gif');
$file_ext = explode('/',$type) ;
$file_ext = end($file_ext);
// checking the file extension is jpg,jpeg or png
if(in_array($file_ext,$extensions ) == false){
$imgE = 'extension must be jpg,jpeg,png,gif';
}
// checking the file size is less than 50kb
if($size > 50000){
$imgE = 'File size must be less tham 50 KB';
}
// uploading file if there is no error
else{
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
}
}
?>
Output:

10.3 COOKIES
PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote
browser and thus tracking or identifying return users. You can set cookies using the setcookie() or
setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 49


CORPORATE TRAINING BOOK – PHP

any output is sent to the browser. This is the same limitation that header() has. You can use the
output buffering functions to delay the script output until you have decided whether or not to set any
cookies or send any headers.
Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global
array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just
add [] to the cookie name.

Example:
Setting new cookie
=============================
<?php
setcookie("name","value",time()+$int);
/*name is your cookie's name
value is cookie's value
$int is time of cookie expires*/
?>

Getting Cookie
=============================
<?php
echo $_COOKIE["your cookie name"];
?>
Updating Cookie
=============================
<?php
setcookie("color","red");
echo $_COOKIE["color"];
/*color is red*/
/* your codes and functions*/
setcookie("color","blue");
echo $_COOKIE["color"];
/*new color is blue*/
?>
Deleting Cookie
==============================

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 50


CORPORATE TRAINING BOOK – PHP

<?php
unset($_COOKIE["yourcookie"]);
/*Or*/
setcookie("yourcookie","yourvalue",time()-1);
/*it expired so it's deleted*/
?>

10.4 SESSIONS

Session support in PHP consists of a way to preserve certain data across subsequent accesses.
A visitor accessing your web site is assigned a unique id, the so-called session id. This is either
stored in a cookie on the user side or is propagated in the URL.
The session support allows you to store data between requests in the $_SESSION superglobal
array. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set
to 1) or on your request (explicitly through session_start()) whether a specific session id has been
sent with the request. If this is the case, the prior saved environment is recreated.

Session Functions:
session_abort — Discard session array changes and finish session
session_cache_expire — Return current cache expire
session_cache_limiter — Get and/or set the current cache limiter
session_commit — Alias of session_write_close
session_create_id — Create new session id
session_decode — Decodes session data from a session encoded string
session_destroy — Destroys all data registered to a session
session_encode — Encodes the current session data as a session encoded string
session_gc — Perform session data garbage collection
session_get_cookie_params — Get the session cookie parameters
session_id — Get and/or set the current session id
session_is_registered — Find out whether a global variable is registered in a session
session_module_name — Get and/or set the current session module
session_name — Get and/or set the current session name
session_regenerate_id — Update the current session id with a newly generated one
session_register_shutdown — Session shutdown function
session_register — Register one or more global variables with the current session
session_reset — Re-initialize session array with original values
session_save_path — Get and/or set the current session save path
session_set_cookie_params — Set the session cookie parameters

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 51


CORPORATE TRAINING BOOK – PHP

session_set_save_handler — Sets user-level session storage functions


session_start — Start new or resume existing session
session_status — Returns the current session status
session_unregister — Unregister a global variable from the current session
session_unset — Free all session variables
session_write_close — Write session data and end session

Example:
<?php
session_start();
if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}else {
$_SESSION['counter']++;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
echo ( $msg );
?>
<p>
To continue click following link <br />
<a href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">
</p>

10.5 ARRAYS
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This
type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an
implementation of a map), dictionary, collection, stack, queue, and probably more. As array values
can be other arrays, trees and multidimensional arrays are also possible.

Syntax
Specifying with array()
An array can be created using the array() language construct. It takes any number of comma-
separated key => value pairs as arguments.
array(
key => value,

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 52


CORPORATE TRAINING BOOK – PHP

key2 => value2,


key3 => value3,
...
)
Example:
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);

// as of PHP 5.4
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>

Array Functions

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 53


CORPORATE TRAINING BOOK – PHP

array_keys Return all the keys or a subset of the keys of an array

array_map Applies the callback to the elements of the given arrays

array_pop Pop the element off the end of array

array_push Push one or more elements onto the end of array

array_reverse Return an array with elements in reverse order

array_search Searches the array for a given value and returns the first
corresponding key if successful

array_unique Removes duplicate values from an array

count Count all elements in an array, or something in an object

list Assign variables as if they were an array

sizeof Alias of count

sort Sort an array

Array Functions Examples


1. array_keys
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 54


CORPORATE TRAINING BOOK – PHP

$array = array("color" => array("blue", "red", "green"),


"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
Output:
Array
(
[0] => 0
[1] => color
)
Array
(
[0] => 0
[1] => 3
[2] => 4
)
Array
(
[0] => color
[1] => size
)

2. array_map
<?php
// print the string in file using file_get_constants() function
echo f<?php
function cube($n)
{
return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>;
?>

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 55


CORPORATE TRAINING BOOK – PHP

Output:
Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)

3. array_pop

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>
Output:
Array
(
[0] => orange
[1] => banana
[2] => apple
)

4. array_push

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
Output:
Array
(
[0] => orange
[1] => banana

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 56


CORPORATE TRAINING BOOK – PHP

[2] => apple


[3] => raspberry
)

5. array_reverse
<?php
$input = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);
print_r($input);
print_r($reversed);
print_r($preserved);
?>
Output:
Array
(
[0] => php
[1] => 4
[2] => Array
(
[0] => green
[1] => red
)
)
Array
(
[0] => Array
(
[0] => green
[1] => red
)
[1] => 4
[2] => php
)

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 57


CORPORATE TRAINING BOOK – PHP

Array
(
[2] => Array
(
[0] => green
[1] => red
)
[1] => 4
[0] => php
)

6. array_search
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>

7. array_unique
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Output:
Array
(
[a] => green
[0] => red
[1] => blue
)

8. count
<?php

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 58


CORPORATE TRAINING BOOK – PHP

$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count($b);
// $result == 3
$result = count(null);
// $result == 0
$result = count(false);
// $result == 1
?>

9. list
<?php
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";
// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>

10. sizeof

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 59


CORPORATE TRAINING BOOK – PHP

<?php
$cars=array("Volvo","BMW","Toyota");
echo sizeof($cars);
?>
Output:
3

11. sort
<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
?>
Output:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

11. MAIL FUNCTIONS

mail — Send mail

Description
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string
$additional_parameters ]] )

Example: Sending mail.


Using mail() to send a simple email:

<?php
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";
// In case any of our lines are larger than 70 characters, we should use wordwrap()

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 60


CORPORATE TRAINING BOOK – PHP

$message = wordwrap($message, 70, "\r\n");


// Send
mail('caffeinated@example.com', 'My Subject', $message);
?>

12. EXCEPTION HANDLING

Try
An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try
block, to facilitate the catching of potential exceptions. Each try must have at least one
corresponding catch or finally block.
Catch
Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when
no exception is thrown within the try block) will continue after that last catch block defined in
sequence. Exceptions can be thrown (or re-thrown) within a catch block.
When an exception is thrown, code following the statement will not be executed, and PHP will
attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will
be issued with an "Uncaught Exception ..." message, unless a handler has been defined with
set_exception_handler().

Example on Try Catch block:


function _modulename_getData($field, $table) {
try {

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 61


CORPORATE TRAINING BOOK – PHP

if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
throw $e->getMessage();

}
}

13. MYSQLI FUCTIONS

This function is an alias of: mysqli::__construct()


Although the mysqli::__construct() documentation also includes procedural examples that use the
mysqli_connect() function, here is a short example:

Example: mysqli_connect() example


<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 62


CORPORATE TRAINING BOOK – PHP

echo "Success: A proper connection to MySQL was made! The my_db database is great." .
PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
mysqli_close($link);
?>

Mysqli Functions

Name Discription

mysqli_escape_string Alias of mysqli_real_escape_string()

mysqli_fetch Alias for mysqli_stmt_fetch()

mysqli_execute Alias for mysqli_stmt_execute()

mysqli_affected_rows() Returns the number of affected rows in the previous


MySQL operation

mysqli_connect_error() Returns the error description from the last connection


error

mysqli_fetch_array() Fetches a result row as an associative, a numeric


array, or both

mysqli_fetch_assoc() Fetches a result row as an associative array

mysqli_fetch_lengths() Returns the lengths of the columns of the current row


in the result set

mysqli_fetch_object() Returns the current row of a result set, as an object

mysqli_fetch_row() Fetches one row from a result-set and returns it as


an enumerated array

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 63


CORPORATE TRAINING BOOK – PHP

mysqli_next_result() Prepares the next result set from


mysqli_multi_query()

mysqli_num_fields() Returns the number of fields in a result set

mysqli_prepare() Prepares an SQL statement for execution

mysqli_query() Performs a query against the database

mysqli_real_escape_string() Escapes special characters in a string for use in an


SQL statement

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 64

Potrebbero piacerti anche