Category: Advanced

  • TryCatch

    In PHP, the keywords try, catch, throw and finally are provided to deal with exceptions. Whereas an Error is an unexpected program result, which cannot be handled by the program itself and the program has to be terminated with die() or setting a custom error handler.

    On the other hand, an exception refers to an unexpected situation which can be handled in such a way that the program may keep running after throwing the exception out of its normal flow.

    An exception can be thrown, and caught with the catch keyword within PHP code. A code block which is potentially prone to exception is surrounded by a try block. Each try must have at least one corresponding catch or finally block.

    Try, Throw, Catch, and Finally

    The four exception related keywords have the following role to play −

    • Try − A block of code where some exception is likely to occur is placed in “try” block. If exception is not triggered, the code continues execution. However, if exception does occur, it is “thrown”. The execution is halted and PHP looks for matching “catch” block. If the exception is not caught, PHP issues a Fatal Error.
    • Throw − Here is how you trigger an exception. Each “throw” must have at least one “catch” or “finally” block.
    • Catch − a block that retrieves an exception and creates an object containing the exception information. Multiple catch blocks can be used to catch different exceptions.
    • Finally − Code within a finally block is always executed after throw or catch block.

    Example

    Here is an example of exception handling technique. The code renders two text fields on the browser and asks the user to enter two numbers for their division to be performed. If the second number (denominator) is 0, an exception is thrown and the program enters the catch block and prints the exception message. Otherwise the result of division is displayed.

    <html><body><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"><h3>First No: <input type="text" name="first"/></h3><h3>Second No: <input type="text" name="second"/></h3><input type="submit" value="Submit" /></form><?php
    
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
         $x = $_POST['first'];
         $y = $_POST['second'];
         echo "$x $y";
         try {
            if ($y == 0) {
               throw new Exception("Division by Zero");
            }
            $z = $x/$y;
            echo "&lt;h3&gt;x = $x y = $y Division = $z&lt;br&gt;";
         }
         catch (Exception $e) {
            echo "&lt;h3&gt; Exception: " . $e-&gt;getMessage();
         }
      }
    ?></body></html>

    It will produce the following output −

    Case 1: x = 10 y = 5 Division = 2
    
    Case 2: x = 10 y = 0
    Exception: Division by Zero
    

    The Exception Class

    PHP throws an object of Exception class. In PHP, Exception class is the base for user exceptions. It implements throwable interface.

    This class defines the following methods −

    getMessage()

    This function returns the Exception message as a string −

    finalpublicException::getMessage():string

    getCode()

    This function returns the exception code as int in Exception −

    finalpublicException::getCode():int

    Take a look at the following example −

    try{thrownewException("Some error message",30);}catch(Exception$e){echo"The exception code is: ".$e->getCode();}

    getFile()

    This function returns the filename in which the exception was created −

    finalpublicException::getFile():string

    Take a look at the following example −

    try{if($y==0){thrownewException("Division by Zero");}$z=$x/$y;echo"<h3>x = $x y = $y Division = $z<br>";}catch(Exception$e){echo"<h3> Exception: ".$e->getMessage()." in ".$e->getFile();}

    It will produce the following output −

    Exception: Division by Zero in C:\xampp\htdocs\hello.php
    

    getLine()

    This function returns the line number where the exception was created −

    finalpublicException::getLine():int

    Example

    Take a look at the following example −

    <?php
       if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
      $x = $_POST['first'];
      $y = $_POST['second'];
      echo "$x $y";
      try {
         if ($y == 0) {
            throw new Exception("Division by Zero");
         }
         $z = $x/$y;
         echo "&lt;h3&gt;x = $x y = $y Division = $z&lt;br&gt;";
      }
      catch (Exception $e) {
         echo "&lt;h3&gt; Exception: " . $e-&gt;getMessage(). " in " . $e-&gt;getLine() . " of " . $e-&gt;getFile();
      }
    } ?>

    It will produce the following output −

    Exception: Division by Zero in 21 of C:\xampp\htdocs\hello.php
    

    Multiple Catch Blocks

    PHP allows a series of catch blocks following a try block to handle different exception cases. Multiple catch blocks may be employed to handle predefined exceptions and errors as well as user defined exceptions.

    Example

    The following example uses catch blocks to process DivisioByZeroError, TypeError, ArgumentCountError and InvalidArgumentException conditions. There is also a catch block to handle general Exception.

    <?php
       declare(strict_types=1);
       function divide(int $a, int $b) : int {
    
      return $a / $b;
    } $a=10; $b=0; try { if (!$b) {
      throw new DivisionByZeroError('Division by zero.');
      if (is_int($a)==FALSE || is_int($b)==FALSE)
      throw new InvalidArgumentException("Invalid type of arguments");
      $result=divide($a, $b);
      echo $result;
    } // if argument types not matching catch (TypeError $x) {
      echo $x-&gt;getMessage();
    } // if denominator is 0 catch (DivisionByZeroError $y) {
      echo $y-&gt;getMessage();
    } // if number of arguments not equal to 2 catch (ArgumentCountError $z) {
      echo $z-&gt;getMessage();
    } // if argument types not matching catch (InvalidArgumentException $i) {
      echo $i-&gt;getMessage();
    } // any uncaught exception catch (Exception $ex) {
      echo $ex-&gt;getMessage();
    } ?>

    To begin with, since denominator is 0, “divide by 0” error will be displayed −

    Division by 0
    

    Set $b=3 which will cause TypeError because divide function is expected to return integer but division results in float.

    divide(): Return value must be of type int, float returned
    

    If just one variable is passed to divide function by changing $res=divide($a); this will result in an ArgumentCountError −

    Too few arguments to function divide(), 1 passed in C:\xampp\htdocs\hello.php on line 16 and exactly 2 expected
    

    If one of arguments is not integer, it is a case of InvalidArgumentException. Change $b to a string −

    Invalid type of arguments
    

    The Finally Block

    finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

    try{if($y==0){thrownewException("Division by Zero");}$z=$x/$y;echo"<h3>x = $x y = $y Division = $z </h3><br>";}catch(Exception$e){echo"<h3> Exception: ".$e->getMessage()."</h3>";}finally{echo"<h3>End of try - catch - finally</h3>";}

    It will produce the following output −

    Case 1 −

    x = 10 y = 5 Division = 2
    End of try - catch  finally
    

    Case 2 −

    X=10 y=0
    Exception: Division by Zero
    End of try - catch  finally
    

    Finally With Return

    There is a peculiar behaviour of finally block when either try block or catch block (or both) contain a return statement. Normally a return statement causes the control of program to go back to the calling position. However, in case of a function with try/catch block with return, the statements in finally block are executed first before returning.

    Example

    In the following example, the div() function has a “try-catch-finally” construct. The try block without exception returns result of division. In case of exception, the catch block returns an error message. However, in either case, the statement in the finally block is executed first.

    <?php
       function div($x, $y) {
    
      try {
         if ($y==0)
         throw new Exception("Division by 0");
         else
         $res=$x/$y;;
         return $res;
      } 
      catch (Exception $e) {
         return $e-&gt;getMessage();
      }
      finally {
         echo "This block is always executed\n";
      }
    } $x=10; $y=0; echo div($x,$y); ?>

    It will produce the following output −

    This block is always executed
    Division by 0

  • Error Handling

    Error handling in PHP refers to the making a provision in PHP code to effectively identifying and recovering from runtime errors that the program might come across. In PHP, the errors are handled with the help of −

    • The die() function
    • The Error Handler Function

    The die() Function

    The die() function is an alias of exit() in PHP. Both result in termination of the current PHP script when encountered. An optional string if specified in the parenthesis, will be output before the program terminates.

    die("message");

    Example

    The following code is a typical usage of die() in a PHP script. It displays the File not found message if PHP doesnt find a file, otherwise proceeds to open it for subsequent processing.

    <?php
       if(!file_exists("nosuchfile.txt")) {
    
      die("File not found");
    } else {
      $file = fopen("nosuchfile","r");
      print "Opend file sucessfully";
      // Rest of the code here.
      fclose($file);
    } ?>

    It will produce the following output −

    File not found
    

    Using above technique, you can stop your program whenever it errors out and display more meaningful and user friendly message, rather than letting PHP generate fatal error message.

    The Error Handler Function

    Using die() for error handling is considered an ungainly and poor program design, as it results in an ugly experience for site users. PHP offers a more elegant alternative with which you can define a custom function and nominate it for handling the errors.

    The set_error_handler() function has the following parameters −

    set_error_handler(?callable$callback,int$error_levels=E_ALL):?callable

    The first parameter is a user defined function which is called automatically whenever an error is encountered.

    The custom error handler callback function should have the following parameters −

    handler(int$errno,string$errstr,string$errfile=?,int$errline=?,array$errcontext=?):bool

    Parameters

    ParameterImportanceDescription
    errnoRequiredIt specifies the error level for the user-defined error. It must be numerical value.
    errstrRequiredIt specifies the error message for the user-defined error.
    errfileOptionalIt specifies the filename in which the error occurred.
    errlineOptionalIt specifies the line number at which the error occurred.
    errcontextOptionalIt specifies an array containing variables and their values in use when the error occurred.

    If the callback function returns false, the default error will be called.

    The $errno is an integer corresponding to the predefined error levels.

    Sr.NoConstant & DescriptionValue
    1E_ERROR (int)Fatal run-time errors that can not be recovered from. Execution of the script is halted.1
    2E_WARNING (int)Run-time warnings (non-fatal errors). Execution of the script is not halted.2
    3E_PARSE (int)Compile-time parse errors. Parse errors should only be generated by the parser.4
    4E_NOTICE (int)Run-time notices. Something that could indicate an error, but could also happen in the normal course of running a script.8
    5E_CORE_ERROR (int)Fatal errors that occur during PHP’s initial startup. This is like an E_ERROR16
    6E_CORE_WARNING (int)Warnings (non-fatal errors) that occur during PHP’s initial startup. This is like an E_WARNING,32
    7E_COMPILE_ERROR (int)Fatal compile-time errors. This is like an E_ERROR.64
    8E_COMPILE_WARNING (int)Compile-time warnings (non-fatal errors). This is like an E_WARNING.128
    9E_USER_ERROR (int)User-generated error message. This is like an E_ERROR, generated in PHP code by using the PHP function trigger_error().256
    10E_USER_WARNING (int)User-generated warning message. This is like an E_WARNING, generated in PHP code by using the function trigger_error().512
    11E_USER_NOTICE (int)User-generated notice message. This is like an E_NOTICE generated in PHP code by using the function trigger_error().1024
    12E_STRICT (int)Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.2048
    13E_RECOVERABLE_ERROR (int)Catchable fatal error. If the error is not caught by a user defined handler, the application aborts as it was an E_ERROR.4096
    14E_DEPRECATED (int)Run-time notices. Enable this to receive warnings about code that will not work in future versions.8192
    15E_USER_DEPRECATED (int)User-generated warning message. This is like an E_DEPRECATED, generated in PHP code by using the function trigger_error().16384
    16E_ALL (int)All errors, warnings, and notices.32767

    Example

    Take a look at the following example −

    <?php
       error_reporting(E_ERROR);
    
       function myerrorhandler($errno, $errstr) {
    
      echo "error No: $errno Error message: $errstr" . PHP_EOL;
      echo "Terminating PHP script"; 
      die();
    } set_error_handler("myerrorhandler"); $f = fopen("nosuchfile.txt", "r"); echo "file opened successfully"; // rest of the code fclose($f); ?>

    It will produce the following output −

    error No: 2 Error message: fopen(nosuchfile.txt): Failed to open stream: No 
    such file or directory
    Terminating PHP script
    

    PHPs error class hierarchy starts from throwable interface. All the predefined Error classes in PHP are inherited from Error class.

    The ArithmeticError Class

    The ArithmeticError class is inherited from the Error class. This type of error may occur while performing certain mathematical operations such as performing bitwise shift operation by negative amount.

    Example

    Take a look at the following example −

    <?php
       try {
    
      $a = 10;
      $b = -3;
      $result = $a &lt;&lt; $b;
    } catch (ArithmeticError $e) {
      echo $e-&gt;getMessage(); 
    } ?>

    It will produce the following output −

    Bit shift by negative number
    

    This error is also thrown when call to intdiv() function results in value such that it is beyond the legitimate boundaries of integer.

    Example

    Take a look at the following example −

    <?php
       try {
    
      $a = PHP_INT_MIN;
      $b = -1;
      $result = intdiv($a, $b);
      echo $result;
    } catch (ArithmeticError $e) {
      echo $e-&gt;getMessage(); 
    } ?>

    It will produce the following output −

    Division of PHP_INT_MIN by -1 is not an integer
    

    DivisionByZeroError

    DivisionByZeroError class is a subclass of ArithmeticError class. This type of error occurs when value of denominator is zero in the division operation.

    Example: Modulo by Zero

    Take a look at the following example:

    <?php
       try {
    
      $a = 10;
      $b = 0;
      $result = $a%$b;
      echo $result;
    } catch (DivisionByZeroError $e) {
      echo $e-&gt;getMessage(); 
    } ?>

    It will produce the following output −

    Modulo by zero
    

    This can also occur when a modulo operator (%) has 0 as second operator, and intdiv() function having second argument as 0.

    Example: Division by Zero

    Take a look at the following example −

    <?php
       try {
    
      $a = 10;
      $b = 0;
      $result = $a/$b;
      echo $result;
    } catch (DivisionByZeroError $e) {
      echo $e-&gt;getMessage(); 
    } ?>

    It will produce the following output −

    Division by zero 
    

    ArgumentCountError

    PHP parser throws ArgumentCountError when arguments passed to a user defined function or method are less than those in its definition.

    Example

    Take a look at the following example −

    <?php
       function add($x, $y) {
    
      return $x+$y;
    } try {
      echo add(10);
    } catch (ArgumentCountError $e) {
      echo $e-&gt;getMessage();
    } ?>

    It will produce the following output −

    Too few arguments to function add(), 1 passed in C:\xampp\php\test.php on line 9 and exactly 2 expected
    

    TypeError

    This error is raised when actual and formal argument types don’t match, return type doesn’t match the declared returned type.

    Example

    Take a look at the following example −

    <?php
       function add(int $first, int $second) {
    
      echo "addition: " . $first + second;
    } try {
      add('first', 'second');
    } catch (TypeError $e) {
      echo $e-&gt;getMessage(), "";
    } ?>

    It will produce the following output −

    add(): Argument #1 ($first) must be of type int, string given, 
       called in /home/cg/root/63814/main.php on line 7
    

    TypeError is also thrown when PHP’s built-in function is passed incorrect number of arguments. However, the “strict_types=1” directive must be set in the beginning.

    Example

    Take a look at the following example −

    <?php
       declare(strict_types=1);
       try {
    
      echo pow(100,2,3);
    } catch (TypeError $e) {
      echo $e-&gt;getMessage(), "";
    } ?>

    It will produce the following output −

    pow() expects exactly 2 parameters, 3 given
    

    Exceptions Handling in PHP

    PHP has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling.

    Lets explain there new keyword related to exceptions.

    • 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 − A “catch” block retrieves an exception and creates an object containing the exception information.

    When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …

    • An exception can be thrown, and caught (“catched”) within PHP. Code may be surrounded in a try block.
    • Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.
    • Exceptions can be thrown (or re-thrown) within a catch block.

    Example

    Following is the piece of code, copy and paste this code into a file and verify the result.

    <?php
       try {
    
      $error = 'Always throw this error';
      throw new Exception($error);
      
      // Code following an exception is not executed.
      echo 'Never executed';
    }catch (Exception $e) {
      echo 'Caught exception: ',  $e-&gt;getMessage(), "";
    } // Continue execution echo 'Hello World'; ?>

    In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class.

    • getMessage() − message of exception
    • getCode() − code of exception
    • getFile() − source filename
    • getLine() − source line
    • getTrace() − n array of the backtrace()
    • getTraceAsString() − formated string of trace

    Creating Custom Exception Handler

    You can define your own custom exception handler. Use following function to set a user-defined exception handler function.

    stringset_exception_handler(callback$exception_handler)

    Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().

    Example

    Take a look at the following example −

    <?php
       function exception_handler($exception) {
    
      echo "Uncaught exception: " , $exception-&gt;getMessage(), "\n";
    } set_exception_handler('exception_handler'); throw new Exception('Uncaught Exception'); echo "Not Executed"; ?>

    Check complete set of error handling functions at PHP Error Handling Functions

  • Regular Expressions

    Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality.

    Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks.

    PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of regular expression. You can use any of them based on your comfort.

    • POSIX Regular Expressions
    • PERL Style Regular Expressions

    POSIX Regular Expressions

    The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various elements (operators) are combined to form more complex expressions.

    The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or bag.

    Lets give explanation for few concepts being used in POSIX regular expression. After that we will introduce you with regular expression related functions.

    Brackets

    Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.

    Sr.NoExpression & Description
    1[0-9]It matches any decimal digit from 0 through 9.
    2[a-z]It matches any character from lower-case a through lowercase z.
    3[A-Z]It matches any character from uppercase A through uppercase Z.
    4[a-Z]It matches any character from lowercase a through uppercase Z.

    The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.

    Quantifiers

    The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a character sequence.

    Sr.NoExpression & Description
    1p+It matches any string containing at least one p.
    2p*It matches any string containing zero or more p’s.
    3p?It matches any string containing zero or one p’s.
    4p{N}It matches any string containing a sequence of N p’s
    5p{2,3}It matches any string containing a sequence of two or three p’s.
    6p{2, }It matches any string containing a sequence of at least two p’s.
    7p$It matches any string with p at the end of it.
    8^pIt matches any string with p at the beginning of it.

    Examples

    Following examples will clear your concepts about matching characters.

    Sr.NoExpression & Description
    1[^a-zA-Z]It matches any string not containing any of the characters ranging from a through z and A through Z.
    2p.pIt matches any string containing p, followed by any character, in turn followed by another p.
    3^.{2}$It matches any string containing exactly two characters.
    4<b>(.*)</b>It matches any string enclosed within <b> and </b>.
    5p(hp)*It matches any string containing a p followed by zero or more instances of the sequence php.

    Predefined Character Ranges

    For your programming convenience several predefined character ranges, also known as character classes, are available. Character classes specify an entire range of characters, for example, the alphabet or an integer set −

    Sr.NoExpression & Description
    1[[:alpha:]]It matches any string containing alphabetic characters aA through zZ.
    2[[:digit:]]It matches any string containing numerical digits 0 through 9.
    3[[:alnum:]]It matches any string containing alphanumeric characters aA through zZ and 0 through 9.
    4[[:space:]]It matches any string containing a space.

    PHP’s Regexp POSIX Functions

    PHP currently offers seven functions for searching strings using POSIX-style regular expressions −

    Sr.NoFunction & Description
    1ereg()The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.
    2ereg_replace()The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found.
    3eregi()The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive.
    4eregi_replace()The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.
    5split()The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.
    6spliti()The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive.
    7sql_regcase()The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a bracketed expression containing two characters.

    PERL Style Regular Expressions

    Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced in the previous POSIX section.

    Lets give explanation for few concepts being used in PERL regular expressions. After that we will introduce you wih regular expression related functions.

    Meta characters

    A meta character is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.

    For instance, you can search for large money sums using the ‘\d’ meta character: /([\d]+)000/, Here \d will search for any string of numerical character.

    Following is the list of meta characters which can be used in PERL Style Regular Expressions.

    Character		Description
    .              a single character
    \s             a whitespace character (space, tab, newline)
    \S             non-whitespace character
    \d             a digit (0-9)
    \D             a non-digit
    \w             a word character (a-z, A-Z, 0-9, _)
    \W             a non-word character
    [aeiou]        matches a single character in the given set
    [^aeiou]       matches a single character outside the given set
    (foo|bar|baz)  matches any of the alternatives specified
    

    Modifiers

    Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in multiple lines etc.

    Modifier	Description
    i 	Makes the match case insensitive
    m 	Specifies that if the string has newline or carriage
    	return characters, the ^ and $ operators will now
    	match against a newline boundary, instead of a
    	string boundary
    o 	Evaluates the expression only once
    s 	Allows use of . to match a newline character
    x 	Allows you to use white space in the expression for clarity
    g 	Globally finds all matches
    cg 	Allows a search to continue even after a global match fails
    

    PHP’s Regexp PERL Compatible Functions

    PHP offers following functions for searching strings using Perl-compatible regular expressions −

    Sr.NoFunction & Description
    1preg_match()The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
    2preg_match_all()The preg_match_all() function matches all occurrences of pattern in string.
    3preg_replace()The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
    4preg_split()The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
    5preg_grep()The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
    6preg_ quote()Quote regular expression characters
  • Coding Standard

    Every company follows its own coding standard based on its best practices. Coding standard is required because there may be many developers working on different modules so if they will start inventing their own standards then source will become very un-manageable and it will become difficult to maintain that source code in future.

    Here are some reasons why one should use coding specifications −

    • Your peer programmers have to understand the code you produce. A coding standard acts as the blueprint for all the team to decipher the code.
    • Simplicity and clarity achieved by consistent coding saves you from common mistakes.
    • If you revise your code after some time then it becomes easy to understand that code.
    • Following a uniform coding standard brings more quality in software.

    There are few guidelines which can be followed while coding in PHP.

    Indenting and Line Length

    Use an indent of 4 spaces and don’t use any tab because different computers use different setting for tab. It is recommended to keep lines at approximately 75-85 characters long for better code readability.

    Control Structures

    These include if, for, while, switch, etc. Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. You are strongly encouraged to always use curly braces even in situations where they are technically optional.

    Examples

    if((condition1)||(condition2)){
       action1;}elseif((condition3)&&(condition4)){
       action2;}else{default action;}

    You can write the switch statements as follows:

    switch(condition){case1:
    
      action1;break;case2:
      action2;break;default:
      defaultaction;break;}</pre>

    Function Calls

    Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example −

    $var=foo($bar,$baz,$quux);

    Function Definitions

    Function declarations follow the "BSD/Allman style" −

    functionfooFunction($arg1,$arg2=''){if(condition){
    
      statement;}return$val;}</pre>

    Comments

    C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is allowed but discouraged.

    PHP Code Tags

    Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PHP compliance and is also the most portable way to include PHP code on differing operating systems and setups.

    Variable Names

    • Use all lower case letters
    • Use '_' as the word separator.
    • Global variables should be prepended with a 'g'.
    • Global constants should be all caps with '_' separators.
    • Static variables may be prepended with 's'.

    Make Functions Reentrant

    Functions should not keep static variables that prevent a function from being reentrant.

    Alignment of Declaration Blocks

    Block of declarations should be aligned.

    One Statement Per Line

    There should be only one statement per line unless the statements are very closely related.

    Short Methods or Functions

    Methods should limit themselves to a single page of code.

    There could be many more points which should be considered while writing your PHP program. Over all intention should be to be consistent throughout of the code programming and it will be possible only when you will follow any coding standard. You can device your own standard if you like something different.

  • Array Destructuring

    In PHP, the term Array destructuring refers to the mechanism of extracting the array elements into individual variables. It can also be called unpacking of array. PHPs list() construct is used to destrucrure the given array assign its items to a list of variables in one statement.

    list($var1,$var2,$var3,...)=array(val1, val2, val3,...);

    As a result, val1 is assigned to $var1, val2 to $var2 and so on. Even though because of the parentheses, you may think list() is a function, but its not as it doesnt have return value. PHP treats a string as an array, however it cannot be unpacked with list(). Moreover, the parenthesis in list() cannot be empty.

    Instead of list(), you can also use the square brackets [] as a shortcut for destructuring the array.

    [$var1,$var2,$var3,...]=array(val1, val2, val3,...);

    Example

    Take a look at the following example −

    <?php
       $marks = array(50, 56, 70);
       list($p, $c, $m) = $marks;
       echo "Physics: $p  Chemistry: $c  Maths: $m" . PHP_EOL;
    
       # shortcut notation
       [$p, $c, $m] = $marks;
       echo "Physics: $p  Chemistry: $c  Maths: $m" . PHP_EOL;
    ?>

    It will produce the following output −

    Physics: 50  Chemistry: 56  Maths: 70
    Physics: 50  Chemistry: 56  Maths: 70
    

    Destructuring an Associative Array

    Before PHP 7.1.0, list() only worked on numerical arrays with numerical indices start at 0. PHP 7.1, array destructuring works with associative arrays as well.

    Let us try to destructure (or unpack) the following associative array, an array with non-numeric indices.

    $marks=array('p'=>50,'c'=>56,'m'=>70);

    To destructure this array the list() statement associates each array key with a independent variable.

    list('p'=>$p,'c'=>$c,'m'=>$m)=$marks;

    Instead, you can also use the [] alternative destructuring notation.

    ['p'=>$p,'c'=>$c,'m'=>$m]=$marks;

    Try and execute the following PHP script −

    <?php
       $marks = array('p'=>50, 'c'=>56, 'm'=>70);
       list('p'=>$p, 'c'=>$c, 'm'=>$m) = $marks;
       echo "Physics: $p  Chemistry: $c  Maths: $m" . PHP_EOL;
    
       # shortcut notation
       ['p'=>$p, 'c'=>$c, 'm'=>$m] = $marks;
       echo "Physics: $p  Chemistry: $c  Maths: $m" . PHP_EOL;
    ?>

    Skipping Array Elements

    In case of an indexed array, you can skip some of its elements in assign only others to the required variables

    <?php
       $marks = array(50, 56, 70);
       list($p, , $m) = $marks;
       echo "Physics: $p  Maths: $m" . PHP_EOL;
    
       # shortcut notation
       [$p, , $m] = $marks;
       echo "Physics: $p  Maths: $m" . PHP_EOL;
    ?>

    In case of an associative array, since the indices are not incremental starting from 0, it is not necessary to follow the order of elements while assigning.

    <?php
       $marks = array('p'=>50, 'c'=>56, 'm'=>70);
       list('c'=>$c, 'p'=>$p, 'm'=>$m) = $marks;
       echo "Physics: $p  Chemistry: $c  Maths: $m" . PHP_EOL;
    
       ['c'=>$c, 'm'=>$m, 'p'=>$p] = $marks;		# shortcut notation
       echo "Physics: $p  Chemistry: $c  Maths: $m" . PHP_EOL;
    ?>

    Destructuring a Nested Array

    You can extend the concept of array destructuring to nested arrays as well. In the following example, the subarray nested inside is an indexed array.

    <?php
       $marks = ['marks' => [50, 60, 70]];
       ['marks' => [$p, $c, $m]] = $marks;
       echo "Physics: $p  Chemistry: $c  Maths: $m" . PHP_EOL;
    ?>

    Destructuring works well even if the nested array is also an associative array.

    <?php
       $marks = ['marks' => ['p'=>50, 'c'=>60, 'm'=>70]];
       ['marks' => ['p'=>$p, 'c'=>$c, 'm'=>$m]] = $marks;
       echo "Physics: $p  Chemistry: $c  Maths: $m" . PHP_EOL;
    ?>

  • File Configuration

    On installing PHP software on your machine, php.ini is created in the installation directory. In case of XAMPP, php.ini is found in c:\xamm\php folder. It is an important configuration file that controls the performance and sets all the PHP related parameters.

    The phpinfo() function displays a list of different parameters and their current values of PHP, Aache, MySQL and other parts of the web server installation.

    Run the following code to display the settings, one of which shows the path to the “php.ini” file:

    <?php
       echo phpinfo();
    ?>

    Loaded Configuration File

    Locate the Loaded Configuration File setting that displays the location of php.ini file

    C:\xampp\php\php.ini
    

    Different aspects of PHPs behaviour are configured by a large number of parameters (called directives). The “php.ini” file comes with most of the lines starting with semicolon (;) symbol indicating that the line is commented. The uncommented line is actually the effective directive and its value. In other words, to activate and assign a value to a particular directive, remove the leading semicolon.

    directive = value
    

    Directive names are *case sensitive. Directives are variables used to configure PHP or PHP extensions. Note that there is no name validation, so if an expected directive is not found a default value will be used, which can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one of the INI constants (On, Off, True, False, Yes, No and None).

    Actually, the C:\XAMPP\PHP folder contains two INI files, one to be used in production environment and other in development environment.

    The php.ini-development.ini is very similar to its production variant, except it is much more verbose when it comes to errors. In development stage, copy this as php.ini to be able to trace the bugs in the code. Once the code is ready for deployment, use php.ini-production.ini file as the effective php.ini file, which essentially supress the error messages to a large extent.

    The directives in php.ini are divided in different categories, like Error handling, data handling, path and directories, file uploads, PHP extensions and module settings.

    Here is a list of some of the important directives in “php.ini” file:

    short_open_tag = Off

    Short open tags look like this: <? ?>. This option must be set to Off if you want to use XML functions.

    safe_mode = Off

    If this is set to On, you probably compiled PHP with the –enable-safe-mode flag. Safe mode is most relevant to CGI use. See the explanation in the section “CGI compile-time options”. earlier in this chapter.

    safe_mode_exec_dir = [DIR]

    This option is relevant only if safe mode is on; it can also be set with the –with-exec-dir flag during the Unix build process. PHP in safe mode only executes external binaries out of this directory. The default is /usr/local/bin. This has nothing to do with serving up a normal PHP/HTML Web page.

    safe_mode_allowed_env_vars = [PHP_]

    This option sets which environment variables users can change in safe mode. The default is only those variables prepended with “PHP_”. If this directive is empty, most variables are alterable.

    safe_mode_protected_env_vars = [LD_LIBRARY_PATH]

    This option sets which environment variables users can’t change in safe mode, even if safe_mode_allowed_env_vars is set permissively

    disable_functions = [function1, function2…]

    A welcome addition to PHP4 configuration and one perpetuated in PHP5 is the ability to disable selected functions for security reasons. Previously, this necessitated hand-editing the C code from which PHP was made. Filesystem, system, and network functions should probably be the first to go because allowing the capability to write files and alter the system over HTTP is never such a safe idea.

    max_execution_time = 30

    The function set_time_limit() won.t work in safe mode, so this is the main way to make a script time out in safe mode. In Windows, you have to abort based on maximum memory consumed rather than time. You can also use the Apache timeout setting to timeout if you use Apache, but that will apply to non-PHP files on the site too.

    error_reporting = E_ALL & ~E_NOTICE

    The default value is E_ALL & ~E_NOTICE, all errors except notices. Development servers should be set to at least the default; only production servers should even consider a lesser value

    error_prepend_string = [“”]

    With its bookend, error_append_string, this setting allows you to make error messages a different color than other text, or what have you.

    warn_plus_overloading = Off

    This setting issues a warning if the + operator is used with strings, as in a form value.

    variables_order = EGPCS

    This configuration setting supersedes gpc_order. Both are now deprecated along with register_globals. It sets the order of the different variables: Environment, GET, POST, COOKIE, and SERVER (aka Built-in). You can change this order around.

    Variables will be overwritten successively in left-to-right order, with the rightmost one winning the hand every time. This means if you left the default setting and happened to use the same name for an environment variable, a POST variable, and a COOKIE variable, the COOKIE variable would own that name at the end of the process. In real life, this doesn’t happen much.

    register_globals = Off

    This setting allows you to decide whether you wish to register EGPCS variables as global. This is now deprecated, and as of PHP4.2, this flag is set to Off by default. Use superglobal arrays instead. All the major code listings in this book use superglobal arrays.

    magic_quotes_gpc = On

    This setting escapes quotes in incoming GET/POST/COOKIE data. If you use a lot of forms which possibly submit to themselves or other forms and display form values, you may need to set this directive to On or prepare to use addslashes() on string-type data.

    magic_quotes_runtime = Off

    This setting escapes quotes in incoming database and text strings. Remember that SQL adds slashes to single quotes and apostrophes when storing strings and does not strip them off when returning them. If this setting is Off, you will need to use stripslashes() when outputting any type of string data from a SQL database. If magic_quotes_sybase is set to On, this must be Off.

    magic_quotes_sybase = Off

    This setting escapes single quotes in incoming database and text strings with Sybase-style single quotes rather than backslashes. If magic_quotes_runtime is set to On, this must be Off.

    auto-prepend-file = [path/to/file]

    If a path is specified here, PHP must automatically include() it at the beginning of every PHP file. Include path restrictions do apply.

    auto-append-file = [path/to/file]

    If a path is specified here, PHP must automatically include() it at the end of every PHP file.unless you escape by using the exit() function. Include path restrictions do apply.

    include_path = [DIR]

    If you set this value, you will only be allowed to include or require files from these directories. The include directory is generally under your document root; this is mandatory if you.re running in safe mode. Set this to . in order to include files from the same directory your script is in. Multiple directories are separated by colons: .:/usr/local/apache/htdocs:/usr/local/lib.

    doc_root = [DIR]

    If you are using Apache, you have already set a document root for this server or virtual host in httpd.conf. Set this value here if you.re using safe mode or if you want to enable PHP only on a portion of your site (for example, only in one subdirectory of your Web root).

    file_uploads = [on/off]

    Turn on this flag if you will upload files using PHP script.

    upload_tmp_dir = [DIR]

    Do not comment this line unless you understand the implications of HTTP uploads!

    session.save-handler = files

    Except in rare circumstances, you will not want to change this setting. So don’t touch it.

    ignore_user_abort = [On/Off]

    This setting controls what happens if a site visitor clicks the browsers Stop button. The default is On, which means that the script continues to run to completion or timeout. If the setting is changed to Off, the script will abort. This setting only works in module mode, not CGI.

    mysql.default_host = hostname

    The default server host to use when connecting to the database server if no other host is specified.

    mysql.default_user = username

    The default user name to use when connecting to the database server if no other name is specified.

    mysql.default_password = password

    The default password to use when connecting to the database server if no other password is specified.

  • MySQL

    PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database.

    What you should already have ?

    • You have gone through MySQL tutorial to understand MySQL Basics.
    • Downloaded and installed a latest version of MySQL.
    • Created database user guest with password guest123.
    • If you have not created a database then you would need root user and its password to create a database.

    We have divided this chapter in the following sections −

    • Connecting to MySQL database − Learn how to use PHP to open and close a MySQL database connection.
    • Create MySQL Database Using PHP − This part explains how to create MySQL database and tables using PHP.
    • Delete MySQL Database Using PHP − This part explains how to delete MySQL database and tables using PHP.
    • Insert Data To MySQL Database − Once you have created your database and tables then you would like to insert your data into created tables. This session will take you through real example on data insert.
    • Retrieve Data From MySQL Database − Learn how to fetch records from MySQL database using PHP.
    • Using Paging through PHP − This one explains how to show your query result into multiple pages and how to create the navigation link.
    • Updating Data Into MySQL Database − This part explains how to update existing records into MySQL database using PHP.
    • Deleting Data From MySQL Database − This part explains how to delete or purge existing records from MySQL database using PHP.
    • Using PHP To Backup MySQL Database − Learn different ways to take backup of your MySQL database for safety purpose.