SlideShare a Scribd company logo
1 of 210
PHP


       By
 OpenGurukul Team

www.opengurukul.com
Chapter 1
Introduction to php




      www.opengurukul.com   2
Introduction to web application
What is Web Application?
Components of Web Application
-Presentation
-Processing
Uses of PhP
- Server Side Scripting
- Command Line Scripting
                   www.opengurukul.com   3
- Writing Desktop Applications
Introduction to PHP
Basic PHP Syntax
<?php ?>
Example of php program
<html><body>
<?php echo “Hello world”; ?>
</body></html>
Comments in php
<html><body>
<?php //This is a comment
/*This is a comment block */?>
                               www.opengurukul.com   4
</body></html>
Chapter 2




Php data types

    www.opengurukul.com   5
Php data Types
A data type refers to the type of data a variable can store.
8 different type of data types are:
integer numbers
floating point numbers
strings
booleans
arrays
objects
resouces
                             www.opengurukul.com               6
null
Integers
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
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)
?>
Integer Data type can be divided into two types – Octal, Hexadecimal,
   Decimal
                                  www.opengurukul.com                   7
Floating point numbers
Floating point numbers are those data types which can store decimal values
Example
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>




                             www.opengurukul.com                         8
Strings
A string is series of characters.
Example
<?php
$str=”Hello world”;
echo $str;
?>
Output: Hello World




                                www.opengurukul.com   9
Booleans
This variable must be true or false
Example
<? php
$foo = True;
// assign the value TRUE to $foo
?>




                             www.opengurukul.com   10
Arrays
An array is a variable that holds a group of values.
Referencing array elements is done like this:
Example
$arrayName[index];
assign a value to an array position:
$listing[0] = "first item";
$listing[1] = "second item";
$listing[2] = "third item";



                               www.opengurukul.com     11
Object
An object is a data type that allows     echo "This is example of object data
  for the storage of not only data         type.";
  but also information on how to
  process that data.                     }

Example:                                 }

<?php                                    $bar = new foo;

class foo                                $bar->do_foo();

{                                        ?>

function do_foo()                        Output :This is example of object
                                           data type.
{

                              www.opengurukul.com                            12
Resources and Null
Resources
Resources are really integers under the surface. Their main benefit is that
  they're garbage collected when no longer in use. When the last reference
  to a resource value goes away, the extension that created the resource is
  called to free any memory, close any connection, etc. for that resource:
Null
The NULL value represents a variable that has no value
<?php
$var = NULL;
?>

                             www.opengurukul.com                         13
Type Casting
PHP will automatically convert data types as necessary across the board
Example
<?php
  $mystring = "wombat";
  $myinteger = (integer)$mystring
?>
At first, $mystring contains a string.
However, we type cast it to be an integer, so PHP will convert it to an
 integer, and place the result into $myinteger


                                www.opengurukul.com                       14
Type juggling
if we add two integer variables then the result is integer type
but if we add one integer and one float type variable then the result is float
  type because float type has a higher precedence than integer.
Example
<?php
$foo = "0";                       // $foo is string (ASCII 48)
$foo += 2;                       // $foo is now an integer (2)
$foo = $foo + 1.3;               // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)
                                www.opengurukul.com                              15
?>
Chapter 3




Variables

  www.opengurukul.com   16
variables
Variables are used for storing values


When a variable is declared, it can be used over and over again in your
  script.


All variables in PHP start with a $ sign symbol.


The variable name is case-sensitive.
Ex-$var_name = value;


                               www.opengurukul.com                        17
PHP-loosely typed language
Example
<?php
$txt="Hello World!";
$x=16;
?>
a variable does not need to be declared before adding a value to it.
It automatically converts the variable to the correct data type, depending on
    its value.



                               www.opengurukul.com                          18
Variable scope
Example
<?php
$a=1;                            /* global scope*/
function test()
{
echo $a;
}                    /* reference to local scope variable*/}
test();
?>
output:It will not produce any output
                               www.opengurukul.com             19
Global keyword
Example<?php
      $a=1;
      $b=2;
      function sum()
      {
      global $a, $b;
      $b = $a + $b;
      }
      Sum();
      echo $b;         www.opengurukul.com   20
      ?>   output: 3
Variables variables
Example
<?php
$a=”hello”;
$$a=”world”;
echo "$a ${$a}";
?>
Here $a is hello then $hello is world so final out put is hello world




                               www.opengurukul.com                      21
Chapter 4



Constants And
 Expressions

    www.opengurukul.com   22
Constants
Constants just as variables are used to store information.


difference between constants and variables is that constant value can not be
    changed in the process of running program.


A constant is case-sensitive by default


define a constant by using the define()-function or the const keyword
   outside a class definition.


                              www.opengurukul.com                         23
Define function
Example
<?php
define("PASSWORD","admin"); // first we define a constant PASSWORD
echo (PASSWORD);              // will display value of PASSWORD
  constant, i.e. admin
echo constant("PASSWORD"); // will also display admin
echo "PASSWORD";              // will display PASSWORD
?>



                            www.opengurukul.com                      24
Const keyword
Example
<?php


const CONSTANT = 'Hello World'; // Works as of PHP 5.3.0


echo CONSTANT;
?>




                            www.opengurukul.com            25
Magic Constants
PHP provides a large number of predefined constants to any script which it
  runs.
__LINE__:The current line number of the file
__FILE__:The full path and filename of the file
__DIR__:The directory of the file
__FUNCTION__:The function name(case-sensitive)
__CLASS__:The class name(case-sensitive)
__METHOD__:The class method name(case-sensitive)
__NAMESPACE__:The name of the current namespace (case-sensitive)


                              www.opengurukul.com                            26
Expressions
Example
$a = “5"
you're assigning '5' into $a. '5', obviously, has the value 5, or in other words
  '5' is an expression with the value of 5 (in this case, '5' is an integer
  constant).
After this assignment, you'd expect $a's value to be 5 as well.
So if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5.
  In other words.
$a is an expression with the value of 5 as well.



                                www.opengurukul.com                            27
Chapter 5




Operators

  www.opengurukul.com   28
Operators
Operators are used to operate on values.


Different types of operators we are using in php.
i.Arithmetic Operators
ii.Assignment Operators
iii.Comparison Operators
iv.Logical Operators




                              www.opengurukul.com   29
Arithmetic Operators
Operator    Description              Example       Result
+           Addition                 x=2,x+2       4
-           Subtraction              x=2,5-x       3
*           Multiplication           x=4           20
                                     x*5
/           Division                 15/5          3
                                     5/2           2.5
%           Modulus (division        5%2           1
            remainder)               10%8          2
                                     10%2          0
++          Increment                x=5           x=6
                                     x++
--          Decrement                x=5           x=4
                                     x--
                             www.opengurukul.com            30
Assignment Operators

Operator   Example           Is The Same As
=          x=y               x=y
+=         x+=y              x=x+y
-=         x-=y              x=x-y
*=         x*=y              x=x*y
/=         x/=y              x=x/y
.=         x.=y              x=x.y
%=         x%=y              x=x%y




             www.opengurukul.com              31
Comparision Operators

Operator   Description           Example
==         is equal to           5==8 returns
                                 false
!=         is not equal          5!=8 returns true
<>         is not equal          5<>8 returns true
>          is greater than       5>8 returns false
<          is less than          5<8 returns true
>=         is greater than or    5>=8 returns
           equal to              false
<=         is less than or       5<=8 returns true
           equal to


           www.opengurukul.com                       32
Logical Operators

Operator    Description      Example
&&          and              x=6
                             y=3

                             (x < 10 && y > 1) returns true
||          or               x=6
                             y=3

                             (x==5 || y==5) returns false
!           not              x=6
                             y=3

                             !(x==y) returns true
                     www.opengurukul.com                      33
Operator precedence
Example
1 + 5 * 3=16 and not 18


because ("*") operator has a higher precedence than the ("+") operator
Parentheses may be used to force precedence, if necessary.


(1 + 5) * 3=18


If operator precedence is equal, left to right associativity is used.

                                www.opengurukul.com                      34
Chapter 6




Control Structure

      www.opengurukul.com   35
Conditional Statements
Conditional statements are used to perform different actions based on
  different conditions.


PhP have the following conditional statements
if statement
if else statement
if elseif else statement
switch statement



                              www.opengurukul.com                       36
If statement
Syntax                                       Example
if (condition)                               <?php

code to be executed if condition is true;    $a=2;

                                             if($a==2)
else
                                                  echo “It is two”;
code to be executed if condition is false;
                                             ?>

                                             output::It is two




                                  www.opengurukul.com                 37
If else Statement
Syntax                                    Example
                                          <?php
if (condition)
                                          $a=2;
code to be executed if condition is
  true;                                   $b=3;

                                          if($b>$a)
else
                                          {
code to be executed if condition is
                                          echo “b is greater”;
  false;
                                          }

                                          else

                                          {

                                          echo “a is greater”;

                                          }
                               www.opengurukul.com                  38

                                          ?> output::b is greater
The if...else if....else Statement
Use the if....elseif...else statement to select one of several blocks of code to
  be executed.
Syntax
if (condition)
 code to be executed if condition is true;
elseif (condition)
 code to be executed if condition is true;
else
 code to be executed if condition is false;

                                www.opengurukul.com                            39
if..else if..else statement
Example                                 elseif ($a == $b)
<?php                                   {
$a=3;                                   echo "a is equal to b";
$b=4;                                   }
if ($a > $b)                            else
{                                       {
echo "a is bigger than b";              echo "a is smaller than b";
}                                       }
                                        ?>
                                        output: a is smaller than b
                             www.opengurukul.com                      40
Switch statement
Use the switch statement to select one of many blocks of code to be
  executed.
Syntax
switch (n){
case label1:

code to be executed if n=label1;
break;
case label2:

code to be executed if n=label2;
break;

default:
                                       www.opengurukul.com            41
code to be executed if n is different from both label1 and label2;}
Switch statement
Example                           case 3:

<?php                             echo "Number 3";

$x=1;                              break;

switch ($x)                       default:

{                                 echo "No number between 1 and 3";

case 1:                           }

echo "Number 1";                  ?>

break;                            output:Number 1

case 2:
echo "Number 2";

break;
                       www.opengurukul.com                            42
looping
A loop is simply a block of code that executes multiple times.
The following loops are available in php
- while statement
- do while statement
- for statement
- foreach statement




                            www.opengurukul.com                  43
The while loop
This loop executes a block of code      Example
  while a condition is true.
                                        <?php
Syntax
                                        $i=1;
while (condition)
                                        while($i<=5)
{
                                        {
code to be executed;
                                        echo $i;
}
                                         $i++;
                                        }
                                        ?>
                                        output:12345
                             www.opengurukul.com       44
The do...while Statement
The loop will always execute the block of    Example
  code once,then check the condition,
  and repeat the loop while the              <?php
  condition is true.
                                              $i=1;
Syntax
                                             do
do
                                             {
{

code to be executed;
                                             $i++;

}                                            echo $i;
while (condition);                            }
                                             while ($i<=5);
                                             ?>
                                  www.opengurukul.com         45
                                             output:123456
The for statement
The loop is used when you know in             Example
  advance how many times the
                                              <?php
  script should run.
                                              for ($i=1; $i<=5; $i++)
Syntax
                                              {
for (init; condition; increment)
                                              echo $i ;
{

code to be executed;                          }

}                                             ?>

                                              output:12345



                                   www.opengurukul.com                  46
The foreach Loop
The foreach loop is used to loop through arrays.
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to
  $value (and the array pointer is moved by one) - so on the next loop
  iteration, you'll be looking at the next array value.


                               www.opengurukul.com                           47
Chapter 7




 Array

 www.opengurukul.com   48
Array
Array is a special type of variable which stores similar types of data.
There are 3 types of array
Numeric array:An array with a numeric index
Associative array:An array where each ID key is associated with a
  value
Multidimensional array:An array containing one or more arrays




                             www.opengurukul.com                          49
Numeric Arrays
There are two methods to create a numeric array.
i.In the following example the index are automatically assigned (the index starts at 0):
Ex-$cars=array("Saab","Volvo","BMW","Toyota");
ii.In the following example we assign the index manually:
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";




                                   www.opengurukul.com                                50
Associative Arrays
Example1
In this example we use an array to assign ages to the different persons
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example2
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";




                              www.opengurukul.com                         51
Multidimensional Arrays
Example
<?php

$families = array(

"Griffin"=>array ("Peter","Lois","Megan" ),

"Quagmire"=>array("Glenn" ),

"Brown"=>array ("Cleveland", "Loretta", "Junior" ));

?>

Output
Array([Griffin] => Array([0] => Peter [1] => Lois [2] => Megan)

[Quagmire] => Array([0] => Glenn )

[Brown] => Array([0] => Cleveland [1] => Loretta [2] => Junior ))
                                         www.opengurukul.com        52
Array Functions
List()
The list() function is used to assign values to a list of variables in one operation.

Syntax
list(var1,var2...)

Example
<?php $my_array = array("Dog","Cat","Horse");
list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
?>

output:I have several animals, a Dog, a Cat and a Horse.
                                    www.opengurukul.com                                 53
count()
The count() function counts the elements of an array, or the properties of an object.

Syntax
count(array,mode)
Example
<?php $people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = count($people);
echo $result;
?>

output: 4


                                  www.opengurukul.com                                   54
array_sum()
The array_sum() function returns the sum of all the values in the array.

Syntax
array_sum(array)
Example
<?php
$a=array(0=>"5",1=>"15",2=>"25");
echo array_sum($a);
?>

output: 45


                                  www.opengurukul.com                      55
Many other functions are there

array_pop() - Pop the element off the end of array
array_push - Push one or more elements onto the end of array
sort - Sort an array
asort - Sort an array and maintain index association
arsort - Sort an array in reverse order and maintain index association
ksort - Sort an array by key
krsort - Sort an array by key in reverse order
print_r - Display all the readable information about the array


                                  www.opengurukul.com                    56
Chapter 8



PHP Forms and User
      Inputs

      www.opengurukul.com   57
Html form example
Example
The example below contains an HTML form with two input fields and a submit button:
  html_form.php
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
                                www.opengurukul.com                             58
</html>
Collecting data from a form
When a user fills out the form above and click on the submit button, the form
  data is sent to a PHP file, called "welcome.php":
"welcome.php" looks like this:
File: welcome.php
<html><body>
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
</body></html>
ouput: Welcome John!
        You are 28 years old.
                                 www.opengurukul.com                       59
Php $_GET function
It is used to collect values from a form.


Information sent from a form is visible to everyone (it will be
   displayed in the browser's address bar)


Not fit for sending passwords or other sensitive information!


Not suitable for very large variable values.(not exceeding 2000
  characters)

                             www.opengurukul.com                  60
$_GET function
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />

Age: <input type="text" name="age" />
<input type="submit" />

</form>

URL looks like this:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
In welcome.php
Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
                              www.opengurukul.com         61
Php $_POST function
It is also used to collect values from a form.
Information sent from a form is invisible to others and has no limits on
   the amount of information to send.
here is an 8 Mb max size for the POST method, by default .
Size can be changed by setting the post_max_size in the php.ini file.
It is fit for the password or any other sensitive information




                             www.opengurukul.com                      62
$_POST function
Example
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
The URL will look like this:
http://www.w3schools.com/welcome.php
In welcome.php
Welcome <?php echo $_POST["fname"]; ?>!<br />
                             www.opengurukul.com
You are <?php echo $_POST["age"]; ?> years old.    63
Php $_REQUEST function
This function contains the contents of both $_GET, $_POST, and
  $_COOKIE.
It can be used to collect form data sent with both the GET and POST
    methods.
Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
You are <?php echo $_REQUEST["age"]; ?> years old.




                              www.opengurukul.com                     64
Chapter 9




String Handling

     www.opengurukul.com   65
String Variables
A string variable is used to store and manipulate text.
Example
<?php
$txt="Hello World";
echo $txt;
?>


output: Hello World


                            www.opengurukul.com           66
String Literal Syntax
A string literal can be specified in four different ways:
single quoted
double quoted
heredoc syntax
Example of single quoted:
    <?php
    $str='Hello World';
    ?>



                                www.opengurukul.com         67
Example of double quote
<?php $str=”hello world”; ?>

Example of heredoc
Heredoc is a robust way to create string in PHP with more lines but without using
  quotations.

<?php
$str = <<<DEMO
This is a demo message with heredoc.
DEMO;
echo $str; ?>
output: This is a demo message with heredoc.
                            www.opengurukul.com                                     68
The concatenation operator
The concatenation operator (.) is used to put two string values together.
Example
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>
output: Hello World! What a nice day!




                                www.opengurukul.com                         69
String Function
Strlen()
The strlen() function is used to return the length of a string.
Syntax
int strlen ( string $string )
Example
<?php
$str = 'abcdef';
echo strlen($str); // 6
$str = ' ab cd ';
echo strlen($str); // 7
                                www.opengurukul.com               70
?>
str_replace()
It replaces some characters with some other characters in a string.

Syntax
str_replace(find,replace,string,count)

Example
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
output:Array([0] => blue [1] => pink [2] => green [3] => yellow)
        Replacements: 1               www.opengurukul.com             71
strrev()
The strrev() function reverses a string.
Syntax
strrev(string)
Example
<?php
echo strrev("Hello World!");
?>

output : !dlroW olleH




                               www.opengurukul.com   72
Strrpos()
The strrpos() function finds the position of the last occurrence of a string
  inside another string.
Syntax
strrpos(string,find,start)
Example
<?php
echo strrpos("Hello world!","wo");
?>
output: 6


                                     www.opengurukul.com                       73
Explode()
The explode() function breaks a string into an array.

Syntax
explode(separator,string,limit)

Example
<?php

$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));

?>

output:
Array([0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day.)

                                         www.opengurukul.com                          74
Chapter 10




Function

 www.opengurukul.com   75
Function
A function is a block of code that performs a specific task. It has a
   name and it is reusable.
There are two types of functions
-Built-in functions
-User defined functions




                             www.opengurukul.com                        76
User defined function
Functions those are defined by user     Example
  according to user requirements.       <?php
Syntax                                  function writeName()
function functionName()                 {

{                                       echo "Kai Jim Refsnes";

code to be executed;                     }

}                                       echo "My name is ";
                                        writeName();
                                        ?>

                                        output: My name is Kai Jim Refsnes


                             www.opengurukul.com                             77
Function Arguments
Information may be passed to                  echo "My sister's name is ";
   functions via the argument list,           writeName("Hege");
   which is a comma-delimited list of
   expressions.                                ?>
                                              output:My name is Kai Jim Refsnes.
Example
                                                         My sister's name is Hege Refsnes.
<?php
function writeName($fname)

{
echo $fname . " Refsnes.<br />";

}
echo "My name is ";

writeName("Kai Jim");
                                   www.opengurukul.com                                       78
Pass by value vs. Pass by
                    reference
Ex-pass by value                            Ex-pass by reference
<?php                                       <?php

function pass_by_value($param)              function_by_reference(&$param)

{                                           {

push_array($param, 4, 5);                   push_array($param, 4, 5);

}                                           }

$ar = array(1,2,3);                         $ar = array(1,2,3);

pass_by_value($ar);                         pass_by_reference($ar);

foreach ($ar as $elem)                      foreach ($ar as $elem)

{                                           {

print "<br>$elem";                          print "<br>$elem";

}                                           }
                                 www.opengurukul.com                         79

?> output:1, 2, 3                           ?> output: 1, 2, 3, 4, 5.
Return values
To let a function return a value, use the return statement .
Example
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
ouput:1 + 16 = 17               www.opengurukul.com            80
Built-in function
Date()
The PHP date() function is used to format a time and/or date.

Syntax
date(format,timestamp)
Example
<?php echo date("Y/m/d") . "<br />";

echo date("Y.m.d") . "<br />";
echo date("Y-m-d"); ?>

output:2009/05/11
       2009.05.11

       2009-05-11                      www.opengurukul.com      81
mktime()
The mktime() function returns the Unix timestamp for a date.

Syntax
mktime(hour,minute,second,month,day,year,is_dst)
Example
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));

echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>
output:Tomorrow is 2009/05/12



                                     www.opengurukul.com       82
include()
You can insert the content of one PHP file into another PHP file before the server
  executes it

Example
<html>
<body>

<?php include("header.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>

</body>
</html>


                                  www.opengurukul.com                                83
Require()
It is identical as the include function

Example()
<?php
require("wrongFile.php");
echo "Hello World!";
?>




                                     www.opengurukul.com   84
Include vs Require
Include                                     Require
Generates warning if file not found         Gives fatal error if file not found
Script will continue execution              Script will stop




                                 www.opengurukul.com                              85
require_once() & include_once()
include_once() and require_once() function is used to include a file only
   once in a page.
Example
<?php
require_once(“header.php");
include_once(“header.php");
?>




                               www.opengurukul.com                          86
Chapter 11




cookies

 www.opengurukul.com   87
cookie
A cookie is often used to identify a user.


A cookie is a small file that the server embeds on the user's computer.


It is used for an origin website to send state information to a user's browser
    and for the browser to return the state information to the origin site




                               www.opengurukul.com                               88
Creating Cookie
The setcookie() function is used to set a cookie.
Syntax
setcookie(name, value, expire, path, domain);
Example
<?php
setcookie("user", "Alex Porter", time()+3600);
?>




                                  www.opengurukul.com   89
Retrieving Cookie Value
The PHP $_COOKIE variable is used to retrieve a cookie value.
Example
<?php


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


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


?>


                               www.opengurukul.com              90
Deliting cookie
When deleting a cookie you should assure that the expiration date is in the
  past.
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>




                                      www.opengurukul.com                     91
Chapter 12




Sessions

 www.opengurukul.com   92
Sessions
A PHP session variable is used to store information about, or change
  settings for a user session.


Session variables hold information about one single user, and are
 available to all pages in one application.




                           www.opengurukul.com                      93
Starting a PHP Session
Before you can store user information in your PHP session, you must first
  start up the session.
Session_start() is used to start a session
Example
<?php session_start(); ?>
<html>
<body>
</body>
</html>


                              www.opengurukul.com                           94
Storing a Session Variable
Example
<?php
session_start();
$_SESSION['user']=”Ram”;
echo $_SESSION['user'];
?>
output:Ram




                           www.opengurukul.com   95
Destroying a Session
Unset() and session_destroy() are used to delete the session
unset():It is used to free the specified session variable:
Example of unset()
<?php
unset($_SESSION['views']);
?>

session_destroy():is used to compltetly destroy the session
Example of session_destroy()
<?php
session_destroy();
                               www.opengurukul.com             96
?>
Chapter 13




File Handling

    www.opengurukul.com   97
File open
 Fopen() is used to open a file
first parameter shows file name and the second parameter shows mode of
    the file
Example
<?php
$file=fopen("welcome.txt","r");
?>




                                  www.opengurukul.com                    98
Closing a File
The fclose() function is used to close an open file:
Example
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>




                                 www.opengurukul.com   99
Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached.
Example
<?php
if (feof($file))
echo "End of file";
?>




                              www.opengurukul.com                         100
File Reading - 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);
?>                                  www.opengurukul.com              101
File Reading - Character by
                 Character
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);
?>
                                    www.opengurukul.com                102
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" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
                                    www.opengurukul.com                       103
Create The Upload Script
Example                                         else

<?php                                           {

if ($_FILES["file"]["error"] > 0)                echo "Upload: " . $_FILES["file"]["name"]
                                                   . "<br />";
{
                                                echo "Type: " . $_FILES["file"]["type"] .
echo "Error: " . $_FILES["file"]["error"] .        "<br />";
   "<br />";
                                                echo "Size: " . ($_FILES["file"]["size"] /
}                                                  1024) . " Kb<br />";
                                                echo "Stored in: " . $_FILES["file"]
                                                   ["tmp_name"];
                                                }
                                                ?>
                                     www.opengurukul.com                                     104
Restrictions on Upload
Example                                              echo "Upload: " . $_FILES["file"]["name"] .
                                                        "<br />";
<?php
                                                     echo "Type: " . $_FILES["file"]["type"] . "<br
if ((($_FILES["file"]["type"] == "image/gif") ||        />";
     ($_FILES["file"]["type"] == "image/jpeg") ||
     ($_FILES["file"]["type"] == "image/pjpeg"))      echo "Size: " . ($_FILES["file"]["size"] /
     && ($_FILES["file"]["size"] < 20000))              1024) . " Kb<br />";

{                                                    echo "Stored in: " . $_FILES["file"]
                                                        ["tmp_name"];
if ($_FILES["file"]["error"] > 0)
                                                     }
{
                                                     }else
echo "Error: " . $_FILES["file"]["error"] . "<br
   />";                                               {

}else                                                echo "Invalid file";

{                                                    }
                                          www.opengurukul.com                                         105
                                                     ?>
Chapter 14




Sending Email

    www.opengurukul.com   106
Sending Email using mail()
The PHP mail() function is used to       Example
  send emails from inside a script.
                                         <?php
Syntax                                   $to = "someone@example.com";
mail(to,subject,message,headers,pa       $subject = "Test mail";
  rameters)
                                         $message = "Hello! This is a simple email
                                           message.";
                                         $from = "someonelse@example.com";

                                         $headers = "From: $from";
                                         mail($to,$subject,$message,$headers);

                                         echo "Mail Sent."; ?>



                              www.opengurukul.com                                    107
Chapter 15




Error Handling

    www.opengurukul.com   108
Default & Other Methods
The default error handling in PHP is very simple. An error message with
  filename, line number and a message describing the error is sent to the
  browser.
different error handling methods:
-Simple "die()" statements
-Custom errors and error triggers
-reporting




                              www.opengurukul.com                           109
Basic Error Handling: Using the
              die() function
Example
<?php if(!file_exists("welcome.txt"))
{

die("File not found");
}

Else
{

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

Now if the file does not exist you get an error like this: File not found
                                        www.opengurukul.com                 110
Creating a Custom Error Handler
This function must be able to handle a minimum of two parameters
i.e (error level and error message) but can accept up to five parameters
(optionally: file, line-number, and the error context):
Syntax
error_function(error_level,error_message,
error_file,error_line,error_context)




                                www.opengurukul.com                        111
Error Report levels
E_WARNING: Non-fatal run-time errors
E_NOTICE: Run-time notices
E_USER_ERROR: Fatal user-generated error
E_USER_WARNING: Non-fatal user-generated warning
E_USER_NOTICE: User-generated notice
E_RECOVERABLE_ERROR: Catchable fatal error
E_ALL: All errors and warnings, except level E_STRICT




                               www.opengurukul.com      112
Set Error Handler
Syntax
set_error_handler("customError");
Example
<?php function customError($errno, $errstr)          //error handler function

{
echo "<b>Error:</b> [$errno] $errstr";

}
set_error_handler("customError");                   //set error handler

echo($test);                                       //trigger error
?>

output: [8] Undefined variable: test
                                         www.opengurukul.com                    113
Trigger an Error
In a script where users can input data it is useful to trigger errors when an
   illegal input occurs.trigger_error() function is used for this.
Example
<?php
$test=2;

if ($test>1)
{

trigger_error("Value must be 1 or below");
}
?>

output: Notice: Value must be 1 or below
                                          www.opengurukul.com                   114
           in C:webfoldertest.php on line 6
Chapter 16




Exception Handling

      www.opengurukul.com   115
Exception Handling
Exceptions are used to change the normal flow of a script if a specified error
  occurs
We will show different error handling methods:
-Basic use of Exceptions
-Creating a custom exception handler
-Multiple exceptions
-Re-throwing an exception
-Setting a top level exception handler



                               www.opengurukul.com                          116
Basic Use of Exceptions
When an exception is thrown, the code following it will not be executed, and
  PHP will try to find the matching "catch" block.




If an exception is not caught, a fatal error will be issued with an "Uncaught
    Exception" message.




                               www.opengurukul.com                          117
Basic use of exception
                                              output:Fatal error: Uncaught exception
Example                                           'Exception'
<?php                                                 with message 'Value must be 1 or
                                                  below' in C:webfoldertest.php:6
function checkNum($number)
                                                      Stack trace: #0
{                                                 C:webfoldertest.php(12):
if($number>1)                                         checkNum(28) #1 {main} thrown in C:
                                                  webfoldertest.php on line 6
{

throw new Exception("Value must be 1 or
    below");
}

return true;
}
                                   www.opengurukul.com                                   118
checkNum(2);    ?>
Try, throw and catch
Try - A function using an exception should be in a "try" block.
If the exception does not trigger, the code will continue as normal. However
    if the exception triggers, an exception is "thrown"


Throw - This is how you trigger an exception. Each "throw" must have at
  least one "catch"


Catch - This block retrieves an exception and creates an object containing
  the exception information



                               www.opengurukul.com                        119
Try throw catch
Example                                       Try

<?php                                         {

function checkNum($number)                    checkNum(2);

{                                             echo 'If you see this, the number is 1 or
                                                 below';
if($number>1)
                                              }
{
                                              catch(Exception $e)
throw new Exception("Value must be 1 or
    below");                                  {

}                                             echo 'Message: ' .$e->getMessage();

return true;                                  }

}                                             ?>

                                   www.opengurukul.com Message: Value must be 1 or below
                                              output:                                  120
Chapter 17




 Filter

 www.opengurukul.com   121
Filters
PHP filters are used to validate and filter data coming from insecure
  sources, like user input.


To test, validate and filter user input or custom data is an important part of
  any web application.




                                www.opengurukul.com                              122
Use of filter
We should always filter all external data!
What is external data?
-Input data from a form
-Cookies
-Web services data
-Server variables
-Database query results




                               www.opengurukul.com   123
Functions and Filters
To filter a variable, use one of the following filter functions:
filter_var() - Filters a single variable with a specified filter
filter_var_array() - Filter several variables with the same or different filters
filter_input - Get one input variable and filter it
filter_input_array - Get several input variables and filter them with the
   same or different filters




                                 www.opengurukul.com                         124
filter_var()
Example of filters:we validate an integer using the filter_var() function:
$int = 123;
if(!filter_var($int, FILTER_VALIDATE_INT))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
?>                               www.opengurukul.com                         125
Validating and Sanitizing
Are used to validate user input            Are used to allow or disallow
                                             specified characters in a string



Strict format rules (like URL or E-
   Mail validating)                        No data format rules




Returns the expected type on
  success or FALSE on failure
                                           Always return the string


                                www.opengurukul.com                             126
Validate input
Example                                            else

<?php                                              {

if(!filter_has_var(INPUT_GET, "email"))            echo "E-Mail is valid";

{                                                  }

echo("Input type does not exist");                 }

}                                                  ?>

else                                               The example tells

{                                                  1. Check if an "email" input variable of the
                                                       "GET" type exist
if (!filter_input(INPUT_GET, "email",
     FILTER_VALIDATE_EMAIL))                       2. If the input variable exists, check if it is a
                                                        valid e-mail address
{

echo "E-Mail is not valid";             www.opengurukul.com                                            127

}
Sanitize Input
Example                                             The example tells

<?php                                               1. Check if the "url" input of the "POST" type
                                                        exists
if(!filter_has_var(INPUT_POST, "url"))
                                                    2. If the input variable exists, sanitize (take
{                                                        away invalid characters) and store it in the
                                                         $url variable
echo("Input type does not exist");

}
else

{
$url = filter_input(INPUT_POST, "url",
    FILTER_SANITIZE_URL);
}

?>                                       www.opengurukul.com                                      128
Chapter 18




PHP & MySQL

   www.opengurukul.com   129
Connecting to a Database
In PHP,mysql_connect() function is used to connect the database
Syntax
mysql_connect( servername, username ,password);
Example
<?php
$con = mysql_connect("localhost","root","root”);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
                                   www.opengurukul.com            130
?>
Closing a Connection
The connection will be closed automatically when the script ends.
To close the connection before, use the mysql_close() function:
Example
<?php
$con = mysql_connect("localhost","root","root”);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_close($con);
                                   www.opengurukul.com              131
?>
Creating Database
The CREATE DATABASE statement is used to create a database in
  MySQL.
Syntax
CREATE DATABASE database_name
To execute the statement query we must use the mysql_query() function




                            www.opengurukul.com                         132
Creating database
Example                                       if (mysql_query("CREATE DATABASE
                                                  my_db",$con))
<?php
                                              {
$con =
   mysql_connect("localhost","root","root     echo "Database created";
   ”);
                                              }
if (!$con)
                                              else
{
                                              {
die('Could not connect: ' . mysql_error());
                                              echo "Error creating database: " .
}                                                mysql_error();
                                              }
                                              mysql_close($con);
                                   www.opengurukul.com                             133
                                              ?>
Creating Table
The CREATE TABLE statement is used to create a table in MySQL.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,


)


                           www.opengurukul.com                   134
Creating table
Example                                           else

<?php                                             {

$con =                                            echo "Error creating database: " .
   mysql_connect("localhost","root","root”);         mysql_error();

if (!$con)                                        }

{                                                 mysql_select_db("my_db", $con);

die('Could not connect: ' . mysql_error());       $sql = "CREATE TABLE Persons

}                                                 (

if (mysql_query("CREATE DATABASE                  FirstName varchar(15),
     my_db",$con))
                                                  LastName varchar(15),
{
                                                  )";
echo "Database created";
                                                   mysql_query($sql,$con);
                                        www.opengurukul.com                            135
}
                                                  mysql_close($con);     ?>
Inserting data to DB
The INSERT INTO statement is used to add new records to a database
  table.
Syntax
INSERT INTO table_name
VALUES (value1, value2, value3,...)


INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)




                                www.opengurukul.com                  136
Insert Data From a Form Into a
              Database
Here is the HTML form:form.php
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
<input type="submit" />
</form>
</body>
</html>
                             www.opengurukul.com    137
continue
In insert.php                                      $sql="INSERT INTO Persons (FirstName,
                                                      LastName, Age)
<?php
                                                   VALUES
$con =
   mysql_connect("localhost","root","root”);       ('$_POST[firstname]','$_POST[lastname]','$_
                                                       POST[age]')";
if (!$con)
                                                   if (!mysql_query($sql,$con))
{
                                                   {
die('Could not connect: ' . mysql_error());
                                                   die('Error: ' . mysql_error());
}
                                                   }
mysql_select_db("my_db", $con);
                                                   echo "1 record added";
                                                   mysql_close($con)

                                                   ?>
                                        www.opengurukul.com                                 138
Select statement
It is used to select data from a                  mysql_select_db("my_db", $con);
    database.                                     $result = mysql_query("SELECT * FROM
                                                     Persons");
Syntax
                                                  while($row = mysql_fetch_array($result))
SELECT column_name(s) FROM
  table_name                                      {

                                                  echo $row['FirstName'] . " " .
Example                                              $row['LastName'];
<?php                                             echo "<br />";
$con =                                            }
   mysql_connect("localhost","root","root”);
                                                  mysql_close($con);
if (!$con)
                                                  ?>
{
die('Could not connect: ' . mysql_error());
                                       www.opengurukul.com                                   139
}
Update statement
It is used to update existing records            if (!$con)
    in a table.                                  {

Syntax                                           die('Could not connect: ' . mysql_error());

UPDATE table_name SET                            }
  column1=value,                                 mysql_select_db("my_db", $con);
  column2=value2,...
                                                 mysql_query("UPDATE Persons SET Age =
WHERE some_column=some_value                        '36'
                                                 WHERE FirstName = 'Peter' AND LastName
Example                                            = 'Griffin'");
<?php                                            mysql_close($con);
$con =                                           ?>
   mysql_connect("localhost","root","root”);

                                      www.opengurukul.com                                      140
Delete statement
The DELETE FROM statement is                     if (!$con)
  used to delete records from a                  {
  database table.
                                                 die('Could not connect: ' . mysql_error());
Syntax
                                                 }
DELETE FROM table_name                           mysql_select_db("my_db", $con);
  WHERE some_column =
  some_value                                     mysql_query("DELETE FROM Persons
                                                    WHERE LastName='Griffin'");
Example                                          mysql_close($con);
<?php                                            ?>
$con =
   mysql_connect("localhost","root","root”);


                                      www.opengurukul.com                                      141
Important functions
mysql_num_rows:Get number of rows in result


mysql_affected_rows:Get number of affected rows in previous
 MySQL operation


mysql_select_db:Select a MySQL database




                         www.opengurukul.com                  142
mysql_num_rows
Example
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rowsn";
?>



                             www.opengurukul.com                      143
mysql_affected_rows
Example
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

if (!$link) {
die('Could not connect: ' . mysql_error());

}
mysql_select_db('mydb');

mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %dn", mysql_affected_rows());
mysql_query('DELETE FROM mytable WHERE 0');

printf("Records deleted: %dn", mysql_affected_rows());
                                        www.opengurukul.com           144
?>
mysql_select_db
Example
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can't use foo : ' . mysql_error());
}
?>                                   www.opengurukul.com              145
Chapter 19




PHP & ODBC

   www.opengurukul.com   146
Create an ODBC Connection
Here is how to create an ODBC connection to a MS Access Database:
1.Open the Administrative Tools icon in your Control Panel.
2.Double-click on the Data Sources (ODBC) icon inside.
3. Choose the System DSN tab.
4.Click on Add in the System DSN tab.
5. Select the Microsoft Access Driver. Click Finish.
6. In the next screen, click Select to locate the database.
7.Give the database a Data Source Name (DSN).
8. Click OK.


                                   www.opengurukul.com              147
DSN On Linux:
To use MySQL via ODBC:
<?php
$db_host = "server.mynetwork";
$db_user = "dbuser";
$db_pass = "dbpass";
$dsn = "DRIVER={MySQL ODBC 3.51 Driver};" .
"CommLinks=tcpip(Host=$db_host);" .
"DatabaseName=$db_name;" .
"uid=$db_user; pwd=$db_pass";
odbc_connect($dsn, $db_user, $db_pass);
                            www.opengurukul.com   148
?>
Connecting to an ODBC
The odbc_connect() is used to connect to an ODBC data source.
It takes four parameters:
-data source name
-username
-password
-optional cursor type.
Example
The following example creates a connection to a DSN called northwind, with
  no username and no password.
$conn=odbc_connect('northwind','','');
                              www.opengurukul.com                       149
Executing SQL Statement:
              odbc_exec()
The odbc_exec() function is used to execute an SQL statement.
Example
example with no username and no password.
It then creates an SQL and executes it:
$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);




                              www.opengurukul.com               150
Retrieving Records
                  odbc_fetch_row()
This function is used to return records from the result-set.
The function takes two parameters:
- ODBC result identifier
- an optional row number
Example
odbc_fetch_row($rs)




                               www.opengurukul.com             151
Retrieving Fields from a Record:
            odbc_result()
This function is used to read fields from a record.
It takes two parameters:
-The ODBC result identifier
- a field number or name.
Example1
$compname=odbc_result($rs,1);
returns the value of the first field from the record:
Example2
$compname=odbc_result($rs,"CompanyName");
returns the value of a field called "CompanyName":
                                 www.opengurukul.com    152
Closing an ODBC Connection:
            odbc_close()
The odbc_close() function is used to close an ODBC connection.
Example
odbc_close($conn);




                            www.opengurukul.com                  153
Chapter 20



Object Oriented
 Programming

     www.opengurukul.com   154
classes
A class is user defined data type that contains attributes or data
   members; and methods which work on the data members.
Class structure
class <class-name>
{
<class body :- Data Members &amp; Methods>;
}




                              www.opengurukul.com                    155
Class example
class Customer                                       //customer is the class name

{

private $first_name, $last_name;      //$first_name/$last_name are attributes or data members.


public function setData($first_name, $last_name)     //setData is the method

{

$this->first_name = $first_name;

$this->last_name = $last_name;

}

public function printData()                          //printData is also the method

{

echo $this->first_name . " : " . $this->last_name;

}                                           www.opengurukul.com                                  156

}
The new instance
To create an instance of a class, the new keyword must be used.
An object will always be created when unless the object has a constructor defined
   that throws an exception on error.
Classes should be defined before instantiation
If a string containing the name of a class is used with new, a new instance of that
    class will be created.

Syntax
$instance = new Class();
Or we can write
   $className = 'Foo';
   $instance = new $className();
                                  www.opengurukul.com                                 157
Object assignment
Example
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null;                // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);

                               www.opengurukul.com                         158
Extends keyword
A class can inherit the methods and           }
   properties of another class by             $extended = new ExtendClass();
   using the keyword extends in the
   class declaration.                         $extended->displayVar();
                                              ?>
Example
                                              output:Extending class
<?php
                                                         a default value
class ExtendClass extends SimpleClass

{
function displayVar()

{
    echo "Extending classn";

     parent::displayVar();
                                   www.opengurukul.com                         159
}
Properties
Class member variables are called "properties"
They are defined public, protected, or private, followed by a normal
  variable declaration.
This declaration may include an initialization, but this initialization must be a
  constant value




                                www.opengurukul.com                            160
Properties
Example                                              // valid property declarations:

<?php                                                    public $var6 = myConstant;

class SimpleClass                                        public $var7 = array(true, false);

{                                                    // This is allowed only in PHP 5.3.0 and later.

    // invalid property declarations:                 public $var8 = <<<'EOD'

public $var1 = 'hello ' . 'world';                   hello world

public $var2 = <<<EOD                                EOD;

hello world                                          }

EOD;                                                 ?>

public $var3 = 1+2;

public $var4 = self::myStaticMethod();

public $var5 = $myVar;                    www.opengurukul.com                                          161
Class constants
Example
<?php
class MyClass

{
const constant = 'Any Testing Constant Value';

function showConstant() {
echo self::constant . "n";

}
}
echo MyClass::constant . "n";

?>
                                     www.opengurukul.com   162
output: Any Testing Constant Value
Constructor
Syntax                                         class SubClass extends BaseClass

void __construct ([ mixed $args [, $... ]] )    {

                                               function __construct()
Example
                                                {
<?php
                                               parent::__construct();
class BaseClass
                                               print "SubClass constructorn";
{
                                               }
function __construct()
                                               }
{
                                               $obj = new BaseClass();
print "BaseClass constructorn";
                                               $obj = new SubClass();
}
                                               ?>
}
                                    www.opengurukul.com
                                               Output: BaseClass constructor BaseClass 163
                                                    constructor SubClass constructor.
Destructor
Syntax                                        function __destruct()
                                               {
void __destruct ( void )
                                              print "Destroying " . $this->name . "n";
Example
                                              }
<?php
                                              }
class MyDestructableClass
                                              $obj = new MyDestructableClass();
{
                                              ?>
function __construct()
                                              Output
{
                                              In constructor Destroying
print "In constructorn";                         MyDestructableClass
$this->name = "MyDestructableClass";

}
                                   www.opengurukul.com                                    164
Object inheritance
Example                                          class bar extends foo

<?php                                            {

class foo                                        public function printItem($string)

{                                                {

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

{                                                }

echo 'Foo: ' . $string . PHP_EOL;                }

}                                                $foo = new foo(); $bar = new bar();

public function printPHP()                       $foo->printItem('baz'); // Output: 'Foo: baz'

{                                                $foo->printPHP(); // Output: 'PHP is great'

echo 'PHP is great.' . PHP_EOL;                  $bar->printItem('baz'); // Output: 'Bar: baz'

}                                               $bar->printPHP(); // Output: 'PHP is great' ?>
                                     www.opengurukul.com                                       165
}                                               output:Foo: baz PHP is great. Bar: baz PHP is
                                                     great.
Scope Resolution Operator (::)
It is a token that allows access to static, constant, and overridden properties or
     methods of a class.
The variable's value can not be a keyword (e.g. self, parent and static).

Example
<?php
class MyClass

{
const CONST_VALUE = 'Any constant value';

}
$classname = 'MyClass';

echo MyClass::CONST_VALUE; ?>
output:Any constant value         www.opengurukul.com                                166
Self and parent
Two special keywords self and parent              class OtherClass extends MyClass
  are used to access properties or                {
  methods from inside the class
  definition.                                     public static $my_static = 'static var';

                                                  public static function doubleColon()
Example
                                                  {
<?php
                                                  echo parent::CONST_VALUE . "<br>";
class MyClass
                                                  echo self::$my_static . "<br>";
{
                                                  }
const CONST_VALUE = 'Any constant value';
                                                  }
}
                                                  $classname = 'OtherClass';
$classname = 'MyClass';
                                                  OtherClass::doubleColon();

                                                 ?>
                                      www.opengurukul.com                                    167
                                                 Output: A constant value static var
Static keyword
Declaring class properties or methods as static makes them accessible without
  needing an instantiation of the class.
A property declared as static can not be accessed with an instantiated class object .
The variable's value can not be a keyword (e.g. self, parent and static).




                                  www.opengurukul.com                              168
Static keyword
Example                                                   }

<?                                                        public function getStaticData()

class ClassName                                           {

{                                                         echo ClassName::$staticvariable; //Accessing Static
                                                             Variable
static private $staticvariable; //Defining Static
     Variable                                             }

function __construct($value)                              }

{                                                         $a = new ClassName("12");

if($value != "")                                          $a = new ClassName("23");

{                                                         $a = new ClassName("");

ClassName::$staticvariable = $value; //Accessing          ?>
    Static Variable
                                                          Output:12
}
                                              www.opengurukul.com 23                                      169
$this->getStaticData();
                                                                  23
Abstract classes
It is not allowed to create an instance of a class that has been defined as abstract.
Syntax
<?

abstract class classname

{

//attributes and methods

abstract function methodname

}

class derived extends classname

{

     function methodname

}                                  www.opengurukul.com                                  170

?>
Abstract class
Example                                              class EmployeeData extends employee
                                                        //extending abstract class
<?
                                                 {
abstract class employee
                                                 function __construct($name,$age)
{
                                                 {
protected $empname;
                                                 $this->setdata($name,$age);
protected $empage;
                                                 }
function setdata($empname,$empage)
                                                 function outputData()
{
                                                 {
$this->empname = $empname;
                                                 echo $this->empname;
$this->empage = $empage;
                                                 echo $this->empage;
}
                                                 }
abstract function outputData();
                                     www.opengurukul.com EmployeeData("Hitesh","24");
                                                $a = new                                   171
}
                                                 $a->outputData(); ?> Output: Hitesh 24
Object interfaces
Interface is a object oriented concept,
It is the place where we can define the function.
Syntax
Interface interface_name
{

const 1;
const N;

function methodName1()
function methodNameN()

}


                                   www.opengurukul.com   172
Object interfaces
Example                                         function shimu()

<?php                                           {

interface shahu                                 print "<br />";

{                                               print self::lotu;

const lotu="lotu is lucky";                     }

public function rooja();                        }

}                                               $hanu=new hasu();

class hasu implements shahu                     $hanu->rooja();

{                                               $hanu ->shimu();

public function rooja()                         ?>

print "<br />";                                 output:lotu is lucky

print self::lotu; print "<br />";   www.opengurukul.comhai roja          173

print "hai roja"; }                                      lotu is lucky
Overloading
Overloading in PHP provides means to dynamically "create" properties and
  methods.
All overloading methods must be defined as public.
Two types of overloading are there
-Property overloading
-Method overloading




                                 www.opengurukul.com                       174
Property overloading
Example
void __set ( string $name , mixed $value )

mixed __get ( string $name )
bool __isset ( string $name )

void __unset ( string $name )
The $name argument is the name of the property being interacted with.
__set() is run when writing data to inaccessible properties.

__get() is utilized for reading data from inaccessible properties.
__isset() is triggered by calling isset() or empty() on inaccessible properties.

__unset() is invoked when unset() is used on inaccessible properties.


                                        www.opengurukul.com                        175
Method overloading
Example
mixed __call ( string $name , array $arguments )
mixed __callStatic ( string $name , array $arguments )
-$name argument is the name of the method being called.
-The $arguments argument is an enumerated array containing the parameters
   passed to the $name'ed method.
__call() is triggered when invoking inaccessible methods in an object context.


__callStatic() is triggered when invoking inaccessible methods in a static context.



                                  www.opengurukul.com                                 176
Object iteration
PHP 5 provides a way for objects to be                foreach($this as $key => $value)
  defined so it is possible to iterate through
                                                      {
  a list of items.
                                                      print "$key => $value<br>";
Example
                                                      }
<?php
                                                      }
class MyClass
                                                      }
{
                                                      $class = new MyClass();
public $var1 = 'value 1';
                                                      foreach($class as $key => $value)
public $var2 = 'value 2';
                                                       {
public $var3 = 'value 3';
                                                      print "$key => $value<br>";
protected $protected = 'protected var';
                                                      }
function iterateVisible()
                                                     echo "<br>";
{                                         www.opengurukul.com                             177
                                                     $class->iterateVisible(); ?>
echo "MyClass::iterateVisible:n";
Magic methods
There are so many functions which are      _wakeup
  magical in php
                                           _toString
_construct
                                           _invoke
_destruct
                                           _set_state
_call
                                           _clone
_callStatic
_get
_set
_isset
_unset
_sleep
                                www.opengurukul.com     178
__sleep and __wakeup
Serialize()
checks if your class has a function with the magic name __sleep,
If so, that function is executed prior to any serialization


Unserialize()
checks for the presence of a function with the magic name __wakeup
If present, this function can reconstruct any resources that the object may have.




                                    www.opengurukul.com                             179
__toString,__invoke,__set_state
__toString
The __toString method allows a class to decide how it will react when it is treated like
  a string.
__invoke
The __invoke method is called when a script tries to call an object as a function.
__set_state
This static method is called for classes exported by var_export() since PHP 5.1.0.




                                   www.opengurukul.com                               180
Final keyword
It prevents child classes from overriding a method by prefixing the definition with final.


If the class itself is being defined final then it cannot be extended.


Properties cannot be declared final, only classes and methods may be declared as
  final.




                                    www.opengurukul.com                                181
Final keyword
Example
<?php

final class BaseClass {

public function test() {

echo "BaseClass::test() calledn";

}

final public function moreTesting() // Here it doesn't matter if you specify the function as final or not

{

echo "BaseClass::moreTesting() calledn";

}

}

class ChildClass extends BaseClass {
                                             www.opengurukul.com                                            182
}// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass) ?>
Cloning object
it simply creates a copy of an object.        $so = new SmallObject;
Example                                       $so->field++;
$x = 1;                                       $soRef = $so;
$y =& $x;                                     $soClone = clone $so;
$x++;                                         $so->field++;
echo"$y $x<br>";                              echo $so->field;      // outputs: 2
class SmallObject                             echo $soRef->field;     // outputs: 2
{                                             echo $soClone->field; // outputs: 1
    public $field = 0;
}
                                   www.opengurukul.com                                183
Late static binding
It can be used to refer the called class.



The name late static binding is coined because of the static:: will no longer be
  resolved using the class where the method is defined.




                                   www.opengurukul.com                             184
Late static binding
Example                                                 class Two extends One {

                                                        public static function classIdentifier() {
<?php
                                                        echo __CLASS__;
class One {
                                                        }
public static function classIdentifier() {
                                                        }
echo __CLASS__;
                                                        Two::classtest();
}
                                                        ?>
public static function classtest() {
                                                        Output: One
self::classIdentifier();

}

}



                                             www.opengurukul.com                                     185
Objects and references
Example                                                 $d->foo = 2; // ($c,$d) = <id>

<?php                                                   echo $c->foo."n";

class A {                                               $e = new A;

    public $foo = 1;                                    function foo($obj) {

}                                                           // ($obj) = ($e) = <id>

$a = new A;                                                  $obj->foo = 2;

$b = $a; // $a and $b are copies of the same            }
    identifier
                                                        foo($e);
          // ($a) = ($b) = <id>
                                                        echo $e->foo."n";
$b->foo = 2;
                                                        ?>
echo $a->foo."n";
                                                        output:2
$c = new A;
                                                               2
$d = &$c;     // $c and $d are references   www.opengurukul.com                          186
                                                               2
Object serialization
Serialization in the context of storage and transmitting is the process of converting
   an object into a sequence of bits
so that it can persist in a storage medium and or transmitted across a network.
serializing and unserializing can be done by two functions They are:
-Serialize
-unserialize
serialize() returns a string containing a byte-stream representation of any value
unserialize() can use this string to recreate the original variable values.




                                   www.opengurukul.com                              187
Chapter 21




PHP Built-in Functions

        www.opengurukul.com   188
PHP Calendar Functions and
                constants
cal_days_in_month:It Return the number of days in a month for a given year and
   calendar.
Syntax:int cal_days_in_month ( int $calendar , int $month , int $year )
Parameters:calendar - Calendar to use for calculation
              month - Month in the selected calendar
              year - Year in the selected calendar
Example
<?php

$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003);

echo "There was $num days in August 2003";

?>
                                      www.opengurukul.com
Output -There was 31 days in August 2003                                         189
cal_info
It Returns information about a particular calendar.
Syntax:array cal_info ([ int $calendar = -1 ] )
Parameters:Calendar - Calendar to return information for. If no calendar is specified
   information about all calendars is returned.
Example:<?php
                 $info = cal_info(0);

              print_r($info);

            ?>

output:

Array ( [months] => Array ( [1] => January [2] => February [3] => March [4] => April [5] => May [6] =>
    June [7] => July [8] => August [9] => September [10] => October [11] => November [


                                         www.opengurukul.com                                        190
Many other calender function
cal_from_jd:It Converts from Julian Day Count to a supported calendar.
cal_to_jd:It Converts from a supported calendar to Julian Day Count.
FrenchToJD :It Converts a date from the French Republican Calendar to a
  Julian Day Count.
GregorianToJD:It Converts a Gregorian date to Julian Day Count.




                             www.opengurukul.com                         191
Date/time Functions and constants
Date function
The PHP date() function is used to format a time and/or date.
Syntax
date(format,timestamp) ;
Parameter
format - Required. Specifies the format of the timestamp
timestamp - Optional. Specifies a timestamp. Default is the current date and time.




                                 www.opengurukul.com                                 192
Directory Functions and constants
Chdir: It change the directory
Syntax: bool chdir ( string $directory )
Parameters: directory - The new current directory
Example:<?php
                // current directory

               echo getcwd() . "n";
               chdir('public_html');
               // current directory

               echo getcwd() . "n";
          ?>

output:/home/vincent
                                       www.opengurukul.com   193
      /home/vincent/public_html
chroot
It change the root directory
Syntax
bool chroot ( string $directory )
Parameters
directory - The path to change the root directory to.
Example
<?php

chroot("/path/to/your/chroot/");

echo getcwd();

?>

output: /
                                    www.opengurukul.com   194
getcwd
It gets the current working directory
Syntax: string getcwd ( void )
Example:<?php
              // current directory
              echo getcwd() . "n";

             chdir('cvs');
             // current directory

             echo getcwd() . "n";
        ?>

output:/home/matsya
      home/matsya/cvs
                                      www.opengurukul.com   195
Error Logging functions and
                 constants
debug_backtrace: It generates a                      a_test('friend');
  backtrace.                                                              include_once 'a.txt';

Syntax: array debug_backtrace ([ bool                              ?>
  $provide_object = true ] )
                                                   a.txt:friend is the best part of my life
Parameters                                         output:Hi: friendarray(1) { [0]=> array(4) { ["file"]=>
                                                      string(13) "/var/test.php" ["line"]=> int(10)
provide_object - Whether or not to                    ["function"]=> string(6) "a_test" ["args"]=>
   populate the "object" index.                       array(1) { [0]=> &string(6) "friend" } } } friend is
                                                      the best part of my life
Example: <?php
              function a_test($str)

              {

                   echo "nHi: $str";

              var_dump(debug_backtrace());

             }                          www.opengurukul.com                                            196
error_log
It send an error message somewhere
Syntax: bool error_log ( string $message [, int $message_type = 0 [, string $destination [,
   string $extra_headers ]]] )

Parameters
message - The error message that should be logged.
message_type - Says where the error should go.
Destination - The destination. Its meaning depends on the message_type parameter as
   described above.

extra_headers - The extra headers. It's used when the message_type parameter is set to 1.
Example:<?php

            error_log("You messed up!", 3, "/var/tmp/my-errors.log");
          ?>
                                      www.opengurukul.com                                     197
File System Functions and
                      constants
Basename
It returns trailing name component of path

Syntax
string basename ( string $path [, string $suffix ] )

Parameters
path - A path.

Suffix - If the name component ends in suffix this will also be cut off.

Example
<?php

echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL;

echo "2) ".basename("/etc/passwd").PHP_EOL;

?>                                            www.opengurukul.com          198

Output 1) sudoers 2) passwd
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP
OpenGurukul : Language : PHP

More Related Content

What's hot

Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on PythonSumit Raj
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021Ayesh Karunaratne
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting StartedKent Ohashi
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonYi-Lung Tsai
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityGeorgePeterBanyard
 
Pysmbc Python C Modules are Easy
Pysmbc Python C Modules are EasyPysmbc Python C Modules are Easy
Pysmbc Python C Modules are EasyRoberto Polli
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Pythonkwatch
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
Php and threads ZTS
Php and threads ZTSPhp and threads ZTS
Php and threads ZTSjulien pauli
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...it-people
 
Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for DummiesElizabeth Smith
 
The best of AltJava is Xtend
The best of AltJava is XtendThe best of AltJava is Xtend
The best of AltJava is Xtendtakezoe
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 

What's hot (20)

PHP - Web Development
PHP - Web DevelopmentPHP - Web Development
PHP - Web Development
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
MP in Clojure
MP in ClojureMP in Clojure
MP in Clojure
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting Started
 
06 Loops
06 Loops06 Loops
06 Loops
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded Python
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Pysmbc Python C Modules are Easy
Pysmbc Python C Modules are EasyPysmbc Python C Modules are Easy
Pysmbc Python C Modules are Easy
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
 
Python programming
Python  programmingPython  programming
Python programming
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Php and threads ZTS
Php and threads ZTSPhp and threads ZTS
Php and threads ZTS
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...
 
Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for Dummies
 
The best of AltJava is Xtend
The best of AltJava is XtendThe best of AltJava is Xtend
The best of AltJava is Xtend
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 

Viewers also liked

Webinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible SchemasWebinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible SchemasMongoDB
 
ADA programming language
ADA programming languageADA programming language
ADA programming languageAisha Kalsoom
 
امه لا تسمع قول الرب – اضاد المسيح –منافقون – خادعون دمويون – متأمرون -
امه لا تسمع قول الرب – اضاد المسيح –منافقون – خادعون  دمويون – متأمرون -امه لا تسمع قول الرب – اضاد المسيح –منافقون – خادعون  دمويون – متأمرون -
امه لا تسمع قول الرب – اضاد المسيح –منافقون – خادعون دمويون – متأمرون -Ibrahimia Church Ftriends
 
PeoplePRINT Sydstart pitch deck
PeoplePRINT Sydstart pitch deckPeoplePRINT Sydstart pitch deck
PeoplePRINT Sydstart pitch deckJohn Weichard
 
Inv pres q42013_-_final
Inv pres q42013_-_finalInv pres q42013_-_final
Inv pres q42013_-_finalCNOServices
 
The Digital Workplace in Cities
The Digital Workplace in CitiesThe Digital Workplace in Cities
The Digital Workplace in CitiesAngel Talamona
 
꾸뻬 씨의 행복여행
꾸뻬 씨의 행복여행꾸뻬 씨의 행복여행
꾸뻬 씨의 행복여행Ji Young Kim
 
Цифровой госпиталь 2020 (конференция ФизтехМед)
Цифровой госпиталь 2020 (конференция ФизтехМед)Цифровой госпиталь 2020 (конференция ФизтехМед)
Цифровой госпиталь 2020 (конференция ФизтехМед)Alexandre Prozoroff
 
CV EJJ Lemmens
CV EJJ LemmensCV EJJ Lemmens
CV EJJ Lemmensejjlemmens
 
Elisha man of miracles arabic رجل المعجزات اليشع
Elisha man of miracles arabic رجل المعجزات  اليشعElisha man of miracles arabic رجل المعجزات  اليشع
Elisha man of miracles arabic رجل المعجزات اليشعIbrahimia Church Ftriends
 
Scott Pechstein "How to Sell Used Cars To Your New Car Leads"
Scott Pechstein "How to Sell Used Cars To Your New Car Leads"Scott Pechstein "How to Sell Used Cars To Your New Car Leads"
Scott Pechstein "How to Sell Used Cars To Your New Car Leads"Sean Bradley
 
Citi -030613_presentation_-_final
Citi  -030613_presentation_-_finalCiti  -030613_presentation_-_final
Citi -030613_presentation_-_finalCNOServices
 
台灣漁船能否於該海域捕魚
台灣漁船能否於該海域捕魚台灣漁船能否於該海域捕魚
台灣漁船能否於該海域捕魚Po-Feng Lee
 

Viewers also liked (20)

Webinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible SchemasWebinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible Schemas
 
Plc (1)
Plc (1)Plc (1)
Plc (1)
 
ADA programming language
ADA programming languageADA programming language
ADA programming language
 
Programming Languages
Programming LanguagesProgramming Languages
Programming Languages
 
PHP
 PHP PHP
PHP
 
امه لا تسمع قول الرب – اضاد المسيح –منافقون – خادعون دمويون – متأمرون -
امه لا تسمع قول الرب – اضاد المسيح –منافقون – خادعون  دمويون – متأمرون -امه لا تسمع قول الرب – اضاد المسيح –منافقون – خادعون  دمويون – متأمرون -
امه لا تسمع قول الرب – اضاد المسيح –منافقون – خادعون دمويون – متأمرون -
 
Ciri-ciri Ikan Hiasan
Ciri-ciri Ikan HiasanCiri-ciri Ikan Hiasan
Ciri-ciri Ikan Hiasan
 
PeoplePRINT Sydstart pitch deck
PeoplePRINT Sydstart pitch deckPeoplePRINT Sydstart pitch deck
PeoplePRINT Sydstart pitch deck
 
Inv pres q42013_-_final
Inv pres q42013_-_finalInv pres q42013_-_final
Inv pres q42013_-_final
 
Pub 2014 L H MADKOUR
Pub 2014 L H MADKOURPub 2014 L H MADKOUR
Pub 2014 L H MADKOUR
 
The Digital Workplace in Cities
The Digital Workplace in CitiesThe Digital Workplace in Cities
The Digital Workplace in Cities
 
꾸뻬 씨의 행복여행
꾸뻬 씨의 행복여행꾸뻬 씨의 행복여행
꾸뻬 씨의 행복여행
 
Цифровой госпиталь 2020 (конференция ФизтехМед)
Цифровой госпиталь 2020 (конференция ФизтехМед)Цифровой госпиталь 2020 (конференция ФизтехМед)
Цифровой госпиталь 2020 (конференция ФизтехМед)
 
CV EJJ Lemmens
CV EJJ LemmensCV EJJ Lemmens
CV EJJ Lemmens
 
Elisha man of miracles arabic رجل المعجزات اليشع
Elisha man of miracles arabic رجل المعجزات  اليشعElisha man of miracles arabic رجل المعجزات  اليشع
Elisha man of miracles arabic رجل المعجزات اليشع
 
ظهورات الرب يسوع المسيح
ظهورات الرب يسوع المسيحظهورات الرب يسوع المسيح
ظهورات الرب يسوع المسيح
 
Idioms a
Idioms aIdioms a
Idioms a
 
Scott Pechstein "How to Sell Used Cars To Your New Car Leads"
Scott Pechstein "How to Sell Used Cars To Your New Car Leads"Scott Pechstein "How to Sell Used Cars To Your New Car Leads"
Scott Pechstein "How to Sell Used Cars To Your New Car Leads"
 
Citi -030613_presentation_-_final
Citi  -030613_presentation_-_finalCiti  -030613_presentation_-_final
Citi -030613_presentation_-_final
 
台灣漁船能否於該海域捕魚
台灣漁船能否於該海域捕魚台灣漁船能否於該海域捕魚
台灣漁船能否於該海域捕魚
 

Similar to OpenGurukul : Language : PHP (20)

PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
Php + my sql
Php + my sqlPhp + my sql
Php + my sql
 
Php
PhpPhp
Php
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
PHP Reviewer
PHP ReviewerPHP Reviewer
PHP Reviewer
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 

More from Open Gurukul

Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpen Gurukul
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpen Gurukul
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpen Gurukul
 
OpenGurukul : Operating System : Linux
OpenGurukul : Operating System : LinuxOpenGurukul : Operating System : Linux
OpenGurukul : Operating System : LinuxOpen Gurukul
 

More from Open Gurukul (6)

Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C Programming
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQL
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell Scripting
 
OpenGurukul : Operating System : Linux
OpenGurukul : Operating System : LinuxOpenGurukul : Operating System : Linux
OpenGurukul : Operating System : Linux
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

OpenGurukul : Language : PHP

  • 1. PHP By OpenGurukul Team www.opengurukul.com
  • 2. Chapter 1 Introduction to php www.opengurukul.com 2
  • 3. Introduction to web application What is Web Application? Components of Web Application -Presentation -Processing Uses of PhP - Server Side Scripting - Command Line Scripting www.opengurukul.com 3 - Writing Desktop Applications
  • 4. Introduction to PHP Basic PHP Syntax <?php ?> Example of php program <html><body> <?php echo “Hello world”; ?> </body></html> Comments in php <html><body> <?php //This is a comment /*This is a comment block */?> www.opengurukul.com 4 </body></html>
  • 5. Chapter 2 Php data types www.opengurukul.com 5
  • 6. Php data Types A data type refers to the type of data a variable can store. 8 different type of data types are: integer numbers floating point numbers strings booleans arrays objects resouces www.opengurukul.com 6 null
  • 7. Integers An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}. 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) ?> Integer Data type can be divided into two types – Octal, Hexadecimal, Decimal www.opengurukul.com 7
  • 8. Floating point numbers Floating point numbers are those data types which can store decimal values Example <?php $a = 1.234; $b = 1.2e3; $c = 7E-10; ?> www.opengurukul.com 8
  • 9. Strings A string is series of characters. Example <?php $str=”Hello world”; echo $str; ?> Output: Hello World www.opengurukul.com 9
  • 10. Booleans This variable must be true or false Example <? php $foo = True; // assign the value TRUE to $foo ?> www.opengurukul.com 10
  • 11. Arrays An array is a variable that holds a group of values. Referencing array elements is done like this: Example $arrayName[index]; assign a value to an array position: $listing[0] = "first item"; $listing[1] = "second item"; $listing[2] = "third item"; www.opengurukul.com 11
  • 12. Object An object is a data type that allows echo "This is example of object data for the storage of not only data type."; but also information on how to process that data. } Example: } <?php $bar = new foo; class foo $bar->do_foo(); { ?> function do_foo() Output :This is example of object data type. { www.opengurukul.com 12
  • 13. Resources and Null Resources Resources are really integers under the surface. Their main benefit is that they're garbage collected when no longer in use. When the last reference to a resource value goes away, the extension that created the resource is called to free any memory, close any connection, etc. for that resource: Null The NULL value represents a variable that has no value <?php $var = NULL; ?> www.opengurukul.com 13
  • 14. Type Casting PHP will automatically convert data types as necessary across the board Example <?php $mystring = "wombat"; $myinteger = (integer)$mystring ?> At first, $mystring contains a string. However, we type cast it to be an integer, so PHP will convert it to an integer, and place the result into $myinteger www.opengurukul.com 14
  • 15. Type juggling if we add two integer variables then the result is integer type but if we add one integer and one float type variable then the result is float type because float type has a higher precedence than integer. Example <?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) www.opengurukul.com 15 ?>
  • 16. Chapter 3 Variables www.opengurukul.com 16
  • 17. variables Variables are used for storing values When a variable is declared, it can be used over and over again in your script. All variables in PHP start with a $ sign symbol. The variable name is case-sensitive. Ex-$var_name = value; www.opengurukul.com 17
  • 18. PHP-loosely typed language Example <?php $txt="Hello World!"; $x=16; ?> a variable does not need to be declared before adding a value to it. It automatically converts the variable to the correct data type, depending on its value. www.opengurukul.com 18
  • 19. Variable scope Example <?php $a=1; /* global scope*/ function test() { echo $a; } /* reference to local scope variable*/} test(); ?> output:It will not produce any output www.opengurukul.com 19
  • 20. Global keyword Example<?php $a=1; $b=2; function sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; www.opengurukul.com 20 ?> output: 3
  • 21. Variables variables Example <?php $a=”hello”; $$a=”world”; echo "$a ${$a}"; ?> Here $a is hello then $hello is world so final out put is hello world www.opengurukul.com 21
  • 22. Chapter 4 Constants And Expressions www.opengurukul.com 22
  • 23. Constants Constants just as variables are used to store information. difference between constants and variables is that constant value can not be changed in the process of running program. A constant is case-sensitive by default define a constant by using the define()-function or the const keyword outside a class definition. www.opengurukul.com 23
  • 24. Define function Example <?php define("PASSWORD","admin"); // first we define a constant PASSWORD echo (PASSWORD); // will display value of PASSWORD constant, i.e. admin echo constant("PASSWORD"); // will also display admin echo "PASSWORD"; // will display PASSWORD ?> www.opengurukul.com 24
  • 25. Const keyword Example <?php const CONSTANT = 'Hello World'; // Works as of PHP 5.3.0 echo CONSTANT; ?> www.opengurukul.com 25
  • 26. Magic Constants PHP provides a large number of predefined constants to any script which it runs. __LINE__:The current line number of the file __FILE__:The full path and filename of the file __DIR__:The directory of the file __FUNCTION__:The function name(case-sensitive) __CLASS__:The class name(case-sensitive) __METHOD__:The class method name(case-sensitive) __NAMESPACE__:The name of the current namespace (case-sensitive) www.opengurukul.com 26
  • 27. Expressions Example $a = “5" you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant). After this assignment, you'd expect $a's value to be 5 as well. So if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words. $a is an expression with the value of 5 as well. www.opengurukul.com 27
  • 28. Chapter 5 Operators www.opengurukul.com 28
  • 29. Operators Operators are used to operate on values. Different types of operators we are using in php. i.Arithmetic Operators ii.Assignment Operators iii.Comparison Operators iv.Logical Operators www.opengurukul.com 29
  • 30. Arithmetic Operators Operator Description Example Result + Addition x=2,x+2 4 - Subtraction x=2,5-x 3 * Multiplication x=4 20 x*5 / Division 15/5 3 5/2 2.5 % Modulus (division 5%2 1 remainder) 10%8 2 10%2 0 ++ Increment x=5 x=6 x++ -- Decrement x=5 x=4 x-- www.opengurukul.com 30
  • 31. Assignment Operators Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y .= x.=y x=x.y %= x%=y x=x%y www.opengurukul.com 31
  • 32. Comparision Operators Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true <> is not equal 5<>8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or 5>=8 returns equal to false <= is less than or 5<=8 returns true equal to www.opengurukul.com 32
  • 33. Logical Operators Operator Description Example && and x=6 y=3 (x < 10 && y > 1) returns true || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 !(x==y) returns true www.opengurukul.com 33
  • 34. Operator precedence Example 1 + 5 * 3=16 and not 18 because ("*") operator has a higher precedence than the ("+") operator Parentheses may be used to force precedence, if necessary. (1 + 5) * 3=18 If operator precedence is equal, left to right associativity is used. www.opengurukul.com 34
  • 35. Chapter 6 Control Structure www.opengurukul.com 35
  • 36. Conditional Statements Conditional statements are used to perform different actions based on different conditions. PhP have the following conditional statements if statement if else statement if elseif else statement switch statement www.opengurukul.com 36
  • 37. If statement Syntax Example if (condition) <?php code to be executed if condition is true; $a=2; if($a==2) else echo “It is two”; code to be executed if condition is false; ?> output::It is two www.opengurukul.com 37
  • 38. If else Statement Syntax Example <?php if (condition) $a=2; code to be executed if condition is true; $b=3; if($b>$a) else { code to be executed if condition is echo “b is greater”; false; } else { echo “a is greater”; } www.opengurukul.com 38 ?> output::b is greater
  • 39. The if...else if....else Statement Use the if....elseif...else statement to select one of several blocks of code to be executed. Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; www.opengurukul.com 39
  • 40. if..else if..else statement Example elseif ($a == $b) <?php { $a=3; echo "a is equal to b"; $b=4; } if ($a > $b) else { { echo "a is bigger than b"; echo "a is smaller than b"; } } ?> output: a is smaller than b www.opengurukul.com 40
  • 41. Switch statement Use the switch statement to select one of many blocks of code to be executed. Syntax switch (n){ case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: www.opengurukul.com 41 code to be executed if n is different from both label1 and label2;}
  • 42. Switch statement Example case 3: <?php echo "Number 3"; $x=1; break; switch ($x) default: { echo "No number between 1 and 3"; case 1: } echo "Number 1"; ?> break; output:Number 1 case 2: echo "Number 2"; break; www.opengurukul.com 42
  • 43. looping A loop is simply a block of code that executes multiple times. The following loops are available in php - while statement - do while statement - for statement - foreach statement www.opengurukul.com 43
  • 44. The while loop This loop executes a block of code Example while a condition is true. <?php Syntax $i=1; while (condition) while($i<=5) { { code to be executed; echo $i; } $i++; } ?> output:12345 www.opengurukul.com 44
  • 45. The do...while Statement The loop will always execute the block of Example code once,then check the condition, and repeat the loop while the <?php condition is true. $i=1; Syntax do do { { code to be executed; $i++; } echo $i; while (condition); } while ($i<=5); ?> www.opengurukul.com 45 output:123456
  • 46. The for statement The loop is used when you know in Example advance how many times the <?php script should run. for ($i=1; $i<=5; $i++) Syntax { for (init; condition; increment) echo $i ; { code to be executed; } } ?> output:12345 www.opengurukul.com 46
  • 47. The foreach Loop The foreach loop is used to loop through arrays. Syntax foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value. www.opengurukul.com 47
  • 48. Chapter 7 Array www.opengurukul.com 48
  • 49. Array Array is a special type of variable which stores similar types of data. There are 3 types of array Numeric array:An array with a numeric index Associative array:An array where each ID key is associated with a value Multidimensional array:An array containing one or more arrays www.opengurukul.com 49
  • 50. Numeric Arrays There are two methods to create a numeric array. i.In the following example the index are automatically assigned (the index starts at 0): Ex-$cars=array("Saab","Volvo","BMW","Toyota"); ii.In the following example we assign the index manually: $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; www.opengurukul.com 50
  • 51. Associative Arrays Example1 In this example we use an array to assign ages to the different persons $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); Example2 $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; www.opengurukul.com 51
  • 52. Multidimensional Arrays Example <?php $families = array( "Griffin"=>array ("Peter","Lois","Megan" ), "Quagmire"=>array("Glenn" ), "Brown"=>array ("Cleveland", "Loretta", "Junior" )); ?> Output Array([Griffin] => Array([0] => Peter [1] => Lois [2] => Megan) [Quagmire] => Array([0] => Glenn ) [Brown] => Array([0] => Cleveland [1] => Loretta [2] => Junior )) www.opengurukul.com 52
  • 53. Array Functions List() The list() function is used to assign values to a list of variables in one operation. Syntax list(var1,var2...) Example <?php $my_array = array("Dog","Cat","Horse"); list($a, $b, $c) = $my_array; echo "I have several animals, a $a, a $b and a $c."; ?> output:I have several animals, a Dog, a Cat and a Horse. www.opengurukul.com 53
  • 54. count() The count() function counts the elements of an array, or the properties of an object. Syntax count(array,mode) Example <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); $result = count($people); echo $result; ?> output: 4 www.opengurukul.com 54
  • 55. array_sum() The array_sum() function returns the sum of all the values in the array. Syntax array_sum(array) Example <?php $a=array(0=>"5",1=>"15",2=>"25"); echo array_sum($a); ?> output: 45 www.opengurukul.com 55
  • 56. Many other functions are there array_pop() - Pop the element off the end of array array_push - Push one or more elements onto the end of array sort - Sort an array asort - Sort an array and maintain index association arsort - Sort an array in reverse order and maintain index association ksort - Sort an array by key krsort - Sort an array by key in reverse order print_r - Display all the readable information about the array www.opengurukul.com 56
  • 57. Chapter 8 PHP Forms and User Inputs www.opengurukul.com 57
  • 58. Html form example Example The example below contains an HTML form with two input fields and a submit button: html_form.php <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> www.opengurukul.com 58 </html>
  • 59. Collecting data from a form When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "welcome.php": "welcome.php" looks like this: File: welcome.php <html><body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body></html> ouput: Welcome John! You are 28 years old. www.opengurukul.com 59
  • 60. Php $_GET function It is used to collect values from a form. Information sent from a form is visible to everyone (it will be displayed in the browser's address bar) Not fit for sending passwords or other sensitive information! Not suitable for very large variable values.(not exceeding 2000 characters) www.opengurukul.com 60
  • 61. $_GET function Example <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> URL looks like this: http://www.w3schools.com/welcome.php?fname=Peter&age=37 In welcome.php Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! www.opengurukul.com 61
  • 62. Php $_POST function It is also used to collect values from a form. Information sent from a form is invisible to others and has no limits on the amount of information to send. here is an 8 Mb max size for the POST method, by default . Size can be changed by setting the post_max_size in the php.ini file. It is fit for the password or any other sensitive information www.opengurukul.com 62
  • 63. $_POST function Example <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> The URL will look like this: http://www.w3schools.com/welcome.php In welcome.php Welcome <?php echo $_POST["fname"]; ?>!<br /> www.opengurukul.com You are <?php echo $_POST["age"]; ?> years old. 63
  • 64. Php $_REQUEST function This function contains the contents of both $_GET, $_POST, and $_COOKIE. It can be used to collect form data sent with both the GET and POST methods. Example Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old. www.opengurukul.com 64
  • 65. Chapter 9 String Handling www.opengurukul.com 65
  • 66. String Variables A string variable is used to store and manipulate text. Example <?php $txt="Hello World"; echo $txt; ?> output: Hello World www.opengurukul.com 66
  • 67. String Literal Syntax A string literal can be specified in four different ways: single quoted double quoted heredoc syntax Example of single quoted: <?php $str='Hello World'; ?> www.opengurukul.com 67
  • 68. Example of double quote <?php $str=”hello world”; ?> Example of heredoc Heredoc is a robust way to create string in PHP with more lines but without using quotations. <?php $str = <<<DEMO This is a demo message with heredoc. DEMO; echo $str; ?> output: This is a demo message with heredoc. www.opengurukul.com 68
  • 69. The concatenation operator The concatenation operator (.) is used to put two string values together. Example <?php $txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?> output: Hello World! What a nice day! www.opengurukul.com 69
  • 70. String Function Strlen() The strlen() function is used to return the length of a string. Syntax int strlen ( string $string ) Example <?php $str = 'abcdef'; echo strlen($str); // 6 $str = ' ab cd '; echo strlen($str); // 7 www.opengurukul.com 70 ?>
  • 71. str_replace() It replaces some characters with some other characters in a string. Syntax str_replace(find,replace,string,count) Example <?php $arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo "Replacements: $i"; ?> output:Array([0] => blue [1] => pink [2] => green [3] => yellow) Replacements: 1 www.opengurukul.com 71
  • 72. strrev() The strrev() function reverses a string. Syntax strrev(string) Example <?php echo strrev("Hello World!"); ?> output : !dlroW olleH www.opengurukul.com 72
  • 73. Strrpos() The strrpos() function finds the position of the last occurrence of a string inside another string. Syntax strrpos(string,find,start) Example <?php echo strrpos("Hello world!","wo"); ?> output: 6 www.opengurukul.com 73
  • 74. Explode() The explode() function breaks a string into an array. Syntax explode(separator,string,limit) Example <?php $str = "Hello world. It's a beautiful day."; print_r (explode(" ",$str)); ?> output: Array([0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day.) www.opengurukul.com 74
  • 76. Function A function is a block of code that performs a specific task. It has a name and it is reusable. There are two types of functions -Built-in functions -User defined functions www.opengurukul.com 76
  • 77. User defined function Functions those are defined by user Example according to user requirements. <?php Syntax function writeName() function functionName() { { echo "Kai Jim Refsnes"; code to be executed; } } echo "My name is "; writeName(); ?> output: My name is Kai Jim Refsnes www.opengurukul.com 77
  • 78. Function Arguments Information may be passed to echo "My sister's name is "; functions via the argument list, writeName("Hege"); which is a comma-delimited list of expressions. ?> output:My name is Kai Jim Refsnes. Example My sister's name is Hege Refsnes. <?php function writeName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeName("Kai Jim"); www.opengurukul.com 78
  • 79. Pass by value vs. Pass by reference Ex-pass by value Ex-pass by reference <?php <?php function pass_by_value($param) function_by_reference(&$param) { { push_array($param, 4, 5); push_array($param, 4, 5); } } $ar = array(1,2,3); $ar = array(1,2,3); pass_by_value($ar); pass_by_reference($ar); foreach ($ar as $elem) foreach ($ar as $elem) { { print "<br>$elem"; print "<br>$elem"; } } www.opengurukul.com 79 ?> output:1, 2, 3 ?> output: 1, 2, 3, 4, 5.
  • 80. Return values To let a function return a value, use the return statement . Example <?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?> ouput:1 + 16 = 17 www.opengurukul.com 80
  • 81. Built-in function Date() The PHP date() function is used to format a time and/or date. Syntax date(format,timestamp) Example <?php echo date("Y/m/d") . "<br />"; echo date("Y.m.d") . "<br />"; echo date("Y-m-d"); ?> output:2009/05/11 2009.05.11 2009-05-11 www.opengurukul.com 81
  • 82. mktime() The mktime() function returns the Unix timestamp for a date. Syntax mktime(hour,minute,second,month,day,year,is_dst) Example <?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?> output:Tomorrow is 2009/05/12 www.opengurukul.com 82
  • 83. include() You can insert the content of one PHP file into another PHP file before the server executes it Example <html> <body> <?php include("header.php"); ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html> www.opengurukul.com 83
  • 84. Require() It is identical as the include function Example() <?php require("wrongFile.php"); echo "Hello World!"; ?> www.opengurukul.com 84
  • 85. Include vs Require Include Require Generates warning if file not found Gives fatal error if file not found Script will continue execution Script will stop www.opengurukul.com 85
  • 86. require_once() & include_once() include_once() and require_once() function is used to include a file only once in a page. Example <?php require_once(“header.php"); include_once(“header.php"); ?> www.opengurukul.com 86
  • 88. cookie A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. It is used for an origin website to send state information to a user's browser and for the browser to return the state information to the origin site www.opengurukul.com 88
  • 89. Creating Cookie The setcookie() function is used to set a cookie. Syntax setcookie(name, value, expire, path, domain); Example <?php setcookie("user", "Alex Porter", time()+3600); ?> www.opengurukul.com 89
  • 90. Retrieving Cookie Value The PHP $_COOKIE variable is used to retrieve a cookie value. Example <?php echo $_COOKIE["user"]; // Print a cookie print_r($_COOKIE); // A way to view all cookies ?> www.opengurukul.com 90
  • 91. Deliting cookie When deleting a cookie you should assure that the expiration date is in the past. Example <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?> www.opengurukul.com 91
  • 93. Sessions A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. www.opengurukul.com 93
  • 94. Starting a PHP Session Before you can store user information in your PHP session, you must first start up the session. Session_start() is used to start a session Example <?php session_start(); ?> <html> <body> </body> </html> www.opengurukul.com 94
  • 95. Storing a Session Variable Example <?php session_start(); $_SESSION['user']=”Ram”; echo $_SESSION['user']; ?> output:Ram www.opengurukul.com 95
  • 96. Destroying a Session Unset() and session_destroy() are used to delete the session unset():It is used to free the specified session variable: Example of unset() <?php unset($_SESSION['views']); ?> session_destroy():is used to compltetly destroy the session Example of session_destroy() <?php session_destroy(); www.opengurukul.com 96 ?>
  • 97. Chapter 13 File Handling www.opengurukul.com 97
  • 98. File open Fopen() is used to open a file first parameter shows file name and the second parameter shows mode of the file Example <?php $file=fopen("welcome.txt","r"); ?> www.opengurukul.com 98
  • 99. Closing a File The fclose() function is used to close an open file: Example <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?> www.opengurukul.com 99
  • 100. Check End-of-file The feof() function checks if the "end-of-file" (EOF) has been reached. Example <?php if (feof($file)) echo "End of file"; ?> www.opengurukul.com 100
  • 101. File Reading - 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); ?> www.opengurukul.com 101
  • 102. File Reading - Character by Character 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); ?> www.opengurukul.com 102
  • 103. 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" /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> www.opengurukul.com 103
  • 104. Create The Upload Script Example else <?php { if ($_FILES["file"]["error"] > 0) echo "Upload: " . $_FILES["file"]["name"] . "<br />"; { echo "Type: " . $_FILES["file"]["type"] . echo "Error: " . $_FILES["file"]["error"] . "<br />"; "<br />"; echo "Size: " . ($_FILES["file"]["size"] / } 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"] ["tmp_name"]; } ?> www.opengurukul.com 104
  • 105. Restrictions on Upload Example echo "Upload: " . $_FILES["file"]["name"] . "<br />"; <?php echo "Type: " . $_FILES["file"]["type"] . "<br if ((($_FILES["file"]["type"] == "image/gif") || />"; ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) echo "Size: " . ($_FILES["file"]["size"] / && ($_FILES["file"]["size"] < 20000)) 1024) . " Kb<br />"; { echo "Stored in: " . $_FILES["file"] ["tmp_name"]; if ($_FILES["file"]["error"] > 0) } { }else echo "Error: " . $_FILES["file"]["error"] . "<br />"; { }else echo "Invalid file"; { } www.opengurukul.com 105 ?>
  • 106. Chapter 14 Sending Email www.opengurukul.com 106
  • 107. Sending Email using mail() The PHP mail() function is used to Example send emails from inside a script. <?php Syntax $to = "someone@example.com"; mail(to,subject,message,headers,pa $subject = "Test mail"; rameters) $message = "Hello! This is a simple email message."; $from = "someonelse@example.com"; $headers = "From: $from"; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?> www.opengurukul.com 107
  • 108. Chapter 15 Error Handling www.opengurukul.com 108
  • 109. Default & Other Methods The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser. different error handling methods: -Simple "die()" statements -Custom errors and error triggers -reporting www.opengurukul.com 109
  • 110. Basic Error Handling: Using the die() function Example <?php if(!file_exists("welcome.txt")) { die("File not found"); } Else { $file=fopen("welcome.txt","r"); } ?> Now if the file does not exist you get an error like this: File not found www.opengurukul.com 110
  • 111. Creating a Custom Error Handler This function must be able to handle a minimum of two parameters i.e (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context): Syntax error_function(error_level,error_message, error_file,error_line,error_context) www.opengurukul.com 111
  • 112. Error Report levels E_WARNING: Non-fatal run-time errors E_NOTICE: Run-time notices E_USER_ERROR: Fatal user-generated error E_USER_WARNING: Non-fatal user-generated warning E_USER_NOTICE: User-generated notice E_RECOVERABLE_ERROR: Catchable fatal error E_ALL: All errors and warnings, except level E_STRICT www.opengurukul.com 112
  • 113. Set Error Handler Syntax set_error_handler("customError"); Example <?php function customError($errno, $errstr) //error handler function { echo "<b>Error:</b> [$errno] $errstr"; } set_error_handler("customError"); //set error handler echo($test); //trigger error ?> output: [8] Undefined variable: test www.opengurukul.com 113
  • 114. Trigger an Error In a script where users can input data it is useful to trigger errors when an illegal input occurs.trigger_error() function is used for this. Example <?php $test=2; if ($test>1) { trigger_error("Value must be 1 or below"); } ?> output: Notice: Value must be 1 or below www.opengurukul.com 114 in C:webfoldertest.php on line 6
  • 115. Chapter 16 Exception Handling www.opengurukul.com 115
  • 116. Exception Handling Exceptions are used to change the normal flow of a script if a specified error occurs We will show different error handling methods: -Basic use of Exceptions -Creating a custom exception handler -Multiple exceptions -Re-throwing an exception -Setting a top level exception handler www.opengurukul.com 116
  • 117. Basic Use of Exceptions When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. www.opengurukul.com 117
  • 118. Basic use of exception output:Fatal error: Uncaught exception Example 'Exception' <?php with message 'Value must be 1 or below' in C:webfoldertest.php:6 function checkNum($number) Stack trace: #0 { C:webfoldertest.php(12): if($number>1) checkNum(28) #1 {main} thrown in C: webfoldertest.php on line 6 { throw new Exception("Value must be 1 or below"); } return true; } www.opengurukul.com 118 checkNum(2); ?>
  • 119. Try, throw and catch Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown" Throw - This is how you trigger an exception. Each "throw" must have at least one "catch" Catch - This block retrieves an exception and creates an object containing the exception information www.opengurukul.com 119
  • 120. Try throw catch Example Try <?php { function checkNum($number) checkNum(2); { echo 'If you see this, the number is 1 or below'; if($number>1) } { catch(Exception $e) throw new Exception("Value must be 1 or below"); { } echo 'Message: ' .$e->getMessage(); return true; } } ?> www.opengurukul.com Message: Value must be 1 or below output: 120
  • 121. Chapter 17 Filter www.opengurukul.com 121
  • 122. Filters PHP filters are used to validate and filter data coming from insecure sources, like user input. To test, validate and filter user input or custom data is an important part of any web application. www.opengurukul.com 122
  • 123. Use of filter We should always filter all external data! What is external data? -Input data from a form -Cookies -Web services data -Server variables -Database query results www.opengurukul.com 123
  • 124. Functions and Filters To filter a variable, use one of the following filter functions: filter_var() - Filters a single variable with a specified filter filter_var_array() - Filter several variables with the same or different filters filter_input - Get one input variable and filter it filter_input_array - Get several input variables and filter them with the same or different filters www.opengurukul.com 124
  • 125. filter_var() Example of filters:we validate an integer using the filter_var() function: $int = 123; if(!filter_var($int, FILTER_VALIDATE_INT)) { echo("Integer is not valid"); } else { echo("Integer is valid"); } ?> www.opengurukul.com 125
  • 126. Validating and Sanitizing Are used to validate user input Are used to allow or disallow specified characters in a string Strict format rules (like URL or E- Mail validating) No data format rules Returns the expected type on success or FALSE on failure Always return the string www.opengurukul.com 126
  • 127. Validate input Example else <?php { if(!filter_has_var(INPUT_GET, "email")) echo "E-Mail is valid"; { } echo("Input type does not exist"); } } ?> else The example tells { 1. Check if an "email" input variable of the "GET" type exist if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) 2. If the input variable exists, check if it is a valid e-mail address { echo "E-Mail is not valid"; www.opengurukul.com 127 }
  • 128. Sanitize Input Example The example tells <?php 1. Check if the "url" input of the "POST" type exists if(!filter_has_var(INPUT_POST, "url")) 2. If the input variable exists, sanitize (take { away invalid characters) and store it in the $url variable echo("Input type does not exist"); } else { $url = filter_input(INPUT_POST, "url", FILTER_SANITIZE_URL); } ?> www.opengurukul.com 128
  • 129. Chapter 18 PHP & MySQL www.opengurukul.com 129
  • 130. Connecting to a Database In PHP,mysql_connect() function is used to connect the database Syntax mysql_connect( servername, username ,password); Example <?php $con = mysql_connect("localhost","root","root”); if (!$con) { die('Could not connect: ' . mysql_error()); } www.opengurukul.com 130 ?>
  • 131. Closing a Connection The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function: Example <?php $con = mysql_connect("localhost","root","root”); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_close($con); www.opengurukul.com 131 ?>
  • 132. Creating Database The CREATE DATABASE statement is used to create a database in MySQL. Syntax CREATE DATABASE database_name To execute the statement query we must use the mysql_query() function www.opengurukul.com 132
  • 133. Creating database Example if (mysql_query("CREATE DATABASE my_db",$con)) <?php { $con = mysql_connect("localhost","root","root echo "Database created"; ”); } if (!$con) else { { die('Could not connect: ' . mysql_error()); echo "Error creating database: " . } mysql_error(); } mysql_close($con); www.opengurukul.com 133 ?>
  • 134. Creating Table The CREATE TABLE statement is used to create a table in MySQL. Syntax CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, ) www.opengurukul.com 134
  • 135. Creating table Example else <?php { $con = echo "Error creating database: " . mysql_connect("localhost","root","root”); mysql_error(); if (!$con) } { mysql_select_db("my_db", $con); die('Could not connect: ' . mysql_error()); $sql = "CREATE TABLE Persons } ( if (mysql_query("CREATE DATABASE FirstName varchar(15), my_db",$con)) LastName varchar(15), { )"; echo "Database created"; mysql_query($sql,$con); www.opengurukul.com 135 } mysql_close($con); ?>
  • 136. Inserting data to DB The INSERT INTO statement is used to add new records to a database table. Syntax INSERT INTO table_name VALUES (value1, value2, value3,...) INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) www.opengurukul.com 136
  • 137. Insert Data From a Form Into a Database Here is the HTML form:form.php <html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> <input type="submit" /> </form> </body> </html> www.opengurukul.com 137
  • 138. continue In insert.php $sql="INSERT INTO Persons (FirstName, LastName, Age) <?php VALUES $con = mysql_connect("localhost","root","root”); ('$_POST[firstname]','$_POST[lastname]','$_ POST[age]')"; if (!$con) if (!mysql_query($sql,$con)) { { die('Could not connect: ' . mysql_error()); die('Error: ' . mysql_error()); } } mysql_select_db("my_db", $con); echo "1 record added"; mysql_close($con) ?> www.opengurukul.com 138
  • 139. Select statement It is used to select data from a mysql_select_db("my_db", $con); database. $result = mysql_query("SELECT * FROM Persons"); Syntax while($row = mysql_fetch_array($result)) SELECT column_name(s) FROM table_name { echo $row['FirstName'] . " " . Example $row['LastName']; <?php echo "<br />"; $con = } mysql_connect("localhost","root","root”); mysql_close($con); if (!$con) ?> { die('Could not connect: ' . mysql_error()); www.opengurukul.com 139 }
  • 140. Update statement It is used to update existing records if (!$con) in a table. { Syntax die('Could not connect: ' . mysql_error()); UPDATE table_name SET } column1=value, mysql_select_db("my_db", $con); column2=value2,... mysql_query("UPDATE Persons SET Age = WHERE some_column=some_value '36' WHERE FirstName = 'Peter' AND LastName Example = 'Griffin'"); <?php mysql_close($con); $con = ?> mysql_connect("localhost","root","root”); www.opengurukul.com 140
  • 141. Delete statement The DELETE FROM statement is if (!$con) used to delete records from a { database table. die('Could not connect: ' . mysql_error()); Syntax } DELETE FROM table_name mysql_select_db("my_db", $con); WHERE some_column = some_value mysql_query("DELETE FROM Persons WHERE LastName='Griffin'"); Example mysql_close($con); <?php ?> $con = mysql_connect("localhost","root","root”); www.opengurukul.com 141
  • 142. Important functions mysql_num_rows:Get number of rows in result mysql_affected_rows:Get number of affected rows in previous MySQL operation mysql_select_db:Select a MySQL database www.opengurukul.com 142
  • 143. mysql_num_rows Example <?php $link = mysql_connect("localhost", "mysql_user", "mysql_password"); mysql_select_db("database", $link); $result = mysql_query("SELECT * FROM table1", $link); $num_rows = mysql_num_rows($result); echo "$num_rows Rowsn"; ?> www.opengurukul.com 143
  • 144. mysql_affected_rows Example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); mysql_query('DELETE FROM mytable WHERE id < 10'); printf("Records deleted: %dn", mysql_affected_rows()); mysql_query('DELETE FROM mytable WHERE 0'); printf("Records deleted: %dn", mysql_affected_rows()); www.opengurukul.com 144 ?>
  • 145. mysql_select_db Example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Not connected : ' . mysql_error()); } $db_selected = mysql_select_db('foo', $link); if (!$db_selected) { die ('Can't use foo : ' . mysql_error()); } ?> www.opengurukul.com 145
  • 146. Chapter 19 PHP & ODBC www.opengurukul.com 146
  • 147. Create an ODBC Connection Here is how to create an ODBC connection to a MS Access Database: 1.Open the Administrative Tools icon in your Control Panel. 2.Double-click on the Data Sources (ODBC) icon inside. 3. Choose the System DSN tab. 4.Click on Add in the System DSN tab. 5. Select the Microsoft Access Driver. Click Finish. 6. In the next screen, click Select to locate the database. 7.Give the database a Data Source Name (DSN). 8. Click OK. www.opengurukul.com 147
  • 148. DSN On Linux: To use MySQL via ODBC: <?php $db_host = "server.mynetwork"; $db_user = "dbuser"; $db_pass = "dbpass"; $dsn = "DRIVER={MySQL ODBC 3.51 Driver};" . "CommLinks=tcpip(Host=$db_host);" . "DatabaseName=$db_name;" . "uid=$db_user; pwd=$db_pass"; odbc_connect($dsn, $db_user, $db_pass); www.opengurukul.com 148 ?>
  • 149. Connecting to an ODBC The odbc_connect() is used to connect to an ODBC data source. It takes four parameters: -data source name -username -password -optional cursor type. Example The following example creates a connection to a DSN called northwind, with no username and no password. $conn=odbc_connect('northwind','',''); www.opengurukul.com 149
  • 150. Executing SQL Statement: odbc_exec() The odbc_exec() function is used to execute an SQL statement. Example example with no username and no password. It then creates an SQL and executes it: $conn=odbc_connect('northwind','',''); $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); www.opengurukul.com 150
  • 151. Retrieving Records odbc_fetch_row() This function is used to return records from the result-set. The function takes two parameters: - ODBC result identifier - an optional row number Example odbc_fetch_row($rs) www.opengurukul.com 151
  • 152. Retrieving Fields from a Record: odbc_result() This function is used to read fields from a record. It takes two parameters: -The ODBC result identifier - a field number or name. Example1 $compname=odbc_result($rs,1); returns the value of the first field from the record: Example2 $compname=odbc_result($rs,"CompanyName"); returns the value of a field called "CompanyName": www.opengurukul.com 152
  • 153. Closing an ODBC Connection: odbc_close() The odbc_close() function is used to close an ODBC connection. Example odbc_close($conn); www.opengurukul.com 153
  • 154. Chapter 20 Object Oriented Programming www.opengurukul.com 154
  • 155. classes A class is user defined data type that contains attributes or data members; and methods which work on the data members. Class structure class <class-name> { <class body :- Data Members &amp; Methods>; } www.opengurukul.com 155
  • 156. Class example class Customer //customer is the class name { private $first_name, $last_name; //$first_name/$last_name are attributes or data members. public function setData($first_name, $last_name) //setData is the method { $this->first_name = $first_name; $this->last_name = $last_name; } public function printData() //printData is also the method { echo $this->first_name . " : " . $this->last_name; } www.opengurukul.com 156 }
  • 157. The new instance To create an instance of a class, the new keyword must be used. An object will always be created when unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation If a string containing the name of a class is used with new, a new instance of that class will be created. Syntax $instance = new Class(); Or we can write $className = 'Foo'; $instance = new $className(); www.opengurukul.com 157
  • 158. Object assignment Example $instance = new SimpleClass(); $assigned = $instance; $reference =& $instance; $instance->var = '$assigned will have this value'; $instance = null; // $instance and $reference become null var_dump($instance); var_dump($reference); var_dump($assigned); www.opengurukul.com 158
  • 159. Extends keyword A class can inherit the methods and } properties of another class by $extended = new ExtendClass(); using the keyword extends in the class declaration. $extended->displayVar(); ?> Example output:Extending class <?php a default value class ExtendClass extends SimpleClass { function displayVar() { echo "Extending classn"; parent::displayVar(); www.opengurukul.com 159 }
  • 160. Properties Class member variables are called "properties" They are defined public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value www.opengurukul.com 160
  • 161. Properties Example // valid property declarations: <?php public $var6 = myConstant; class SimpleClass public $var7 = array(true, false); { // This is allowed only in PHP 5.3.0 and later. // invalid property declarations: public $var8 = <<<'EOD' public $var1 = 'hello ' . 'world'; hello world public $var2 = <<<EOD EOD; hello world } EOD; ?> public $var3 = 1+2; public $var4 = self::myStaticMethod(); public $var5 = $myVar; www.opengurukul.com 161
  • 162. Class constants Example <?php class MyClass { const constant = 'Any Testing Constant Value'; function showConstant() { echo self::constant . "n"; } } echo MyClass::constant . "n"; ?> www.opengurukul.com 162 output: Any Testing Constant Value
  • 163. Constructor Syntax class SubClass extends BaseClass void __construct ([ mixed $args [, $... ]] ) { function __construct() Example { <?php parent::__construct(); class BaseClass print "SubClass constructorn"; { } function __construct() } { $obj = new BaseClass(); print "BaseClass constructorn"; $obj = new SubClass(); } ?> } www.opengurukul.com Output: BaseClass constructor BaseClass 163 constructor SubClass constructor.
  • 164. Destructor Syntax function __destruct() { void __destruct ( void ) print "Destroying " . $this->name . "n"; Example } <?php } class MyDestructableClass $obj = new MyDestructableClass(); { ?> function __construct() Output { In constructor Destroying print "In constructorn"; MyDestructableClass $this->name = "MyDestructableClass"; } www.opengurukul.com 164
  • 165. Object inheritance Example class bar extends foo <?php { class foo public function printItem($string) { { public function printItem($string) echo 'Bar: ' . $string . PHP_EOL; { } echo 'Foo: ' . $string . PHP_EOL; } } $foo = new foo(); $bar = new bar(); public function printPHP() $foo->printItem('baz'); // Output: 'Foo: baz' { $foo->printPHP(); // Output: 'PHP is great' echo 'PHP is great.' . PHP_EOL; $bar->printItem('baz'); // Output: 'Bar: baz' } $bar->printPHP(); // Output: 'PHP is great' ?> www.opengurukul.com 165 } output:Foo: baz PHP is great. Bar: baz PHP is great.
  • 166. Scope Resolution Operator (::) It is a token that allows access to static, constant, and overridden properties or methods of a class. The variable's value can not be a keyword (e.g. self, parent and static). Example <?php class MyClass { const CONST_VALUE = 'Any constant value'; } $classname = 'MyClass'; echo MyClass::CONST_VALUE; ?> output:Any constant value www.opengurukul.com 166
  • 167. Self and parent Two special keywords self and parent class OtherClass extends MyClass are used to access properties or { methods from inside the class definition. public static $my_static = 'static var'; public static function doubleColon() Example { <?php echo parent::CONST_VALUE . "<br>"; class MyClass echo self::$my_static . "<br>"; { } const CONST_VALUE = 'Any constant value'; } } $classname = 'OtherClass'; $classname = 'MyClass'; OtherClass::doubleColon(); ?> www.opengurukul.com 167 Output: A constant value static var
  • 168. Static keyword Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object . The variable's value can not be a keyword (e.g. self, parent and static). www.opengurukul.com 168
  • 169. Static keyword Example } <? public function getStaticData() class ClassName { { echo ClassName::$staticvariable; //Accessing Static Variable static private $staticvariable; //Defining Static Variable } function __construct($value) } { $a = new ClassName("12"); if($value != "") $a = new ClassName("23"); { $a = new ClassName(""); ClassName::$staticvariable = $value; //Accessing ?> Static Variable Output:12 } www.opengurukul.com 23 169 $this->getStaticData(); 23
  • 170. Abstract classes It is not allowed to create an instance of a class that has been defined as abstract. Syntax <? abstract class classname { //attributes and methods abstract function methodname } class derived extends classname { function methodname } www.opengurukul.com 170 ?>
  • 171. Abstract class Example class EmployeeData extends employee //extending abstract class <? { abstract class employee function __construct($name,$age) { { protected $empname; $this->setdata($name,$age); protected $empage; } function setdata($empname,$empage) function outputData() { { $this->empname = $empname; echo $this->empname; $this->empage = $empage; echo $this->empage; } } abstract function outputData(); www.opengurukul.com EmployeeData("Hitesh","24"); $a = new 171 } $a->outputData(); ?> Output: Hitesh 24
  • 172. Object interfaces Interface is a object oriented concept, It is the place where we can define the function. Syntax Interface interface_name { const 1; const N; function methodName1() function methodNameN() } www.opengurukul.com 172
  • 173. Object interfaces Example function shimu() <?php { interface shahu print "<br />"; { print self::lotu; const lotu="lotu is lucky"; } public function rooja(); } } $hanu=new hasu(); class hasu implements shahu $hanu->rooja(); { $hanu ->shimu(); public function rooja() ?> print "<br />"; output:lotu is lucky print self::lotu; print "<br />"; www.opengurukul.comhai roja 173 print "hai roja"; } lotu is lucky
  • 174. Overloading Overloading in PHP provides means to dynamically "create" properties and methods. All overloading methods must be defined as public. Two types of overloading are there -Property overloading -Method overloading www.opengurukul.com 174
  • 175. Property overloading Example void __set ( string $name , mixed $value ) mixed __get ( string $name ) bool __isset ( string $name ) void __unset ( string $name ) The $name argument is the name of the property being interacted with. __set() is run when writing data to inaccessible properties. __get() is utilized for reading data from inaccessible properties. __isset() is triggered by calling isset() or empty() on inaccessible properties. __unset() is invoked when unset() is used on inaccessible properties. www.opengurukul.com 175
  • 176. Method overloading Example mixed __call ( string $name , array $arguments ) mixed __callStatic ( string $name , array $arguments ) -$name argument is the name of the method being called. -The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method. __call() is triggered when invoking inaccessible methods in an object context. __callStatic() is triggered when invoking inaccessible methods in a static context. www.opengurukul.com 176
  • 177. Object iteration PHP 5 provides a way for objects to be foreach($this as $key => $value) defined so it is possible to iterate through { a list of items. print "$key => $value<br>"; Example } <?php } class MyClass } { $class = new MyClass(); public $var1 = 'value 1'; foreach($class as $key => $value) public $var2 = 'value 2'; { public $var3 = 'value 3'; print "$key => $value<br>"; protected $protected = 'protected var'; } function iterateVisible() echo "<br>"; { www.opengurukul.com 177 $class->iterateVisible(); ?> echo "MyClass::iterateVisible:n";
  • 178. Magic methods There are so many functions which are _wakeup magical in php _toString _construct _invoke _destruct _set_state _call _clone _callStatic _get _set _isset _unset _sleep www.opengurukul.com 178
  • 179. __sleep and __wakeup Serialize() checks if your class has a function with the magic name __sleep, If so, that function is executed prior to any serialization Unserialize() checks for the presence of a function with the magic name __wakeup If present, this function can reconstruct any resources that the object may have. www.opengurukul.com 179
  • 180. __toString,__invoke,__set_state __toString The __toString method allows a class to decide how it will react when it is treated like a string. __invoke The __invoke method is called when a script tries to call an object as a function. __set_state This static method is called for classes exported by var_export() since PHP 5.1.0. www.opengurukul.com 180
  • 181. Final keyword It prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. Properties cannot be declared final, only classes and methods may be declared as final. www.opengurukul.com 181
  • 182. Final keyword Example <?php final class BaseClass { public function test() { echo "BaseClass::test() calledn"; } final public function moreTesting() // Here it doesn't matter if you specify the function as final or not { echo "BaseClass::moreTesting() calledn"; } } class ChildClass extends BaseClass { www.opengurukul.com 182 }// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass) ?>
  • 183. Cloning object it simply creates a copy of an object. $so = new SmallObject; Example $so->field++; $x = 1; $soRef = $so; $y =& $x; $soClone = clone $so; $x++; $so->field++; echo"$y $x<br>"; echo $so->field; // outputs: 2 class SmallObject echo $soRef->field; // outputs: 2 { echo $soClone->field; // outputs: 1 public $field = 0; } www.opengurukul.com 183
  • 184. Late static binding It can be used to refer the called class. The name late static binding is coined because of the static:: will no longer be resolved using the class where the method is defined. www.opengurukul.com 184
  • 185. Late static binding Example class Two extends One { public static function classIdentifier() { <?php echo __CLASS__; class One { } public static function classIdentifier() { } echo __CLASS__; Two::classtest(); } ?> public static function classtest() { Output: One self::classIdentifier(); } } www.opengurukul.com 185
  • 186. Objects and references Example $d->foo = 2; // ($c,$d) = <id> <?php echo $c->foo."n"; class A { $e = new A; public $foo = 1; function foo($obj) { } // ($obj) = ($e) = <id> $a = new A; $obj->foo = 2; $b = $a; // $a and $b are copies of the same } identifier foo($e); // ($a) = ($b) = <id> echo $e->foo."n"; $b->foo = 2; ?> echo $a->foo."n"; output:2 $c = new A; 2 $d = &$c; // $c and $d are references www.opengurukul.com 186 2
  • 187. Object serialization Serialization in the context of storage and transmitting is the process of converting an object into a sequence of bits so that it can persist in a storage medium and or transmitted across a network. serializing and unserializing can be done by two functions They are: -Serialize -unserialize serialize() returns a string containing a byte-stream representation of any value unserialize() can use this string to recreate the original variable values. www.opengurukul.com 187
  • 188. Chapter 21 PHP Built-in Functions www.opengurukul.com 188
  • 189. PHP Calendar Functions and constants cal_days_in_month:It Return the number of days in a month for a given year and calendar. Syntax:int cal_days_in_month ( int $calendar , int $month , int $year ) Parameters:calendar - Calendar to use for calculation month - Month in the selected calendar year - Year in the selected calendar Example <?php $num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); echo "There was $num days in August 2003"; ?> www.opengurukul.com Output -There was 31 days in August 2003 189
  • 190. cal_info It Returns information about a particular calendar. Syntax:array cal_info ([ int $calendar = -1 ] ) Parameters:Calendar - Calendar to return information for. If no calendar is specified information about all calendars is returned. Example:<?php $info = cal_info(0); print_r($info); ?> output: Array ( [months] => Array ( [1] => January [2] => February [3] => March [4] => April [5] => May [6] => June [7] => July [8] => August [9] => September [10] => October [11] => November [ www.opengurukul.com 190
  • 191. Many other calender function cal_from_jd:It Converts from Julian Day Count to a supported calendar. cal_to_jd:It Converts from a supported calendar to Julian Day Count. FrenchToJD :It Converts a date from the French Republican Calendar to a Julian Day Count. GregorianToJD:It Converts a Gregorian date to Julian Day Count. www.opengurukul.com 191
  • 192. Date/time Functions and constants Date function The PHP date() function is used to format a time and/or date. Syntax date(format,timestamp) ; Parameter format - Required. Specifies the format of the timestamp timestamp - Optional. Specifies a timestamp. Default is the current date and time. www.opengurukul.com 192
  • 193. Directory Functions and constants Chdir: It change the directory Syntax: bool chdir ( string $directory ) Parameters: directory - The new current directory Example:<?php // current directory echo getcwd() . "n"; chdir('public_html'); // current directory echo getcwd() . "n"; ?> output:/home/vincent www.opengurukul.com 193 /home/vincent/public_html
  • 194. chroot It change the root directory Syntax bool chroot ( string $directory ) Parameters directory - The path to change the root directory to. Example <?php chroot("/path/to/your/chroot/"); echo getcwd(); ?> output: / www.opengurukul.com 194
  • 195. getcwd It gets the current working directory Syntax: string getcwd ( void ) Example:<?php // current directory echo getcwd() . "n"; chdir('cvs'); // current directory echo getcwd() . "n"; ?> output:/home/matsya home/matsya/cvs www.opengurukul.com 195
  • 196. Error Logging functions and constants debug_backtrace: It generates a a_test('friend'); backtrace. include_once 'a.txt'; Syntax: array debug_backtrace ([ bool ?> $provide_object = true ] ) a.txt:friend is the best part of my life Parameters output:Hi: friendarray(1) { [0]=> array(4) { ["file"]=> string(13) "/var/test.php" ["line"]=> int(10) provide_object - Whether or not to ["function"]=> string(6) "a_test" ["args"]=> populate the "object" index. array(1) { [0]=> &string(6) "friend" } } } friend is the best part of my life Example: <?php function a_test($str) { echo "nHi: $str"; var_dump(debug_backtrace()); } www.opengurukul.com 196
  • 197. error_log It send an error message somewhere Syntax: bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] ) Parameters message - The error message that should be logged. message_type - Says where the error should go. Destination - The destination. Its meaning depends on the message_type parameter as described above. extra_headers - The extra headers. It's used when the message_type parameter is set to 1. Example:<?php error_log("You messed up!", 3, "/var/tmp/my-errors.log"); ?> www.opengurukul.com 197
  • 198. File System Functions and constants Basename It returns trailing name component of path Syntax string basename ( string $path [, string $suffix ] ) Parameters path - A path. Suffix - If the name component ends in suffix this will also be cut off. Example <?php echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL; echo "2) ".basename("/etc/passwd").PHP_EOL; ?> www.opengurukul.com 198 Output 1) sudoers 2) passwd