PHP

 PHP BASICS

(HYPERTEXT PREPROCESSOR)





Important Links:-
---------------------



1) Open-source scripting language
2) Case sensitivity
     i) Keywords: no
     ii) Variable names: yes
3) Scripts run server-side
     i) Web server must support PHP
    ii) HTML result is sent back to client browser
4) .php file extension
5) Can contain pHP, CSS, HTML
6) PHP code blocks begin with <?php
7) PHP code blocks end with ?>;
8) PHP is normally embedded within HTML
9) Use a semi-colon to end each line
10) Comments
      i) // Comment text
     ii) # Comment text
    iii) /* Multi-line or inline comment text */
11) PHP == 'Hypertext Preprocessor'
12) Interpreted language, scripts are parsed at run-time rather than compiled beforehand.
13) Executed on the server-side.
14) Source code not visible by client.
     - 'View Source' in browsers does not display the PHP code.
15) Compatible with many popular databases.


cmd commands:-
--------------------

1) netstat -ano
2) taskkill /pid 4

PHP Data Types:
-------------------

String ------------------------------->  Integer
Floating point/double --------------> Object
Array --------------------------------> Boolean
Resource ----------------------------> NULL

Variables:
------------


Variable Name Rules:
---------------------------

1) Must start with the $ sign, followed by the name of the variable.
2) Must start with a letter or the underscore character.
3) Cannot start with a number.
4) Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
5) Variable names are case-sensitive ($var1 and $VAR1 are two different variables).

Global Scope Variable:
---------------------------

1) A Variable declared outside a function.
2) PHP stores Global Variables in an array called: $GLOBALS[index].
3) They are always available for use.

Superglobals:
-----------------

A superglobal is a built-in PHP variable that is available in any scope: at the top level of your script, within a function, or within a class method.

1) $_REQUEST - Contains the values of both the $_GET and $_POST arrays combined, along with the values of the $_COOKIE superglobal array.
2) $_POST - Contains a list of all the field names and values sent by a form using the post method.
3) $_GET - Contains a list of all the field names and values sent by a form using the get method.
4) $_SERVER

Local Scope Variable:
--------------------------

A Variable declared inside a function.

1) $variablename=value
2) $city="Halifax";
3) Echo "Location:" .$city;   // The dot is used for concatenation
4) $hourly_wage=14.56;
5) static $hourly_wage=14.56;
* If declared within a function, do not delete when function completes

Echo or print:-
-----------------

1) It is used to print the lines of output on the screen.
2) Echo allows multiple parameters in a statement whereas print does not.
3) Echo also executes statements slightly faster than print.

Data Types:
---------------

1) String
2) Integer
3) Float
4) Array
5) NULL
6) Boolean
7) Object

2) Integer:
    ---------

   1) Must have at least one digit.
   2) Must not have a decimal point.
   3) Can be either positive or negative.
   4) Can be in three formats, i.e., decimal, hexadecimal or octal formats.

3) Float:
    -------

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

5) Null: -> A variable with no value assigned to it. 


6) False Boolean Values:
    --------------------------

   1) The integer 0 (zero)
   2) The float 0.0 (zero)
   3) The empty string, and the string "0"
   4) An array with zero elements
   5) NULL Variables
   6) Any other value would be considered true.

7) Object:
    --------

    1) Stores data and also information on how to process the data known as a method.

Object Class:-
-----------------

The set of properties (or variables) that are tied to an object.

Assignment Types:
------------------------

1) A public assignment means the property can be accessed everywhere.
2) A private assignment means it can only be accessed by the class that defines it.
3) A protected assignment means it can be accessed only within the class itself and by inherited parent classes].

PHP Constants:
-------------------

Constant:- An identifier for a given value. A constant cannot be changed during the script, as a variable can.

Syntax:
---------

define (name, value, case-insensitive)

PHP Operators:
--------------------

Used to perform various operations on variables and values.

Operator Groups:
----------------------

1) Arithmetic Operators
2) Assignment Operators
3) Comparison Operators
4) Increment/Decrement Operators
5) Logical Operators
6) String Operators
7) Array Operators

PHP Conditional Statements:
-----------------------------------

Types of Conditional Statements:
----------------------------------------

1) If
2) If-else
3) If-else-elseif
4) Switch

1) The IF statement:
    ---------------------

Syntax:-
----------

if (condition) {
      code to be executed if condition is true;
}

2) If-else:-
    ----------

Syntax:-
----------

if (condition) {
       code to be executed if condition is true;
} else {
       code to be executed if condition is false
}

$weekday = date ("D");
if ($weekday == "Fri")
{
      echo "Happy Friday!";
}
else
{
     echo "Hang in there.";
}

PHP Switch Statement:-
---------------------------

Switch Statement:-
-----------------------

Compares the value of an expression against a set of predefined conditions, also referred to as cases.

PHP Looping:-
------------------

Loops allow us to run the same block of code multiple times.

1) Loop Types:
    ----------------

   i) For:
      ----

      i) The number of iterations is known.
     ii) If working with arrays, use foreach.

   ii) While:
       -------

       i) Code block runs while a condition is true.

  iii) Do-While Loop
  iv) Foreach Loop


Foreach Looping Example:
--------------------------------

$cost_centers = array ("Hfx-1", "Hfx-2", "Tor-1");

Foreach ($cost_centers as $tempvar)
{
      echo "The cost center is $tempvar";
}

While Looping Example:
-----------------------------

$filenotthere = true;

while ($filenotthere)
{
       $filenotthere = fileexists ("upload1.jpg");
}

PHP Functions: f(x)
------------------

1) Provide additional capabilities
2) Over 1,000 built-in functions
3) Can accept arguments
4) Can return values - uses the "return" statement
5) A function is a block of statements that can be called upon whenever they are required.
6) A function will not execute unless we specifically call the function in our script.

Syntax:-
----------

function functionName () {
        code to be executed;
}

PHP Arrays:-
----------------

An array is a variable that can store mutiple values.

Types of Arrays:
--------------------

1) Indexed Arrays
2) Associative Arrays
3) Multidimensional Arrays
4) Sorting Arrays - sort();

=> print_r() can be used to output the contents of arrays.


PHP Built-in Functions:
----------------------------

i) mysqli_connect() ----------->  crypt () -----------------------> trim ()
ii) wordwrap () ---------------->  substr () -----------------------> strtoupper ()
iii) strlen () --------------------->  is_bool () ----------------------> boolval ()
iv) phpinfo () ------------------->  datetime () --------------------> pdf_save ()

Custome Functions:
------------------------

Fuction testFunctionOne ($msgtext)
{
          echo $msgtext;
}
testFunctionOne ();

Building Function into a PHP Script:
-------------------------------------------



PHP URL Parameters:
-----------------------------

1) Values can be passed between pages via URLs.
2) PHP can parse URL strings to retrieve values.
3) Retrieve URL items with $_GET
    i) Applies to all parameters appearing after? in the URL.
   ii) This is called the HTTP query string.
4) Multiple URL parameters can be used in a single URL.

Example 1:
-------------

1) URL is http://www.webapp1.com/?city=Halifax
2) Example extraction PHP code:
     Echo "The location is: " .$_GET["city"]

Example 2:
-------------

1) URL is http://www.webapp1.com/?email=user@abc.com
2) Example extraction PHP code:
    If (isset ($_GET["email"])) {
echo $[GET["email"]];
    }

PHP Connectivity to MySQL:
------------------------------------

Current Options:-
---------------------

1) MySQLi
    i) Connectivity only to MySQL
   ii) Normally installed automatically with PHP
  iii) mysqli_connect
  iv) Built-in PHP function
2) PDO
    i) Connectivity to many types of databases

PHP MySQL Connectivity:
--------------------------------

<?php
$servername = "server1";
$username = "cblackwell";
$password = "Pa$$w0rdABS123";

$conn = mysqli_connect ($servername, $username, $password);

if (mysqli_num_rows($result) > 0)
....

Close MySQL connections:
--------------------------------

mysqli_close ($conn);

MySQLi:
-----------

i) Establish MySQL connections
ii) Create databases, tables
iii) Insert, update, delete rows

Selecting Rows:
-------------------

$query = "SELECT id, fname, lname FROM Customers";
$result = mysqli_query ($conn, $query);

if (mysqli_num_rows ($result) > 0) {
          while ($row = mysqli_fetch_assoc ($result))
          {
echo $row["custid"]. " - " .
$row["lname"] . ", " . $row["fname"] . "<br>";
          }
}

Other Row Operations:
---------------------------

$query = "INSERT INTO Customers (id, fname, lname, email) VALUES ('0001', 'Codey', 'Blackwell', 'cblackwell@abc.com')";

$query = "UPDATE Customers SET lname = 'Bond' WHERE id=007";

$query = "DELETE FROM Customers WHERE id=0001";

PHP Forms:
----------------

1) Forms are very important.
2) Web pages interact with users using Forms.

PHP Script:
--------------

1) <form action = "send.php" method = "post">
2) Validate Form using PHP.
3) Server-side validation is best.

POST vs GET:-
-------------------

1) Both POST & GET use Arrays to pass data.
2) Key = Name of Form Control.
3) Value = Data Input by User

GET:
-------

1) The GET method passes our array variables through the URL parameters.
2) Should be used only for sending non-sensitive data.
3) Never send passwords through the GET method.
4) All variables are displayed openly in the URL.
5) The GET method has limits on how much information can be sent.
6) The current limit is 2000 characters.

POST:
----------

1) The POST method passes variables using the HTTP Post method.
2) The POST method is much more secure because variables are not displayed in the URL.
3) Information is invisible to others because it is embedded within the body of the HTTP request.
4) It has no limits as to the amount of information we can send.
5) This method is preferred by developers.

Validation:
------------

1) Pass all variables through PHP's htmlspecialchars() functions to make sure data is transmitted                 securely.
2) Use the trim function to strip any unnecessary characters such as extra space, tabs, or breaks inserted into the input fields.
3) Use the striplashes() function to remove any backslashes from user input data. This helps add an additional layer of security and protects data integrity.

Functions Used:
-------------------

1) preg_match()
2) 

PHP Objects(OOPs):
--------------------------

Advantages of OOP:
--------------------------

1) To start with, OOP makes it easy to map business requirements to code modules. Because your application is based on the idea of real-world objects, you can often create a direct mapping of people,
     things, and concepts in classes.

2) The second benefit of OOP is code reuse.

3) Another OOP advantage comes from the modularity of classes.

Classes:-
------------

1) A class is a unit of code that describes the characteristics and behaviors of something, or of a group of things.
2) A class is a blueprint, or factory, for constructing an object.
3) To create a class, you use PHP’s class keyword.
4) A common coding standard is to begin a class name with a capital letter.

e.g.- class Car {
// Nothing to see here; move along
       }

Object:-
----------

1) An object is a specific instance of a class.
2) class specifies the characteristics that an object will have, but not necessarily the specific values of those characteristics.
3) To create an object, you use the new keyword, followed by the name of the class that you want to base the object on. You can then assign this object to a variable, much like any other value.

e.g.-  class Car {
// Nothing to see here; move along
         }
         $beetle = new Car();
         $mustang = new Car();
         print_r( $beetle ); // Displays “Car Object ( )”
         print_r( $mustang ); // Displays “Car Object ( )”

Properties:-
---------------

1) In OOP terminology, the characteristics of a class or object are known as its properties.
2) Properties are much like regular variables, in that they have a name and a value (which can be of any type).
3) Some properties allow their value to be changed and others do not.

e.g.- the Car class might have properties such as color and weight. Although the color of the car can be changed by giving it a new paint job, the weight of the car (without cargo or passengers) is a fixed value.

Methods:-
-------------

1) The behaviors of a class — that is, the actions associated with the class — are known as its methods.
2) Methods are very similar to functions; in fact, you define methods in PHP using the function statement.
3) Like functions, some methods act on external data passed to them as arguments, but an object’s method can also access the properties of the object.
4) The methods of a class, along with its properties, are collectively known as members of the class.

Property Visibility:-
-----------------------

Each property of a class in PHP can have one of three visibility levels, known as public, private, and protected:

1) Public:-
    ---------

    Public properties can be accessed by any code, whether that code is inside or outside the class. If a property is declared public, its value can be read or changed from anywhere in your script.

2) Private:-
    ----------

    Private properties of a class can be accessed only by code inside the class. So if you create a property that’s declared private, only methods inside the same class can access its contents.
    (If you attempt to access the property outside the class, PHP generates a fatal error.).

3) Protected:-
    -------------

    Protected class properties are a bit like private properties in that they can’t be accessed by code outside the class, but there’s one subtle difference: any class that inherits from the class can also access the properties.

e.g. - 1) class MyClass {
public $property1; // This is a public property
private $property2; // This is a private property
protected $property3; // This is a protected property
            }
        2) class MyClass {
public $widgetsSold = 123;
            }

Accessing Properties:-
---------------------------

$object-> property;

Static Properties:-
----------------------

1) You can also create static class properties in a similar way, by adding the static keyword just before the property name:
    class MyClass {
        public static $myProperty;
    }

2) Static members of a class are independent of any particular object derived from that class.

3) To access a static property, you write the class name, followed by two colons ( :: ), followed by the property name (preceded by a $ symbol):
    e.g. - MyClass::$myProperty = 123;

Class Constants:-
---------------------

1) constants — special identifiers that hold fixed values throughout the running of your script.
2) PHP also lets you create constants within classes.
3) To define a class constant, use the keyword const, as follows:
     class MyClass {
const MYCONST = 123;
     }
4) As with normal constants, it’s good practice to use all - uppercase letters for class constant names.

5) Like static properties, you access class constants via the class name and the :: operator:
    e.g. - echo MyClass::MYCONST;

6) Class constants are useful whenever you need to define a fixed value or set a configuration option, that is specific to the class in question.

Calling Methods:-
----------------------

1) To call an object’s method, simply write the object’s name, then the same arrow used for accessing properties ( - > ), then the method name followed by parentheses:
     e.g.- $object-> method();

Adding Parameters and Returning Values:
--------------------------------------------------

public function aMethod( $param1, $param2 ) {
       // (do stuff here)
}

public function aMethod( $param1, $param2 ) {
          // (do stuff here)
          return true;
}

Accessing Object Properties from Methods:-
------------------------------------------------------

1) To access an object’s property from within a method of the same object, you use the special variable name $this, as follows:
      $this-> property;

Static Methods:-
--------------------

1) PHP lets you create static methods in much the same way as static properties. To make a method             static, add the static keyword before the function keyword in the method definition:

class MyClass {
     public static function staticMethod() {
// (do stuff here)
    }
}

2) To call a static method, write the class name, followed by two colons, followed by the method name,      and the arguments (if any) in parentheses:
MyClass::staticMethod();

3) Static methods are useful when you want to add some functionality that’s related to a class, but that         doesn’t need to work with an actual object created from the class.

e.g.- 
class Car {
       public static function calcMpg( $miles, $gallons ) {
              return ( $miles / $gallons );
       }
}
echo Car::calcMpg( 168, 6 ); // Displays “28”

4) You can also use the self keyword (much as you use $this with objects).

Encapsulation:-
------------------

Encapsulation means that a class’s internal data should be protected from being directly manipulated from outside, and that the details of the class’s implementation — such as how it stores values or manipulates data 
— should be hidden from the outside world.
By doing this, you gain two advantages:
1) You can change your class’s implementation details at any time without affecting the code that uses     the class.

2) You can trust the state of an object to be valid and to make sense.

Object Overloading with —get(), —set(), and —call():
----------------------------------------------------------------

PHP lets you use a technique known as overloading to intercept attempts to read or write an object’s properties or call its methods.

PHP allows you to create three “ magic ” methods that you can use to intercept property and method accesses:
1) _get() is called whenever the calling code attempts to read an invisible property of the object.
2) _set() is called whenever the calling code attempts to write to an invisible property of the object.
3) _call() is called whenever the calling code attempts to call an invisible method of the object.

Overloading Property Accesses with __get() and __set():-
---------------------------------------------------------------------

To intercept attempts to read an invisible property, you create a method called _get() within your class. (That’s two underscores, followed by the word get .) Your _get() method should expect a single
argument: the name of the requested property. It should then return a value; this value in turn gets passed back to the calling code as the retrieved property value.

e.g. - 
class Car {
     public function __get( $propertyName ) {
echo “The value of ‘$propertyName’ was requested < br / > ”;
return “blue”;
     }
}
$car = new Car;
$x = $car- > color; // Displays “The value of ‘color’ was requested”
echo “The car’s color is $x < br / > ”; // Displays “The car’s color is blue”

Overloading Method Calls with __call():-
-------------------------------------------------

1) We use _call() to handle calls to nonexistent methods of a class.
2) Just create a method named _call() in your class that accepts the nonexistent method name as a string, and any arguments passed to the nonexistent method as an array. 
    The method should then return a value (if any) back to the calling code:
     
    public function __call( $methodName, $arguments ) {
           // (do stuff here)
           return $returnVal;
    }

3) __call() is very useful if you want to create a “ wrapper ” class that doesn’t contain much functionality of its own, but instead hands-off method calls to external functions or APIs for processing.

Built-in String Functions:-
------------------------------

1) strlen() for calculating the length of the string.
2) strtoupper() for converting the string to uppercase letters.
3) strpos() for finding the position of the first occurrence of a character in the string.

Other Overloading Methods:-
-----------------------------------

1) __isset() is called whenever the calling code attempts to call PHP ’ s isset() function on an invisible property.
2) It takes one argument — the property name — and should return true if the property is deemed to be “ set, ” and false otherwise:
    class MyClass {
           public function __isset( $propertyName ) {
// All properties beginning with “test” are “set”
return ( substr( $propertyName, 0, 4 ) == “test” ) ? true : false;
           }
    }
    $testObject = new MyClass;
    echo isset( $testObject- > banana ) . “ < br / > ”; // Displays “” (false)
    echo isset( $testObject- > testBanana ) . “ < br / > ”; // Displays “1” (true)

    _unset() is called when the calling code attempts to delete an invisible property with PHP ’ s unset() function. It shouldn ’ t return a value, but should do whatever is necessary to “ unset ” the property (if applicable):
     class MyClass {
           public function __unset( $propertyName ) {
echo “Unsetting property ‘$propertyName’ < br / > ”;
           }
    }
    $testObject = new MyClass;
    unset( $testObject- > banana ); // Displays "Unsetting property 'banana' "

    _callStatic() works like _call() , except that it is called whenever an attempt is made to call an invisible static method. E.g.- 
    class MyClass {
            public static function __callStatic( $methodName, $arguments ) {
echo “Static method ‘$methodName’ called with the arguments: < br / > ”;
foreach ( $arguments as $arg ) {
       echo “$arg < br / > ”;
}
           }
    }
    MyClass::randomMethod( “apple”, “peach”, “strawberry” );

3) __callStatic() works like _call() , except that it is called whenever an attempt is made to call an invisible static method. e.g. - 
class MyClass {
        public static function __callStatic( $methodName, $arguments ) {
echo "Static method '$methodName' called with the arguments:<br />";
foreach ( $arguments as $args ) {
echo "$arg<br />";
}
        }
}
MyClass::randomMethod( "apple", "peach", "strawberry" );

Inheritance:-
-----------------

Using Inheritance to Extend the Power of Objects:-
--------------------------------------------------------------

1) A child class inherits all the properties and methods of its parent, and it can also add additional properties and methods.
2) If you want to create a lot of similar classes, you have to write the code that they have in common only once, in the parent class. This saves you from duplicating code.
3) We use extends keyword for inheritance.
e.g. - 
class Shape {
       // (General Shape properties and methods here)
}

class Circle extends Shape {
      // (Circle-specific properties and methods here)
}

Overriding Methods in the Parent Class:-
------------------------------------------------

1) Simply create a method with the same name in the child class. Then, when that method name is called for an object of the child class, the child class’s method is run instead of the parent class’s method.
2) The parent class’s method is called when accessed from an object of the parent class, and the child class’s method is called when using an object of the child class.

Syntax:-
----------

class ParentClass {
        public function someMethod() {
// (do stuff here)
        }
}
class ChildClass extends ParentClass {
        public function someMethod() {
// This method is called instead for ChildClass objects
       }
}

$parentObj = new ParentClass;
$parentObj- > someMethod(); // Calls ParentClass::someMethod()
$childObj = new ChildClass;
$childObj- > someMethod(); // Calls ChildClass::someMethod()

3) To call an overridden method, you write parent:: before the method name:
parent::someMethod();

Final Class:-  A final class in PHP cannot be inherited into other classes.

Final Method:- A final method cannot be overridden into another class.

e.g.- 
i) final class HandsOffThisClass {
        public $someProperty = 123;
        public function someMethod() {
echo “A method”;
        }
}

// Generates an error:
// “Class ChildClass may not inherit from final class (HandsOffThisClass)”
class ChildClass extends HandsOffThisClass {
}

ii) class ParentClass {
            public $someProperty = 123;
            public final function handsOffThisMethod() {
echo “A method”;
            }
   }
   // Generates an error:
   // “Cannot override final method ParentClass::handsOffThisMethod()”

  class ChildClass extends ParentClass {
          public function handsOffThisMethod() {
echo “Trying to override the method”;
          }
  }

Abstract Classes and Methods:-
--------------------------------------

1) To declare an abstract method, simply use the abstract keyword.
abstract public function myMethod( $param1, $param2 );

2) If we declare one or more methods of a class to be abstract, we must also declare the whole class to be abstract, too.
abstract class MyClass {
abstract public function myMethod( $param1, $param2 );
}

3) We can’t instantiate an abstract class — that is, create an object from it — directly.
// Generates an error: “Cannot instantiate abstract class MyClass”
$myObj = new MyClass;

4) The opposite of an abstract class — that is, a class that implements all the methods of its parent abstract class — is called a concrete class.

Interfaces:-
---------------

1) A class implements an interface.
2) You create an interface much like a class, except that you use the keyword interface rather than class.
interface MyInterface {
          public function myMethod1( $param1, $param2 );
          public function myMethod2( $param1, $param2 );
}

3) Interfaces can't contain properties; they can only contain method declarations (which can’t contain any implementation code).
4) All methods in an interface must be public.
5) We can then make a class implement an interface using the implements keyword.
class MyClass implements MyInterface {
public function myMethod1( $param1, $param2 ) {
// (implement the method here)
}
public function myMethod2( $param1, $param2 ) {
// (implement the method here)
}
}

6) To implement more than one interface at once, separate the interface names with commas:
class MyClass implements MyInterface1, MyInterface2 {


Constructors and Destructors:-
--------------------------------------

1) An object's constructor method is called just after the object is created, and its destructor method is called just before the object is freed from memory.

2) To create a constructor, simply add a method with the special name __construct() to your class.

e.g.-
class MyClass {
        function __construct() {
echo “Whoa! I’ve come into being. < br / > ”;
        }
}
$obj = new MyClass; // Displays “Whoa! I’ve come into being.”

3) We can also pass arguments to constructors, just like normal methods.

4) If a class contains a constructor, it is only called if objects are created specifically from that class; if an object is created from a child class, only the child class's constructor is called. 
    However, if necessary you can make a child class call its parent's constructor with parent::__construct() .

5) Destructors are useful for tidying up an object before it's removed from memory.

6) You create destructor methods in the same way as constructors, except that you use __destruct() rather than __construct().

    Syntax:-
    -----------

     function __destruct() {
// (Clean up here)
     }

7) a destructor can’t accept arguments.

8) An object's destructor is called just before the object is deleted. This can happen because all references to it have disappeared (such as when the last variable containing the object is unset or goes out of scope), 
    when the script exits, either naturally or because of an error of some sort. In each case, the object gets a chance to clean itself up via its destructor before it vanishes.

9) As with constructors, a destructor of a parent class is not called when the child object is deleted, but you can explicitly call a parent’s destructor with parent::__destruct().

10) require_once() lets you include one PHP script file inside another, which means you can break up your PHP application into small, manageable script files.

Storing Objects as Strings:-
----------------------------------

1) PHP provides two functions to help:-
    i) serialize() - converts an object — properties, methods, and all — into a string of text.
    ii) unserialize() - takes a string created by serialize() and turns it back into a usable object

2) _sleep() is useful for cleaning up an object prior to serializing it, in the same way, that you might clean up in a destructor method.

3) In a real-world situation, make sure you don’t transmit sensitive information such as usernames as passwords as plain text strings if there’s a chance that the data might be intercepted or read by 
    untrusted third parties.

4) We can use the get_object_vars() function to get an associative array of all the properties in the object.

5) We can use the array_keys() function to get just the property names as an array, which you can then return from your _sleep() method.

Determining an Object's Class:-
----------------------------------------

1) get_class() is useful if you want to find out exactly which class an object belongs to.

instanceof Operator:-
--------------------------

If $object ’ s class is ClassName , or if $object ’ s class is descended from ClassName , then instanceof returns true . Otherwise, it returns false.

Syntax:-
----------

if( $object instanceof ClassName ) { 
}

Handling HTML Forms with PHP:
-----------------------------------------

1) You could then access the value that the user entered into that form field using either the $_GET or the
     $_REQUEST superglobal:
     $email = $_GET[“emailAddress”];
     $email = $_REQUEST[“emailAddress”];


Preserving State With Query Strings, Cookies, and Sessions:
---------------------------------------------------------------------

1) Query strings are used to store small amounts of data in the URL.
2) Cookies are used to store larger amounts of data in the browser itself.
3) Sessions is used to store even larger amounts of data and store it in a much more secure fashion.

Saving State with Query Strings:-
----------------------------------------

1) Query strings are a quick, convenient way to pass small amounts of data between browser requests.

2) Common uses of query strings include remembering a user's entered keywords when using a search function, identifying which topic within a forum to display to the user, 
    and specifying which post within a blog to display.

3) Query string data is very easy for the user to alter because it's visible and editable within the browser's address bar.

4) Therefore, query strings should be used only in situations where sending incorrect data won't compromise security.

5) You also need to make sure you don’t rely on query strings to authenticate users because people             often send URLs to friends in emails or instant messaging applications.

    If your URL contains all the data needed to authenticate a user, and that user sends the URL to a            friend, then the friend can pretend to be them!

6) you can embed sent form data in a URL by setting the form's method attribute to get.

7) When the form data is sent to the server, it is appended to the end of the URL as follows:
http://localhost/myscript.php?firstName=Fred & lastName=Bishop & ...

8) The browser adds a query ( ? ) character to the end of the URL, then follows it with each of the form fields as “name=value” pairs, with each pair separated by an ampersand ( & ). 
    The query string is the part of the URL after the ? character.

9) The specifications for a query string allow only the following characters to be used
within field names and values: letters, numbers, and the symbols - , , . (period), ! , ~ , * , ‘ (single quote), ( , and ) .

10) PHP gives you a function called urlencode() that can encode any string using URL encoding.

11) Simply pass it a string to encode, and it returns the encoded string. So you can use urlencode() to encode any data that may contain reserved characters.

http_build_query():-
----------------------

This function takes an associative array of field names and values and returns the entire query string.
You can then append this string, along with the initial ? symbol, to your URL. If generating XHTML markup, you should also pass the string through PHP's htmlspecialchars() function, 
which converts, for example, & to & amp; automatically:

Accessing Data in Query Strings:-
---------------------------------------

to access the field names and values in a query string you simply read them from the $_GET superglobal array, just as if you were handling a form sent with the get method:
$firstName = $_GET[“firstName”];
$homePage = $_GET[“homePage”];

Cookies:-
-----------

1) A cookie lets you store a small amount of data — no more than 4KB — within the user’s browser itself.

2) Then, whenever the browser requests a page on your Web site, all the data in the cookie is automatically sent to the server within the request. This means that you can send the data once to the browser, and the data is automatically available to your script from that moment onward.

3) You can make a cookie last for a fixed amount of time — anywhere from a few seconds to several years if you like — or you can set a cookie to expire once the browser application is closed.

4) Most modern browsers can store up to 30 cookies per Web site domain.

5) Cookies are somewhat more secure than using query strings.

6) If you need to store non-critical data, such as user preferences, on an ongoing basis, then cookies are      useful tool.

7) Most browsers let you view, as well as delete, any cookies stored by the browser. This can be very useful for debugging your cookie-based scripts.

Cookie Components:-
----------------------------

A cookie is sent from the server to the browser as part of the HTTP headers. Here’s an example of an HTTP header to create a cookie:
Set-Cookie: fontSize=3; expires=Tuesday, 6-Jan-2009 17:53:08 GMT; path=/;
domain=.example.com; HttpOnly


Cookie Field Description
---------------- --------------

1) name (for example, fontSize ) - The name of the cookie. This is much like the name of a form                                                                     field, or a key in an associative array.

2) value (for example, 3 ) -            The value of the cookie. This is similar to the value of a form field                                                            or a value in an associative array.

3) expires -     The time that the cookie should expire. When this point is reached, it is deleted                                        from the browser, and is no longer sent back to the server in requests. 
            If this value is set to zero, or omitted, the cookie lasts as long as the browser is                                        running, and is automatically deleted when the browser exits.

4) path  -     The path that the browser should send the cookie back to. If specified, the                                                browser will only send the cookie to URLs that contain this path. For                                                        example, if you specify a path of /admin/, only scripts contained in the                                                    /admin/ folder (and any subfolders) will receive the cookie. If you don’t                                                     specify a value, the current directory of the script is assumed. It's generally                                              a good idea so specify a path. Use a value of “/” if you want the cookie to                                                 be available to all URLs in your Web site.

5) domain -     By default, a browser only sends a cookie back to the exact computer that sent it.                                     For example, if your Web site at www.example.com sets a cookie, the cookie                                        will only be sent back to URLs that begin with http://www.example.com. URLs                                     beginning with http://example.com or http://www2.example.com won't receive                                        the cookie. However, if you set domain to .example.com the browser will send                                        the cookie back to all URLs within this domain, including URLs beginning with                                     http://www.example.com, 
            http://example.com, or http://www2.example.com.

6) secure -     This field, if present, indicates that the cookie should be sent only if the browser                                     has made a secure (https) connection with the server. If it's not present, the
            browser will send the cookie to the server regardless of whether the connection                                        is secure. Omit this field if you're working with standard (http) connections.

7) HttpOnly -     This field, if present, tells the browser that it should make the cookie data                                                accessible only to scripts that run on the Web server (that is, via HTTP).                                                    Attempts to access the cookie via JavaScript within the Web page are rejected.                                        This can help to reduce your application's vulnerability to cross-site scripting                                        (XSS) attacks.


Setting a Cookie in PHP:-
-------------------------------

1) PHP provides a built-in function, setcookie(), that can send the appropriate HTTP header to create        the cookie on the browser.

2) Make sure you call setcookie() before sending any output to the browser. This is because setcookie()     needs to send the Set - Cookie: HTTP header. If you output any content before calling setcookie(), 
    PHP automatically sends the headers first, so by the time setcookie() is called it's too late to send the     Set - Cookie: header.

3) The expires argument uses a PHP function called time().

4) It's a good idea to precede the domain value with a dot ( . ) character, as in “.example. com”, unless        the domain is a hostname such as www.example.com, in which case the initial period should not be        used.

5) setcookie() is used to store the number of page views in the user's current browser session.

6) The expires argument is zero, so the cookie will disappear when the user closes her browser. In addition the domain argument is an empty string, which means the browser will 
    only send the cookie back to the exact Web server that created it:
setcookie( “pageViews”, 7, 0, “/”, “”, false, true );

7) We can also update an existing cookie simply by calling setcookie() with the cookie name and the         new value.

8) We still need to supply the path and expires arguments when updating the cookie:
setcookie( “pageViews”, 8, 0, “/”, “”, false, true );


Accessing Cookies in Your Scripts:
-----------------------------------------

1) We simply read values from the $_COOKIE superglobal array. This associative array contains a list      of all the cookie values sent by the browser in the current request, keyed by cookie name.

2) So to display the pageViews cookie set in the previous example, you could use:
echo $_COOKIE[“pageViews”]; // Displays “8”

3) As with $_GET and $_POST, in a real-world situation you shouldn't directly output data from the        $_COOKIE array without filtering and/or validating it first.

4) It’s important to realize that a newly created cookie isn’t available to your scripts via $_COOKIE        until the next browser request is made. This is because the first time your script is run, it merely            sends the cookie to the browser. The browser doesn’t return the cookie to the server until it next            requests a URL from the server. For example:
setcookie( “pageViews”, 7, 0, “/”, “”, false, true );
echo isset( $_COOKIE[“pageViews”] );


Removing Cookies:-
-------------------------

1) To delete a cookie, you call setcookie() with the cookie name and any value (such as an empty string), and pass in an expires argument that is in the past. This immediately expires the cookie on the
    browser, ensuring that it is deleted.

2) You should also pass exactly the same path, domain, and other fields that you used when you first created the cookie to ensure that the correct cookie is deleted:
setcookie( “fontSize”, “”, time() - 3600, “/”, “.example.com”, false, true );

3) Deleting a cookie via setcookie() doesn’t delete it from the $_COOKIE array while the script is running. However, the next time the browser visits the page, it will no longer send the cookie to the server and the corresponding $_COOKIE array element will not be created.


Drawbacks of Cookies:-
-----------------------------

1) They aren't very secure. As with form data and query strings, an attacker can easily modify a cookie’s contents to insert data that could potentially break your application or compromise security.

2) Although you can store a fair amount of state information in a cookie, remember that all the cookie data for a Web site is sent every time the browser requests a URL on the server. 

    If you have stored 10 cookies, each 4KB in size, on the browser, then the browser needs to upload 40KB of data each time the user views a page.



PHP Sessions:-
-------------------

1) A PHP session stores data on the server, and associates a short session ID string (known as SID) with that data.

2) The PHP engine then sends a cookie containing the SID to the browser to store.

3) Then, when the browser requests a URL on the Web site, it sends the SID cookie back to the server, allowing PHP to retrieve the session data and make it accessible to your script.

4) The session IDs generated by PHP are unique, random, and almost impossible to guess, making it very hard for an attacker to access or change the session data.

5) Furthermore, because the session data is stored on the server, it doesn't have to be sent with each browser request. This allows you to store a lot more data in a session than you can in a cookie.

6) By default, PHP stores each session's data in a temporary file on the server.

7) The location of the temporary files are specified by the session.save_path directive in the PHP configuration file. You can display this value with:
echo ini_get( “session.save_path” );

8) The session files are often stored in /tmp on UNIX or Linux systems, and C:\WINDOWS\Temp on Windows systems.

9) ini_get() lets you access the value of most PHP configuration directives, and ini_set() lets you set directives.

10) In fact, by default, PHP's session cookies are set to expire when the browser is closed.


Creating a Session:-
------------------------

1) To start a PHP session in your script, simply call the session_ start() function.

2) If this is a new session, this function generates a unique SID for the session and sends it to the browser as a cookie called PHPSESSID (by default).

3) However, if the browser has sent a PHPSESSID cookie to the server because a session already exists, session_start() uses this existing session:
session_start();

e.g.-  Hi there!
         < ?php
         // Generates a “Cannot send session cookie - headers already sent” warning
         session_start();
         ? >


Reading and Writing Session Data:-
------------------------------------------

1) We store all your session data as keys and values in the $_SESSION[] superglobal array.
$_SESSION[“firstName”] = “John”;

2) You can store any type of data in sessions, including arrays and objects:
$userDetails = array( “firstName” => “John”, “lastName” => “Smith”, “age” =>34 );
$_SESSION[“userDetails”] = $userDetails;


Destroying a Session:-
---------------------------

1) by default PHP sessions are automatically deleted when users quit their browser, because the PHPSESSID cookie's expires field is set to zero.

2) To destroy a session, you can simply call the built - in session_destroy() function:
session_destroy();

3) However, that this merely erases the session data from the disk. The data is still in the $_SESSION array until the current execution of the script ends. So to make sure that all session data has been erased,
    you should also initialize the $_SESSION array:
$_SESSION = array();
session_destroy();

4) A trace of the session remains in the form of the PHPSESSID cookie in the user's browser. When the user next visits your site, PHP will pick up the PHPSESSID cookie and re-create the
    session (though the session won't contain any data when it's re-created). Therefore, to really make sure that you have wiped the session from both the server and the browser, you should also destroy the
    session cookie:
if ( isset( $_COOKIE[session_name()] ) ) {
setcookie( session_name(), “”, time()-3600, “/” );
}
$_SESSION = array();
session_destroy();

5) PHP actually lets you work with more than one session in the same script by using session_name() to create different named sessions.


Passing Session IDs in Query Strings:-
----------------------------------------------

1) PHP session IDs are saved in cookies.

2) Another alternative is to pass the session ID inside links between the pages of your site.

3) PHP helps to automate this process with the built-in SID constant.

4) If the browser supports cookies, this constant is empty; however, if the session cookie can’t be set on the browser, SID contains a string similar to the following:
PHPSESSID=b8306b025a76a250f0428fc0efd20a11

5) When the user clicks the link to view myscript.php, the PHPSESSID query string value is automatically picked up by the PHP engine and the session data is made available to the script.

6) We need to have called session_start() before trying to access the SID constant.

7) You can also retrieve the current session ID by calling the session_id() function. This allows you, among other things, to embed the session ID in a hidden PHPSESSID field in a form, so that the session can be propagated across form submissions.

Changing Session Behavior:-
-----------------------------------

We can alter PHP's default session-handling behavior in a number of ways. The php.ini file contains several configuration directives that you can alter:
1) session.cookie_lifetime

2) session.cookie_path

3) session.cookie_domain

4) session.cookie_httponly

5) session.auto_start

ini_set( “session.cookie_lifetime”, 1200 ); // Set session timeout to 20 minutes


=> As well as altering session behavior, you can even write your own custom code to store the session data on the server.


Working with Files and Directories:
------------------------------------------

1) Files are stored in directories on a hard drive, and because they retain their data after the computer is shut down, they are a persistent storage mechanism, instead of temporary storage such as RAM.

2) Directories are a special kind of file made for storing other files.

3) Directories are created hierarchically inside other directories, starting with the root (top-level) directory and proceeding down from there.

4) Files can contain any kind of data, and also can contain quite a bit of information about themselves, such as who owns them and when they were created.

5) PHP makes working with the file system easy by including functions that allow you to obtain information about files, as well as open, read from, and write to them.

File:-
-----

A file is nothing more than an ordered sequence of bytes stored on a hard disk or other storage media.

Directories:-
---------------

A directory is a special type of file that holds the names of the files and directories inside the folder (sometimes denoted as subdirectories or subfolders ) and pointers to their storage areas on the media.

6) Windows uses backslashes:
C:\MyDocs\data\data.txt

Time-Related Properties:
------------------------------

1) fileatime() — Returns the time at which the file was last accessed as a UNIX timestamp. A file is considered accessed if its contents are read.

2) filectime() — Returns the time at which the file was last changed as a UNIX timestamp. A file is considered changed if it is created or written, or when its permissions have been changed.

3) filemtime() — Returns the time at which the file was last modified as a UNIX timestamp. The file is considered modified if it is created or has its contents changed.

timestamp:-
-------------

A UNIX timestamp is an integer value indicating the number of seconds between the UNIX epoch (midnight on January 1, 1970) and the specified time and date.

getdate():-
------------

It returns an associative array containing the date information present in a timestamp. The array includes such values as the year, the month, the day of the month, and so on.

Retrieving a Filename from a Path:-
------------------------------------------

It’s often very useful to be able to separate a filename from its directory path, and the basename() function does exactly that, taking a complete file path and returning just the filename. For example, the
following code assigns index.html to $filename :
$filename = basename( “/home/james/docs/index.html” );

You can specify a directory path instead, in which case the rightmost directory name is returned. Here ’ s an example that assigns the value docs to $dir :
$dir = basename( “/home/james/docs” );

=> basename() retrieves the last whole string after the rightmost slash.

Opening and Closing Files:-
----------------------------------

Usually, to work with a file from within your PHP script, you first need to open the file. When you open a file, you create a file handle.

File Handler:-
-----------------

A file handler is a pointer associated with the open file that you can then use to access the file's contents. When you've finished with the file, you close it, which removes the file handle from memory.


0 Comments