Category: 13. Advanced

https://cdn3d.iconscout.com/3d/premium/thumb/3d-software-settings-icon-download-in-png-blend-fbx-gltf-file-formats–setting-configuration-preferences-printing-pack-science-technology-icons-8549424.png?f=webp

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

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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;}</code></pre>

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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;}</code></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. PHP’s 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 it’s not as it doesn’t 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 −

    Open Compiler

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

    Open Compiler

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

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Skipping Array Elements

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

    Open Compiler

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

    Open Compiler

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

    Open Compiler

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

    Open Compiler

    <?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;
    ?>
  • PHP.INI 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 PHP’s 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.

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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 browser’s 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.