php introduction - miracleindia.com · php introduction a) awhat is php: ... or task scheduler (on...

40
PHP INTRODUCTION a) AWHAT IS PHP: PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. EXAMPLE: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Example</title> </head> <body> <?php echo "Hi, this is my first php script!"; ?> </body> </html> b) WHAT PHP CAN DO: Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more. There are three main areas where PHP scripts are used. Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.

Upload: trinhdan

Post on 14-Apr-2018

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

PHP INTRODUCTION

a) AWHAT IS PHP: PHP (recursive acronym for PHP: Hypertext

Preprocessor) is a widely-used open source general-purpose

scripting language that is especially suited for web development

and can be embedded into HTML.

EXAMPLE:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>Example</title>

</head>

<body>

<?php

echo "Hi, this is my first php script!";

?>

</body>

</html>

b) WHAT PHP CAN DO:

Anything. PHP is mainly focused on server-side scripting, so you can do

anything any other CGI program can do, such as collect form data,

generate dynamic page content, or send and receive cookies. But PHP can

do much more.

There are three main areas where PHP scripts are used.

Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or

server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the

server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation

instructions section for more information.

Page 2: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This

type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for

simple text processing tasks. See the section about Command line usage of PHP for more information.

Writing desktop applications. PHP is probably not the very best language

to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such

programs.

HOW TO CREATE A BASIC PHP SCRIPT:

Create a file named hello.php and put it in your web server's root

directory (DOCUMENT_ROOT) with the following content:

Example #1 Our first PHP script: hello.php

<html>

<head> <title>PHP Test</title> </head>

<body> <?php echo '<p>Hello World</p>'; ?>

</body> </html>

DEALING WITH FORMS IN PHP:

One of the most powerful features of PHP is the way it handles HTML

forms. The basic concept that is important to understand is that any form

element will automatically be available to your PHP scripts.

Consider the following example:

Page 3: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

EXAMPLE 1:

A Simple HTML form:

<form action="action.php" method="post"> <p>Your name: <input type="text" name="name" /></p>

<p>Your age: <input type="text" name="age" /></p> <p><input type="submit" /></p> </form>

There is nothing special about this form. It is a straight HTML form with

no special tags of any kind. When the user fills in this form and hits the

submit button, the action.php page is called. In this file you would write

something like this:

EXAMPLE 2:

Printing data from our form:

Hi <?php echo($_POST['name']); ?>.

You are <?php echo($_POST['age']); ?> years old.

OUTPUT

Hi Joe. You are 22 years old.

2. VARIABLES AND EXPRESSIONS IN PHP:

DATATYPES:

PHP supports 8 primitive datatypes:

a) BOOLEAN :

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

b) INTEGERS:

Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a

sign (- or +).

Page 4: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

EXAMPLE:

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

c) STRINGS:

String is a series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set.

<?php

echo 'this is a simple string';?>

d) 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, )

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

EXAMPLE: <?php

$array = array( "name" => "richard",

"age" => "25", ); ?>

e) OBJECTS:

Page 5: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

To create a new object, use the new statement to instantiate a

class:

<?php class a

{ function mymethod() {

echo "this is my first method."; }

} $c = new a();

$c->mymethod(); ?>

f) RESOURCES: A resource is a special variable, holding a reference to an external

resource. Resources are created and used by special functions.

g) NULL:

The special NULL value represents a variable with no value. NULL is the only possible value of type null.

A variable is considered to be null if:

it has been assigned the constant NULL.

it has not been set to any value yet. it has been unset().

BASICS:

Variables in PHP are represented by a dollar sign followed by the name

of the variable. The variable name is case-sensitive.

Example: $a, $num, etc.

PREDEFINED VARIABLES:

PHP provides a large number of predefined variables to any script

which it runs.

Example: $this

Page 6: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

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.

Any variable used inside a function is by default limited to the local

function scope.Since variable has two types of scope includes local and

global. A global variable needs to be declared as global before using it

whereas if variable is not being declared as global it means local by

default.A global variable is defined by using global keyword.

Example:

<?php

$a = 1; /* global scope */

function test()

{

echo $a; /* reference to local scope variable */

}

test();

?>

Example using global:

<?php

$a = 1;

$b = 2;

function Sum()

{

global $a, $b;

$b = $a + $b;

}

Sum();

echo $b;s

?>

The above script will output 3. By declaring $a and $b global within the

function, all references to either variable will refer to the global

version. There is no limit to the number of global variables that can be

manipulated by a function.

Page 7: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

HTTP ENVIRONMENT VARIABLES:

a) $_GET:

An associative array of variables passed to the current script via the

URL parameters.

b) $_POST:

An associative array of variables passed to the current script via the

HTTP POST method.

c) $_SESSION:

An associative array containing session variables available to the

current script.

d) $_COOKIE:

An associative array of variables passed to the current script via

HTTP Cookies.

e) $_REQUEST:

An associative array that by default contains the contents

of $_GET, $_POST and $_COOKIE.

CONSTANTS:

A constant is an identifier (name) for a simple value. As the name

suggests, that value cannot change during the execution of the

script.

A constant is case-sensitive by default. By convention, constant

identifiers are always uppercase.

Page 8: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

3. PHP OPERATORS:

ARITHMETIC OPERATORS:

The division operator ("/") returns a float value unless the two

operands are integers (or strings that get converted to integers)

and the numbers are evenly divisible, in which case an integer

value will be returned.

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").

Arithmetic Operators

Example Name Result

-$a Negation Opposite of $a.

$a + $b Addition Sum of $a and $b.

$a - $b Subtraction Difference of $a and $b.

$a * $b Multiplication Product of $a and $b.

$a / $b Division Quotient of $a and $b.

$a % $b Modulus Remainder of $a divided by $b.

Page 9: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

EXAMPLE:

<?php

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

.

?>

LOGICAL OPERATORS:

Logical Operators

Example Name Result

$a and $b And TRUE if both $a and $b are TRUE.

$a or $b Or TRUE if either $a or $b is TRUE.

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

! $a Not TRUE if $a is not TRUE.

$a && $b And TRUE if both $a and $b are TRUE.

$a || $b Or TRUE if either $a or $b is TRUE.

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

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

Page 10: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

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 not18 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.

The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides the order of evaluation.

Operator Precedence

Associativity Operators Additional Information

non-

associative clone new clone and new

Left [ array()

Right ++ -- ~ (int) (float) (string) types and increment/decrement

Comparison Operators

Example Name Result

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

$a === $b

Identical TRUE if $a is equal to $b, and they are of the same type.

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

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

$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of

the same type.

$a < $b Less than TRUE if $a is strictly less than $b.

$a > $b Greater than TRUE if $a is strictly greater than $b.

$a <= $b Less than or equal to

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

$a >= $b Greater than or equal to

TRUE if $a is greater than or equal to $b.

Page 11: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

Operator Precedence

Associativity Operators Additional Information

(array) (object) (bool) @

non-

associative instanceof types

Right ! logical

Left * / % arithmetic

Left + - . arithmetic and string

Left << >> bitwise

non-associative

< <= > >= comparison

non-associative

== != === !== <> comparison

Left & bitwise and references

Left ^ bitwise

Left | bitwise

Left && logical

Left || logical

Left ? : ternary

Right = += -= *= /= .= %= &= |=

^= <<= >>= => assignment

Left and logical

Left xor logical

Left or logical

Left , many uses

For operators of equal precedence, left associativity means that evaluation proceeds from left to right, and right associativity means the opposite. For

operators of equal precedence that are non-associative those operators may not associate with themselves.

Page 12: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

TERNARY OPERATORS:

The Ternary comparison operator is an alternative to the if-else

statement, it's shorter and could be used to easily do a significant

difference depending on a condition without the need of a if

statement. The Ternary operator is made for two different actions,

one if the condition is true, the other one if it's false but with nested

Ternary operators we can use it like an if-elseif.else statement(more

to that later). The syntax of a Ternary operator looks like this:

(condition) ? true : false

The Ternary operator will return either the first value(if the condition

were true) or the second value (if the condition were false).

4. CONDITIONAL TESTS AND EVENTS IN PHP:

INTRODUCTION:

Any PHP script is built out of a series of statements. A statement can

be an assignment, a function call, a loop, a conditional statement or

even a statement that does nothing (an empty statement).

Statements usually end with a semicolon. In addition, statements

can be grouped into a statement-group by encapsulating a group of

statements with curly braces. A statement-group is a statement by

itself as well.

ALTERNATIVE SYNTAX FOR CONTROL STRUTURE:

PHP offers an alternative syntax for some of its control structures;

namely, if, while, for, foreach, and switch. In each case, the

basic form of the alternate syntax is to change the opening brace to

a colon (:) and the closing brace

to endif, endwhile, endfor endforeach, or endswitch,

respectively.

Example:

Page 13: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

<?php

if ($a == 5):

echo "a equals 5";

echo "...";

elseif ($a == 6):

echo "a equals 6";

echo "!!!";

else:

echo "a is neither 5 nor 6";

endif;

?>

IF STATEMENT:

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:

Syntax:

If (exp)

Statement;

Example:

<?php

if ($a > $b)

echo "a is bigger than b";

?>

ELSE Statement:

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:

Example:

<?php

if ($a > $b) {

echo "a is greater than b";

} else {

echo "a is NOT greater than b";

Page 14: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

}

?>

ELSE IF Statement:

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 ifexpression 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:

Example:

<?php

if ($a > $b) {

echo "a is bigger than b";

} elseif ($a == $b) {

echo "a is equal to b";

} else {

echo "a is smaller than b";

}

?>

5. PHP CONTROL FLOW:

WHILE Statement:

While loops are the simplest type of loop in PHP. They behave just

like their C counterparts. The basic form of a while statement is:

Syntax:

while (exp) :

statement

endwhile;

Example:

<?php

/* example 1 */

$i = 1;

while ($i <= 10) {

echo $i++; /* the printed value would be

$i before the increment

(post-increment) */

}

Page 15: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

/* example 2 */

$i = 1;

while ($i <= 10):

echo $i;

$i++;

endwhile;

?>

FOR EACH LOOP:

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;

}

Print_r($value);

SWITCH STATEMENT:

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

} elseif ($i == 1) {

echo "i equals 1";

} elseif ($i == 2) {

Page 16: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

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;

}

?>

BREAK STATEMENT:

break ends execution of the current for, foreach, while, do-

while or switch structure.

Example:

?php

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');

while (list(, $val) = each($arr)) {

if ($val == 'stop') {

break; /* You could also write 'break 1;' here. */

}

echo "$val<br />\n";

}

CONTINUE STATEMENT:

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.

Example:

<?php

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

if ($i == 2)

continue

print "$i\n";

}

?>

Page 17: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

6. STRING MANIPULATION IN PHP:

INTRODUCTION:

A string is series of characters, where a character is the same as a

byte.

String functions with examples:

STRING CONCATENATION OPERATOR:

To concatenate two string variables together, use the dot (.)

operator:

<?php $string1="Hello World"; $string2="1234";

echo $string1 . " " . $string2; ?>

OUTPUT: Hello World 1234

USING THE STRLEN FUNCTION:

The strlen() function is used to find the length of a string.

Let's find the length of our string "Hello world!":

<?php echo strlen("Hello world!");

?>

OUTPUT: 12

USING THE STRPOS FUNCTION:

Page 18: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

The strpos() function is used to search for a string or character within string.If a match is found in the string, this function will return the position of the first

match. If no match is found, it will return FALSE.Let's see if we can find the string "world" in our string:

<?php

echo strpos("Hello world!","world"); ?>

OUTPUT:

6

7. ARRAY:

INTRODUCTION:

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

$cars1="Volvo"; $cars2="BMW";

$cars3="Toyota";

CREATING AN ARRAY IN PHP:

In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

Indexed arrays - Arrays with numeric index

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

Page 19: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

INDEXED ARRAY:

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0):

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

or the index can be assigned manually:

$cars[0]="Volvo";

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

EXAMPLE:

<?php

$cars=array("Volvo","BMW","Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

?>

LOOP THROUGH AN INDEXED ARRAY:

EXAMPLE:

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

$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++) { echo $cars[$x];

echo "<br>"; }

?>

Page 20: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

ASSOCIATIVE ARRAY:

Associative arrays are arrays that use named keys that you assign to them.

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

EXAMPLE:

<?php

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old.";

?>

LOOP THROUGH AN ASSOCIATIVE ARRAY:

EXAMPLE:

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

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

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

} ?>

MULTIDIMENSIONAL ARRAY:

An array can also contain another array as a value, which in turn

can hold other arrays as well. In such a way we can create two- or three-dimensional arrays:

Page 21: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

EXAMPLE:

<?php // A two-dimensional array:

$cars = array (

array("Volvo",100,96), array("BMW",60,59), array("Toyota",110,100)

); ?>

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

In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

EXAMPLE:

$families = array

( "Griffin"=>array

( "Peter", "Lois",

"Megan" ),

"Quagmire"=>array ( "Glenn"

), "Brown"=>array

( "Cleveland", "Loretta",

"Junior" )

);

Page 22: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

OUTPUT:

Array (

[Griffin] => Array (

[0] => Peter [1] => Lois [2] => Megan

) [Quagmire] => Array

( [0] => Glenn

) [Brown] => Array (

[0] => Cleveland [1] => Loretta

[2] => Junior ) )

8. PHP FUNCTIONS:

CREATING PHP FUNCTIONS:

A function will be executed by a call to the function. Syntax

function functionName() {

code to be executed; }

Page 23: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

EXAMPLE:

<html> <body>

<?php

function writeName() { echo "Kai Jim Refsnes";

}

echo "My name is "; writeName();

?> </body>

</html>

OUTPUT:

My name is Kai Jim Refsnes

RETURNING VALUE FROM FUNCTION:

To let a function return a value, use the return statement.’

EXAMPLE:

<html>

<body> <?php

function add($x,$y) {

$total=$x+$y; return $total; }

echo "1 + 16 = " . add(1,16);

?>

</body> </html>

OUTPUT:

1+16 = 17

Page 24: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

USER DEFINED FUNCTION:

These are the functions that are defined by the user.

Syntax:

function function-name()

{

statement 1 :

statement 2 :

statement 3 : ...... } –

EXAMPLE:

<?php

function myfunction()

{ echo "Good Morning"; }

myfunction();

?>

FUNCTION WITHIN FUNCTION:

<?php function function1()

{ function function2()

{ echo "Good Morning <br>";

}

} function1();

function2(); ?>

FUNCTION ARGUMENTS:

PHP supports passing arguments by value (the default), passing by reference and default argument values.

Page 25: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

EXAMPLE: Passing function parameters by reference

<?php function add_some_extra(&$string) {

$string .= 'and something extra.'; }

$str = 'This is a string, '; add_some_extra($str); echo $str; // outputs 'This is a string, and something extra.'

?>

EXAMPLE: Use of default parameters in functions

<?php function makecoffee($type = "cappuccino")

{ return "Making a cup of $type.\n"; }

echo makecoffee(); echo makecoffee(null);

echo makecoffee("espresso"); ?>

OUTPUT:

Making a cup of cappuccino. Making a cup of . Making a cup of espresso.

9. SESSION AND COOKIES:

SESSIONS:

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more

customized applications and increase the appeal of your web site.

Page 26: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

STARTING A PHP SESSION: The session_start() function must appear BEFORE the <html> tag:

<?php

session_start(); ?>

<html> <body> </body>

</html>

STORING A SESSION VARIABLE: The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

<?php

session_start(); // store session data $_SESSION['views']=1;

?>

<html> <body>

<?php //retrieve session data

echo "Pageviews=". $_SESSION['views']; ?>

</body> </html>

DESTROYING A SESSION:

If you wish to delete some session data, you can use the unset() or the session_destroy() function.The unset() function is used to free the specified session variable:

<?php session_start();

if(isset($_SESSION['views'])) unset($_SESSION['views']);

?>

Page 27: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

You can also completely destroy the session by calling the

session_destroy() function:

<?php session_destroy(); ?>

session_destroy() will reset your session and you will lose all your stored session data.

PHP COOKIES:

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page

with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

HOW TO CREATE COOKIE:

The setcookie() function is used to set a cookie.

The setcookie() function must appear BEFORE the <html> tag.

SYNTAX:

setcoookie(name, value, expire, path , domain)

EXAMPLE:

<?php $expire=time()+60*60*24*30;

setcookie("user", "Alex Porter", $expire); ?>

RETRIEVING COOKIE VALUE:

The PHP $_COOKIE variable is used to retrieve a cookie value.

EXAMPLE:

<?php

// Print a cookie echo $_COOKIE["user"];

// A way to view all cookies print_r($_COOKIE);

?>

Page 28: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

DELETING COOKIE:

When deleting a cookie you should assure that the expiration date is

in the past. <?php

// set the expiration date to one hour ago setcookie("user", "", time()-3600);

?>

COOKIE SECURITY ISSUE:

> What does cookie actually contain. What ever you put in there. Arbitrary data, around 1-4 kb max.

Additionally: A time when it becomes invalid, an URL and a "ssl" flag.

> What information can we get from cookies. See above

> List potential vulnerabilities that exist for the client if this cookie data were transmitted in plain text.

Not more and not less vulnerabilities than transmitting anything else unencrypted too.

> List potential vulnerabilities that exist for a server if a client were allowed to modify the contents of the local cookie file and it were

transmitted to the server. A client is allowed to modify its own cookies. A server side

programmer must know this and never rely on cookies containing anything valid.

10. FILE AND DIRECTORY ACCESS USING PHP:

PHP INCLUDE FILES:

In PHP, you can insert the content of one PHP file into another PHP file before the server executes it.The include and require statements are used to

insert useful codes written in other files, in the flow of execution.

require will produce a fatal error (E_COMPILE_ERROR) and stop the script include will only produce a warning (E_WARNING) and the script will

continue

So, if you want the execution to go on and show users the output, even if the include file is missing, use include. Otherwise, in case of FrameWork, CMS or a complex PHP application coding, always use require to include a key file to the

flow of execution. This will help avoid compromising your application's security and integrity, just in-case one key file is accidentally missing.

Page 29: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header

needs to be updated, you can only update the header include file.

SYNTAX:

include ‘filename’;

Or

require ‘filename’;

OPENING A FILE:

The fopen() function is used to open files in PHP.The first parameter of

this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:

<html>

<body> <?php

$file=fopen("welcome.txt","r"); ?>

</body> </html>

The file may be opened in one of the following modes:

Modes Description

R Read only. Starts at the beginning of the file

r+ Read/Write. Starts at the beginning of the file

W Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist

w+ Read/Write. Opens and clears the contents of file; or creates a new file if

it doesn't exist

A Append. Opens and writes to the end of the file or creates a new file if it doesn't exist

a+ Read/Append. Preserves file content by writing to the end of the file

X Write only. Creates a new file. Returns FALSE and an error if file already exists

Page 30: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

EXAMPLE:

<html>

<body>

<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?>

</body>

</html>

CLOSING A FILE:

The fclose() function is used to close an open file: <?php $file = fopen("test.txt","r");

//some code to be executed

fclose($file); ?>

CHECK END OF FILE:

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.

SYNTAX: if (feof($file)) echo "End of file";

READING A FILE LINE BY LINE:

The fgets() function is used to read a single line from a file. EXAMPLE:

<?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached

while(!feof($file)) {

echo fgets($file). "<br>"; } fclose($file);

?>

READING A FILE CHARACTER BY CHARACTER:

Page 31: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

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

<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!");

while (!feof($file)) { echo fgetc($file);

} fclose($file);

?>

PHP FILE UPLOAD:

CREATE AN UPLOAD FILE FORM:

<html> <body>

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

<label for="file">Filename:</label> <input type="file" name="file" id="file"><br> <input type="submit" name="submit" value="Submit">

</form>

</body> </html>

The enctype attribute of the <form> tag specifies which content-type to

use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded

The type="file" attribute of the <input> tag specifies that the input should

be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field

CREATE AN UPLOAD FILE SCRIPT:

The "upload_file.php" file contains the code for uploading a file: <?php

if ($_FILES["file"]["error"] > 0) {

echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else

{ echo "Upload: " . $_FILES["file"]["name"] . "<br>";

echo "Type: " . $_FILES["file"]["type"] . "<br>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; echo "Stored in: " . $_FILES["file"]["tmp_name"];

} ?>

Page 32: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

By using the global PHP $_FILES array you can upload files from a client computer to the remote server.

$_FILES["file"]["name"] - the name of the uploaded file

$_FILES["file"]["type"] - the type of the uploaded file $_FILES["file"]["size"] - the size in kilobytes of the uploaded file

$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server

$_FILES["file"]["error"] - the error code resulting from the file upload

11. OBJECT ORIENTATION IN PHP:

DEFINING PHP CLASSES: The general form for defining a new class in PHP is as follows:

<?php class phpClass{ var $var1;

var $var2 = "constant string"; function myfunc ($arg1, $arg2) {

} ?>

The special form class, followed by the name of the class that you want to define.

A set of braces enclosing any number of variable declarations and function definitions.

Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value.

Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.

Page 33: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

EXAMPLE:

<?php class Books{

/* Member variables */ var $price;

var $title; /* Member functions */ function setPrice($par){

$this->price = $var; }

function getPrice(){ echo $this->price ."<br/>";

} function setTitle($par){ $this->title = $par;

} function getTitle(){

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

?>

The variable $this is a special variable and it refers to the same object ie. itself.

CREATING OBJECTS IN PHP:

Once you defined your class, then you can create as many objects as you

like of that class type by using new keyword.

$physics = new Books; $maths = new Books;

$chemistry = new Books; CALLING MEMBER FUNCTIONS:

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process

member variable of related object only.

$physics->setTitle( "Physics for High School" ); $chemistry->setTitle( "Advanced Chemistry" ); $maths->setTitle( "Algebra" );

$physics->setPrice( 10 );

$chemistry->setPrice( 15 ); $maths->setPrice( 7 );

Page 34: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

Now you call another member functions to get the values set by in above example:

$physics->getTitle(); $chemistry->getTitle();

$maths->getTitle(); $physics->getPrice();

$chemistry->getPrice(); $maths->getPrice();

OUTPUT:

Physics for High School Advanced Chemistry

Algebra 10 15

7

CONSTRUCTOR IN PHP:

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.PHP

provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.

function __construct( $par1, $par2 ){

$this->price = $par1; $this->title = $par2;

}

DESTRUCTOR IN PHP:

Like a constructor function you can define a destructor function using

function __destruct(). You can release all the resourceses with-in a destructor.

function __destruct( $par1, $par2 ){

$this->price = $par1; $this->title = $par2;

}

INHERITANCE:

PHP class definitions can optionally inherit from a parent class definition

by using the extends clause. The syntax is as follows:

class Child extends Parent

{ <definition body>

Page 35: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

}

The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics:

Automatically has all the member variable declarations of the parent class.

Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.

Following example inherit Books class and adds more functionality based on the

requirement.

class Novel extends Books{ var publisher; function setPublisher($par){

$this->publisher = $par; }

function getPublisher(){ echo $this->publisher. "<br />"; }

}

12. HANDLING EMAIL WITH PHP:

SENDING PLAIN TEXT EMAIL:

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the

subject of the the message and the actual message additionally there are other two optional parameters.

mail( to, subject, message, headers, parameters );

Parameter Description

To Required. Specifies the receiver / receivers of the email

Subject Required. Specifies the subject of the email. This

parameter cannot contain any newline characters

Message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70

characters

Headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a

CRLF (\r\n)

parameters Optional. Specifies an additional parameter to the sendmail program

Page 36: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.

Multiple recipients can be specified as the first argument to the mail() function in

a comma separated list.

EXAMPLE:

<html> <head>

<title>Sending email using PHP</title> </head>

<body> <?php

$to = "[email protected]"; $subject = "This is subject"; $message = "This is simple text message.";

$header = "From:[email protected] \r\n"; $retval = mail ($to,$subject,$message,$header);

if( $retval == true ) { echo "Message sent successfully...";

} else

{ echo "Message could not be sent..."; }

?> </body>

</html>

SENDING HTML EMAIL:

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML

syntax. But PHP provides option to send an HTML message as actual HTML message.

While sending an email message you can specify a Mime version, content type

and character set to send an HTML email.

Page 37: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

EXAMPLE:

<html> <head>

<title>Sending HTML email using PHP</title> </head>

<body> <?php $to = "[email protected]";

$subject = "This is subject"; $message = "<b>This is HTML message.</b>";

$message .= "<h1>This is headline.</h1>"; $header = "From:[email protected] \r\n";

$header = "Cc:[email protected] \r\n"; $header .= "MIME-Version: 1.0\r\n"; $header .= "Content-type: text/html\r\n";

$retval = mail ($to,$subject,$message,$header); if( $retval == true )

{ echo "Message sent successfully..."; }

else {

echo "Message could not be sent..."; } ?>

</body> </html>

: SENDING ATTACHMENTS WITH EMAIL:

To send an email with mixed content requires to set Content-type header tomultipart/mixed. Then text and attachment sections can

be specified within boundaries.A boundary is started with two hyphens followed by a unique number which can not appear in the message part of

the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's

final section must also end with two hyphens.Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This

adds \r\n inside the file at regular intervals, normally every 76 characters.

EXAMPLE:

<html> <head>

<title>Sending attachment using PHP</title> </head>

Page 38: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

<body> <?php

$to = "[email protected]"; $subject = "This is subject";

$message = "This is test message."; # Open a file $file = fopen( "/tmp/test.txt", "r" );

if( $file == false ) {

echo "Error in opening file"; exit(); }

# Read the file into a variable $size = filesize("/tmp/test.txt");

$content = fread( $file, $size); # encode the data for safe transit

# and insert \r\n after every 76 chars. $encoded_content = chunk_split( base64_encode($content));

# Get a random 32 bit number using time() as seed. $num = md5( time() );

# Define the main headers.

$header = "From:[email protected]\r\n"; $header .= "MIME-Version: 1.0\r\n"; $header .= "Content-Type: multipart/mixed; ";

$header .= "boundary=$num\r\n"; $header .= "--$num\r\n";

# Define the message section $header .= "Content-Type: text/plain\r\n";

$header .= "Content-Transfer-Encoding:8bit\r\n\n"; $header .= "$message\r\n";

$header .= "--$num\r\n";

# Define the attachment section $header .= "Content-Type: multipart/mixed; "; $header .= "name=\"test.txt\"\r\n";

$header .= "Content-Transfer-Encoding:base64\r\n"; $header .= "Content-Disposition:attachment; ";

$header .= "filename=\"test.txt\"\r\n\n"; $header .= "$encoded_content\r\n"; $header .= "--$num--";

# Send email now

$retval = mail ( $to, $subject, "", $header ); if( $retval == true ) {

echo "Message sent successfully..."; }

else

Page 39: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement

{ echo "Message could not be sent...";

} ?>

</body> </html>

Page 40: PHP INTRODUCTION - miracleindia.com · PHP INTRODUCTION a) AWHAT IS PHP: ... or Task Scheduler (on Windows). ... Any PHP script is built out of a series of statements. A statement