Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
3. TYPES
3.1 INTRODUCTION
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
?>
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)
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)
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)
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
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
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.
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.
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:
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.
For example:
<?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:
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
$$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
?>
<?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).
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.
Name Example
?>
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
?>
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.
Name Example
<?php
Or (inclusive or) $a=5; $b=11;
echo $a | $b; // 15
?>
Bits that are set in $a are not set, and vice versa.
<?php
Not $a=12; $b=10;
echo $a & ~ $b; // 4
?>
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.
Name Example
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)
?>
var_dump($a<=$b); // bool(false)
?>
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.
<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>
Example:
<?php
$a = 10;
Name Example
?>
?>
Example 1: Concatenation
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2; // Hello world!
?>
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2; // Hello world!
echo $txt1;
?>
Name Example
<?php
$x = array("a" => "red", "b" => "green");
Identity
$y = array("c" => "blue", "d" => "yellow");
var_dump($x === $y);
?>
Output: bool(false)
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)
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
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
?>
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
echo "a is bigger than 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).
Output:
0
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 */
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:
<?php
$arr = array(
1,
2,
3,
4
);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
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);
$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
if ($i == 2)
continue
print "$i\n";
?>
Output:
0
1
3
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) {
switch ($i) {
case 0:
break;
case 1:
break;
case 2:
break;
?>
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.
Example:
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0] + $input[1];
}
?>
Example:
<?php
function square($num)
{
return $num * $num;
}
echo square(4); // outputs '16'.
?>
<?php
function foo()
{
echo "In foo()<br />\n";
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
?>
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.
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.
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
Example:
<?php
class A
{
function __construct()
{
$a = func_get_args();
$i = func_num_args();
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;
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
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.
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;
}
?>
Example:
<?php
class MyClass
{
const CONST_VALUE = 'A constant value';
}
$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0
echo MyClass::CONST_VALUE;
?>
Output:
A constant value'
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
?>
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";
}
}
Output:
ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($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();
$this->vars[$name] = $var;
}
}
?>
Anonymous classes are useful when simple, one-off objects need to be created.
Example:
<?php
class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}
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
"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;
?>
Output:
Calling object method 'runTest' in object context
Calling static method 'runTest' in static context
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";
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";
} 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;
}
}
?>
</body>
</html>
10. FEATURES
Example:
<?php
echo readfile("webdictionary.txt");
?>
Example:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile, filesize("webdictionary.txt"));
fclose($myfile);
?>
Example:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
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);
?>
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);
?>
fopen Opens file ofputcsv— Format line as CSV and write to file pointer
is_uploaded_file Tells whether the file was uploaded via HTTP POST
</body>
</html>
<?php
$uploaddir = 'uploads/'; // upload directory
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$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
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
==============================
<?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
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,
// as of PHP 5.4
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
Array Functions
array_search Searches the array for a given value and returns the first
corresponding key if successful
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);
?>;
?>
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
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
)
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
$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
<?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
Description
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string
$additional_parameters ]] )
<?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()
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().
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
throw $e->getMessage();
}
}
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