PHP

What is PHP?

  • PHP is an acronym for "PHP: Hypertext Preprocessor"
  • PHP is a widely-used, open source scripting language
  • PHP scripts are executed on the server
  • PHP is free to download and use
  • It is also easy enough to be a beginner's first server side language

Reactjs
What is a PHP File?
  • PHP files can contain text, HTML, CSS, JavaScript, and PHP code
  • PHP code is executed on the server, and the result is returned to the browser as plain HTML
  • PHP files have extension ".php"
  • PHP can generate dynamic page content
  • PHP can create, open, read, write, delete, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can be used to control user-access
  • PHP can encrypt data
  • With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML.
  1. Basic PHP Syntax
    Basic PHP Syntax
    A PHP script can be placed anywhere in the document.

    A PHP script starts with :

    The default file extension for PHP files is ".php".
    A PHP file normally contains HTML tags, and some PHP scripting code.

    Note: PHP statements end with a semicolon (;).
                         <?php
                            // PHP code goes here 
                            ?>
                            
    
  2. Comments in PHP
    Comments in PHP
    A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is to be read by someone who is looking at the code.

    Comments can be used to:
    Let others understand your code
    Remind yourself of what you did - Most programmers have experienced coming back to their own work a year or two later and having to re-figure out what they did. Comments can remind you of what you were thinking when you wrote the code
                                         // This is a single-line comment
                                            # This is also a single-line comment
                                            
            
  3. PHP Variables
    PHP Variables
    Variables are "containers" for storing information.


    A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

    Rules for PHP variables:
    A variable starts with the $ sign, followed by the name of the variable
    A variable name must start with a letter or the underscore character
    A variable name cannot start with a number
    A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

    Variable names are case-sensitive ($age and $AGE are two different variables)
                     
                    <?php
    $txt = "Hello world!";
    $x = 5;
    $y = 10.5;
    ?>
                
            
  4. PHP Variables Scope
    PHP Variables Scope
    In PHP, variables can be declared anywhere in the script.
    The scope of a variable is the part of the script where the variable can be referenced/used.

    PHP has three different variable scopes:
    • local
    • global
    • static


    Global and Local Scope
    A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function

    You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

    PHP The global Keyword
    The global keyword is used to access a global variable from within a function.

    The static Keyword
    Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
    1. global Keyword
                  
                          global $x, $y;
              
              
    2. static Keyword
          
              static $x = 0;
      
      
  5. echo and print Statements
    echo and print Statements
    echo and print are more or less the same. They are both used to output data to the screen.

    The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.

    The echo statement can be used with or without parentheses: echo or echo().

    The print statement can be used with or without parentheses: print or print()
    1. echo Statement
                  
                      echo "<h2>PHP is Fun!</h2>";
              
              
    2. print Statement
                  
                      print "I'm about to learn PHP!";
              
              
  6. PHP Data Types
    PHP Data Types
    Variables can store data of different types, and different data types can do different things.

    PHP supports the following data types:
    • String:
      A string is a sequence of characters, like "Hello world!".A string can be any text inside quotes. You can use single or double quote
    • Integer:
      An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

      Rules for integers:
      An integer must have at least one digit
      An integer must not have a decimal point
      An integer can be either positive or negative
      Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
    • Float (floating point numbers - also called double):
      A float (floating point number) is a number with a decimal point or a number in exponential form.
    • Boolean:A Boolean represents two possible states: TRUE or FALSE.
    • Array:An array stores multiple values in one single variable.
    • Object:Classes and objects are the two main aspects of object-oriented programming.

      A class is a template for objects, and an object is an instance of a class.

      When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.
    • NULL:Null is a special data type which can have only one value: NULL.
      A variable of data type NULL is a variable that has no value assigned to it.
      Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
    • Resource:The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP.
      A common example of using the resource data type is a database call.
    1. PHP String

                  
                      $x = "Hello world!";
              
              
    2. PHP Integer

                  
                      $x = 5985;
              
              
    3. PHP Boolean

                  
                      $x = true;
              
              
    4. PHP Array

                  
                      $cars = array("Volvo","BMW","Toyota");
              
              
    5. PHP Object

                  
                      class Car {
                          public $color;
                          public $model;
                          public function __construct($color, $model) {
                            $this->color = $color;
                            $this->model = $model;
                          }
                          $myCar = new Car("black", "Volvo");
              
              
    6. PHP NULL Value

                  
                      $x = null;
              
              
  7. PHP String Functions
    PHP String Functions
    A string is a sequence of characters, like "Hello world!".
    1. strlen() - Return the Length of a String

          
              echo strlen("Hello world!"); // outputs 12
      
      
    2. str_word_count() - Count Words in a String

          
              echo str_word_count("Hello world!"); // outputs 2
      
      
    3. strrev() - Reverse a String

          
              echo strrev("Hello world!"); // outputs !dlrow olleH
      
      
    4. strpos() - Search For a Text Within a String

          
              echo strpos("Hello world!", "world"); // outputs 6 otherwise FALSE
      
      
    5. str_replace() - Replace Text Within a String

          
              echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
      
      
  8. PHP Math
    PHP Math
    PHP has a set of math functions that allows you to perform mathematical tasks on numbers.
    1. pi() Function
                          
                              echo(pi()); // returns 3.1415926535898
                      
                      
    2. min() and max() Functions
                      
                          echo(min(0, 150, 30, 20, -8, -200));  // returns -200
                  echo(max(0, 150, 30, 20, -8, -200));  // returns 150
                  
                  
    3. abs() Function
                      
                          echo(abs(-6.7));  // returns 6.7
                  
                  
    4. sqrt() Function
                      
                          echo(sqrt(64));  // returns 8
                  
                  
    5. round() Function
                      
                          echo(round(0.60));  // returns 1
                  
                  
    6. Random Numbers
                      
                          echo(rand());
                  
                  
  9. PHP Constants
    PHP Constants
    A constant is an identifier (name) for a simple value. The value cannot be changed during the script.

    A valid constant name starts with a letter or underscore (no $ sign before the constant name).
    Parameters: name: Specifies the name of the constant value: Specifies the value of the constant case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false.

    Syntax

        
            define(name, value, case-insensitive)
    
    

    Example

        
            define("GREETING", "Welcome to W3Schools.com!", true);
    echo greeting;
    
    
  10. PHP Operators
    PHP Operators
    Operators are used to perform operations on variables and values.

    PHP divides the operators in the following groups:
    • Arithmetic operators
    • Assignment operators
    • Comparison operators
    • Increment/Decrement operators
    • Logical operators
    • String operators
    • Array operators
    • Conditional assignment operators

    1. Arithmetic operators
      PHP Operators
      Operator Name Example Result
      + Addition $x + $y Sum of $x and $y
      - Subtraction $x - $y Difference of $x and $y
      * Multiplication $x * $y Product of $x and $y
      / Division $x / $y Quotient of $x and $y
      % Modulus $x % $y Remainder of $x divided by $y
      ** Exponentiation $x ** $y Result of raising $x to the $y'th power
    2. Assignment operators
      Assignment operators
      Assignment Same as... Description
      x = y x = y The left operand gets set to the value of the expression on the right
      x += y x = x + y Addition
      x -= y x = x - y Subtraction
      x *= y x = x * y Multiplication
      x /= y x = x / y Division
      x %= y x = x % y Modulus
    3. Comparison operators
      Comparison operators
      Operator Name Example Result
      == Equal $x == $y Returns true if $x is equal to $y
      === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
      != Not equal $x != $y Returns true if $x is not equal to $y
      <> Not equal $x <> $y Returns true if $x is not equal to $y
      !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
      > Greater than $x > $y Returns true if $x is greater than $y
      < Less than $x < $y Returns true if $x is less than $y
      >= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
      <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
      <=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.
    4. Increment/Decrement operators
      Increment/Decrement operators
      Operator Name Description
      ++$x Pre-increment Increments $x by one, then returns $x
      $x++ Post-increment Returns $x, then increments $x by one
      --$x Pre-decrement Decrements $x by one, then returns $x
      $x-- Post-decrement Returns $x, then decrements $x by one
    5. Logical operators
      Logical operators
      Operator Name Example Result
      and And $x and $y True if both $x and $y are true
      or Or $x or $y True if either $x or $y is true
      xor Xor $x xor $y True if either $x or $y is true, but not both
      && And $x && $y True if both $x and $y are true
      || Or $x || $y True if either $x or $y is true
      ! Not !$x True if $x is not true
    6. String operators
      String operators
      Operator Name Example Result
      . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
      .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1
    7. Array operators
      Array operators
      Operator Name Example Result
      + Union $x + $y Union of $x and $y
      == Equality $x == $y Returns true if $x and $y have the same key/value pairs
      === Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
      != Inequality $x != $y Returns true if $x is not equal to $y
      <> Inequality $x <> $y Returns true if $x is not equal to $y
      !== Non-identity $x !== $y Returns true if $x is not identical to $y
    8. Conditional assignment operators
      Conditional assignment operators
      Operator Name Example Result
      ?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
      The value of $x is expr2 if expr1 = TRUE.
      The value of $x is expr3 if expr1 = FALSE
      ?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
      The value of $x is expr1 if expr1 exists, and is not NULL.
      If expr1 does not exist, or is NULL, the value of $x is expr2.
      Introduced in PHP 7
  11. PHP Conditional Statements
    DELETE Statement
    In PHP we have the following conditional statements:
    • if statement - executes some code if one condition is true
    • if...else statement - executes some code if a condition is true and another code if that condition is false
    • if...elseif...else statement - executes different codes for more than two conditions
    • switch statement - selects one of many blocks of code to be executed
    1. The if Statement
                                  
                                      if (condition) {
                                          code to be executed if condition is true;
                                        }
                              
                              
    2. The if...else Statement
                              
                                  if (condition) {
                                      code to be executed if condition is true;
                                    } else {
                                      code to be executed if condition is false;
                                    }
                          
                          
    3. The if...elseif...else Statement
                              
                                  if (condition) {
                                      code to be executed if this condition is true;
                                    } elseif (condition) {
                                      code to be executed if first condition is false and this condition is true;
                                    } else {
                                      code to be executed if all conditions are false;
                                    }
                          
                          
    4. switch Statement
                              
                                  switch (n) {
                                      case label1:
                                        code to be executed if n=label1;
                                        break;
                                      case label2:
                                        code to be executed if n=label2;
                                        break;
                                      case label3:
                                        code to be executed if n=label3;
                                        break;
                                        ...
                                      default:
                                        code to be executed if n is different from all labels;
                                    }
                          
                          
  12. PHP Loops
    PHP Loops
    Often when you write code, you want the same block of code to run over and over again a certain number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.
    Loops are used to execute the same block of code again and again, as long as a certain condition is true.
    In PHP, we have the following loop types:
    • while - loops through a block of code as long as the specified condition is true
    • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
    • for - loops through a block of code a specified number of times

      Parameters:
      init counter: Initialize the loop counter value

      test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

      increment counter: Increases the loop counter value
    • foreach - loops through a block of code for each element in an array
    • Break- It was used to "jump out" of a switch statement.The break statement can also be used to jump out of a loop.
    • Continue - The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
    1. while Loop
                              
                                  while (condition is true) {
                                      code to be executed;
                                    }
                          
                          
    2. do...while Loop
                              
                                  do {
                                      code to be executed;
                                    } while (condition is true);
                          
                          
    3. for Loop
                              
                                  for (init counter; test counter; increment counter) {
                                      code to be executed for each iteration;
                                    }
                          
                          
    4. foreach Loop
                              
                                  foreach ($array as $value) {
                                      code to be executed;
                                    }
                          
                          
    5. Break
                              
                                  for ($x = 0; $x < 10; $x++) {
                                      if ($x == 4) {
                                        break;
                                      }
                                      echo "The number is: $x 
      "; }
    6. Continue
                              
                                  for ($x = 0; $x < 10; $x++) {
                                      if ($x == 4) {
                                        continue;
                                      }
                                      echo "The number is: $x 
      "; }
  13. User Defined Function
    User Defined Function
    Besides the built-in PHP functions, it is possible to create your own functions.

    A function is a block of statements that can be used repeatedly in a program.
    A function will not execute automatically when a page loads.
    A function will be executed by a call to the function.
        
            function functionName() {
                code to be executed;
              }
    
    
  14. PHP Arrays
    PHP Arrays
    An array is a special variable, which can hold more than one value at a time.An array can hold many values under a single name, and you can access the values by referring to an index number.

    In PHP, there are three types of arrays:
    Indexed arrays - Arrays with a numeric index
    Associative arrays - Arrays with named keys
    Multidimensional arrays - Arrays containing one or more arrays



    PHP - Sort Functions For Arrays
    The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.

    sort() - sort arrays in ascending order
    rsort() - sort arrays in descending order
    asort() - sort associative arrays in ascending order, according to the value
    ksort() - sort associative arrays in ascending order, according to the key
    arsort() - sort associative arrays in descending order, according to the value
    krsort() - sort associative arrays in descending order, according to the key

    Function Description
    array() Creates an array
    array_change_key_case() Changes all keys in an array to lowercase or uppercase
    array_chunk() Splits an array into chunks of arrays
    array_column() Returns the values from a single column in the input array
    array_combine() Creates an array by using the elements from one "keys" array and one "values" array
    array_count_values() Counts all the values of an array
    array_diff() Compare arrays, and returns the differences (compare values only)
    array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
    array_diff_key() Compare arrays, and returns the differences (compare keys only)
    array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
    array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
    array_fill() Fills an array with values
    array_fill_keys() Fills an array with values, specifying keys
    array_filter() Filters the values of an array using a callback function
    array_flip() Flips/Exchanges all keys with their associated values in an array
    array_intersect() Compare arrays, and returns the matches (compare values only)
    array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
    array_intersect_key() Compare arrays, and returns the matches (compare keys only)
    array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
    array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)
    array_key_exists() Checks if the specified key exists in the array
    array_keys() Returns all the keys of an array
    array_map() Sends each value of an array to a user-made function, which returns new values
    array_merge() Merges one or more arrays into one array
    array_merge_recursive() Merges one or more arrays into one array recursively
    array_multisort() Sorts multiple or multi-dimensional arrays
    array_pad() Inserts a specified number of items, with a specified value, to an array
    array_pop() Deletes the last element of an array
    array_product() Calculates the product of the values in an array
    array_push() Inserts one or more elements to the end of an array
    array_rand() Returns one or more random keys from an array
    array_reduce() Returns an array as a string, using a user-defined function
    array_replace() Replaces the values of the first array with the values from following arrays
    array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively
    array_reverse() Returns an array in the reverse order
    array_search() Searches an array for a given value and returns the key
    array_shift() Removes the first element from an array, and returns the value of the removed element
    array_slice() Returns selected parts of an array
    array_splice() Removes and replaces specified elements of an array
    array_sum() Returns the sum of the values in an array
    array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)
    array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
    array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)
    array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)
    array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
    array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)
    array_unique() Removes duplicate values from an array
    array_unshift() Adds one or more elements to the beginning of an array
    array_values() Returns all the values of an array
    array_walk() Applies a user function to every member of an array
    array_walk_recursive() Applies a user function recursively to every member of an array
    arsort() Sorts an associative array in descending order, according to the value
    asort() Sorts an associative array in ascending order, according to the value
    compact() Create array containing variables and their values
    count() Returns the number of elements in an array
    current() Returns the current element in an array
    each() Deprecated from PHP 7.2. Returns the current key and value pair from an array
    end() Sets the internal pointer of an array to its last element
    extract() Imports variables into the current symbol table from an array
    in_array() Checks if a specified value exists in an array
    key() Fetches a key from an array
    krsort() Sorts an associative array in descending order, according to the key
    ksort() Sorts an associative array in ascending order, according to the key
    list() Assigns variables as if they were an array
    natcasesort() Sorts an array using a case insensitive "natural order" algorithm
    natsort() Sorts an array using a "natural order" algorithm
    next() Advance the internal array pointer of an array
    pos() Alias of current()
    prev() Rewinds the internal array pointer
    range() Creates an array containing a range of elements
    reset() Sets the internal pointer of an array to its first element
    rsort() Sorts an indexed array in descending order
    shuffle() Shuffles an array
    sizeof() Alias of count()
    sort() Sorts an indexed array in ascending order
    uasort() Sorts an array by values using a user-defined comparison function
    uksort() Sorts an array by keys using a user-defined comparison function
    usort() Sorts an array using a user-defined comparison function
    1. PHP Indexed Arrays
                              
                                  $cars = array("Volvo", "BMW", "Toyota");
                              
                              
    2. Associative Arrays
                              
                                  $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
                              
                              
    3. Multidimensional Arrays
                                  
                                      echo $cars[0][0]
                                  
                                  
  15. PHP - Sort Functions For Arrays
    1. Sort Array in Ascending Order - sort()
                                              
                                                  $cars = array("Volvo", "BMW", "Toyota");
                                                  sort($cars);
                                              
                                              
    2. Sort Array in Descending Order - rsort()
                                              
                                                  $cars = array("Volvo", "BMW", "Toyota");
      rsort($cars);
                                              
                                              
    3. Sort Array (Ascending Order), According to Value - asort()
                                              
                                                  $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
      asort($age);
                                              
                                              
    4. Sort Array (Ascending Order), According to Key - ksort()
                                              
                                                  $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
      ksort($age);
                                              
                                              
    5. Sort Array (Descending Order), According to Value - arsort()
                                              
                                                  $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
                                                  arsort($age);
                                              
                                              
    6. Sort Array (Descending Order), According to Key - krsort()
                                              
                                                  $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
                                                  krsort($age);
                                              
                                              
  16. Superglobals
    Superglobals
    Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

    The PHP superglobal variables are:

    $_SERVER : $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.
    $GLOBALS :$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods).
    PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
    $_REQUEST : PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form.
    $_POST : PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.
    $_GET : PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get".$_GET can also collect data sent in the URL.
    $_FILES
    $_ENV
    $_COOKIE
    $_SESSION
  17. Regular Expression
    Regular Expression
    A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.
    A regular expression can be a single character, or a more complicated pattern.
    Regular expressions can be used to perform all types of text search and text replace operations.

    Regular Expression Functions
    Function Description
    preg_match() Returns 1 if the pattern was found in the string and 0 if not
    preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0
    preg_replace() Returns a new string where matched patterns have been replaced with another string
    1. preg_match()
                              
                                  $str = "Visit W3Schools";
                              $pattern = "/w3schools/i";
                              echo preg_match($pattern, $str); // Outputs 1
                              
                              
    2. preg_match_all()
                              
                                  $str = "The rain in SPAIN falls mainly on the plains.";
                              $pattern = "/ain/i";
                              echo preg_match_all($pattern, $str); // Outputs 4
                              
                              
    3. preg_replace()
                              
                                  $str = "Visit Microsoft!";
                                  $pattern = "/microsoft/i";
                                  echo preg_replace($pattern, "W3Schools", $str); // Outputs "Visit W3Schools!"
                              
                              
  18. Regular Expression Modifiers
    Regular Expression Modifiers
    Modifiers can change how a search is performed.

    Modifier Description
    i Performs a case-insensitive search
    m Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)
    u Enables correct matching of UTF-8 encoded patterns
  19. Regular Expression Patterns
    Regular Expression Patterns
    Expression Description
    [abc] Find one character from the options between the brackets
    [^abc] Find any character NOT between the brackets
    [0-9] Find one character from the range 0 to 9
  20. Metacharacters
    Metacharacters
    Metacharacter Description
    | Find a match for any one of the patterns separated by | as in: cat|dog|fish
    . Find just one instance of any character
    ^ Finds a match as the beginning of a string as in: ^Hello
    $ Finds a match at the end of the string as in: World$
    \d Find a digit
    \s Find a whitespace character
    \b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b
    \uxxxx Find the Unicode character specified by the hexadecimal number xxxx
  21. Quantifiers
    Quantifiers
    Quantifier Description
    n+ Matches any string that contains at least one n
    n* Matches any string that contains zero or more occurrences of n
    n? Matches any string that contains zero or one occurrences of n
    n{x} Matches any string that contains a sequence of X n's
    n{x,y} Matches any string that contains a sequence of X to Y n's
    n{x,} Matches any string that contains a sequence of at least X n's
  22. PHP Form Handling
    PHP Form Handling
    The PHP superglobals $_GET and $_POST are used to collect form-data.

    GET vs. POST
    Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

    Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

    $_GET is an array of variables passed to the current script via the URL parameters.

    $_POST is an array of variables passed to the current script via the HTTP POST method.

    When to use GET? Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
    GET may be used for sending non-sensitive data.
    Note: GET should NEVER be used for sending passwords or other sensitive information!

    When to use POST? Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
    Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
    However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
    Developers prefer POST for sending form data.
    
        <html>
    <body><form action="welcome.php" method="post">
    Name: <input type="text" name="name"><br>
    E-mail: <input type="text" name="email"><br>
    <input type="submit">
    </form></body>
    </html>
    
    
  23. PHP Form Validation
    PHP Form Validation
    The validation rules for the form above are as follows:
    Field Validation Rules
    Name Required. + Must only contain letters and whitespace
    E-mail Required. + Must contain a valid email address (with @ and .)
    Website Optional. If present, it must contain a valid URL
    Comment Optional. Multi-line input field (textarea)
    Gender Required. Must select one
                        
                            <!DOCTYPE HTML>  
                            <html>
                            <head>
                            <style>
                            .error {color: #FF0000;}
                            </style>
                            </head>
                            <body>  
                            
                            <?php
                            // define variables and set to empty values
                            $nameErr = $emailErr = $genderErr = $websiteErr = "";
                            $name = $email = $gender = $comment = $website = "";
                            
                            if ($_SERVER["REQUEST_METHOD"] == "POST") {
                              if (empty($_POST["name"])) {
                                $nameErr = "Name is required";
                              } else {
                                $name = test_input($_POST["name"]);
                                // check if name only contains letters and whitespace
                                if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
                                  $nameErr = "Only letters and white space allowed";
                                }
                              }
                              
                              if (empty($_POST["email"])) {
                                $emailErr = "Email is required";
                              } else {
                                $email = test_input($_POST["email"]);
                                // check if e-mail address is well-formed
                                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                                  $emailErr = "Invalid email format";
                                }
                              }
                                
                              if (empty($_POST["website"])) {
                                $website = "";
                              } else {
                                $website = test_input($_POST["website"]);
                                // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
                                if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
                                  $websiteErr = "Invalid URL";
                                }
                              }
                            
                              if (empty($_POST["comment"])) {
                                $comment = "";
                              } else {
                                $comment = test_input($_POST["comment"]);
                              }
                            
                              if (empty($_POST["gender"])) {
                                $genderErr = "Gender is required";
                              } else {
                                $gender = test_input($_POST["gender"]);
                              }
                            }
                            
                            function test_input($data) {
                              $data = trim($data);
                              $data = stripslashes($data);
                              $data = htmlspecialchars($data);
                              return $data;
                            }
                            ?>
                            
                            <h2>PHP Form Validation Example</h2>
                            <p><span class="error">* required field</span></p>
                            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
                              Name: <input type="text" name="name" value="<?php echo $name;?>">
                              <span class="error">* <?php echo $nameErr;?></span>
                              <br><br>
                              E-mail: <input type="text" name="email" value="<?php echo $email;?>">
                              <span class="error">* <?php echo $emailErr;?></span>
                              <br><br>
                              Website: <input type="text" name="website" value="<?php echo $website;?>">
                              <span class="error"><?php echo $websiteErr;?></span>
                              <br><br>
                              Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
                              <br><br>
                              Gender:
                              <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
                              <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
                              <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other  
                              <span class="error">* <?php echo $genderErr;?></span>
                              <br><br>
                              <input type="submit" name="submit" value="Submit">  
                            </form>
                            
                            <?php
                            echo "<h2>Your Input:</h2>";
                            echo $name;
                            echo "<br>";
                            echo $email;
                            echo "<br>";
                            echo $website;
                            echo "<br>";
                            echo $comment;
                            echo "<br>";
                            echo $gender;
                            ?>
                            
                            </body>
                            </html>