If you have a prior knowledge of C programming, learning PHP becomes a lot easier, especially the basics. Although PHP is a lot like C, it is bundled with a whole lot of Web-specific libraries, with everything hooked up directly to your favorite Web server. The simplest way to think of PHP is as interpreted C that you can embed in HTML documents. PHP script can also be executed from the command line, much like a C program. The syntax of statements and function definitions should be familiar, except that variables are always preceded by $, and functions do not require separate prototypes. Let us take a look at some of the similarities and differences in PHP and C − Similarities Between C and PHP Syntax − Broadly speaking, PHP syntax is the same as in C, which is what makes learning PHP easier, if you are already conversant with C. Similar to C, PHP Code is blank insensitive, statements are terminated with semicolons. function calls have the same structure Curly brackets are used to put multiple statements into blocks. PHP supports C and C++-style comments (/* */ as well as //), and also Perl and shell-script style (#). Operators − The assignment operators (=, +=, *=, and so on), the Boolean operators (&&, ||, !), the comparison operators (<,>, <=, >=, ==, !=), and the basic arithmetic operators (+, -, *, /, %) all behave in PHP as they do in C. Control Structures − The basic control structures (if, switch, while, for) behave as they do in C, including supporting break and continue. One notable difference is that switch in PHP can accept strings as case identifiers. PHP also has foreach looping construct that traverses the collections such as arrays. Function Names − As you peruse the documentation, you.ll see many function names that seem identical to C functions. Differences Between C and PHP Dollar Sign − All variable names are prefixed with a leading $. Variables do not need to be declared in advance of assignment, and they have no intrinsic type. PHP is a dynamically typed language, as against C being a statically typed language. Types − PHP has only two numerical types: integer (corresponding to a long in C) and double (corresponding to a double in C). In PHP, float is synonymous to double. Strings are of arbitrary length. There is no separate char type in PHP, as is the case in C. Type Conversion − C is a strongly typed language, as type of a variable must be declared before using, and the types are checked at compile time. PHP on the other hand, is a weakly typed language, types are not checked at compile time, and type errors do not typically occur at runtime either. Instead, variables and values are automatically converted across types as needed. Arrays − Arrays have a syntax superficially similar to C’s array syntax, but they are implemented completely differently. In C, an array is a collection of similar data types. In a PHP array, the items may be of different types. PHP arrays are actually associative arrays or hashes, and the index can be either a number or a string. They do not need to be declared or allocated in advance. No Struct Type − The struct keyword in C is used to define a new data type. There is no struct keyword or its equivalent in PHP, partly because the array and object types together make it unnecessary. The elements of a PHP array need not be of a consistent type. No Pointers − Pointers are an important concept in C. There are no pointers available in PHP, although the tapeless variables play a similar role. Unlike C, PHP does support variable references. You can also emulate function pointers to some extent, in that function names can be stored in variables and called by using the variable rather than a literal name. No Prototypes − Functions do not need to be declared before their implementation is defined, as long as the definition can be found somewhere in the current code file or included files. On the contrary, a C function must defined before it is used. No main() − In a C program, the main() function is the entry point, irrespective of where it is present in the code. A PHP program on the other hand starts execution from the first statement in the script Memory Management − The PHP engine is effectively a garbage-collected environment (reference-counted), and in small scripts there is no need to do any deallocation. You should freely allocate new structures – such as new strings and object instances. IN PHP5, it is possible to define destructor for objects, but there is are no free or delete keywords as in C/C++. Destructor are called when the last reference to an object goes away, before the memory is reclaimed. Compilation and Linking − PHP is an interpreted language. Hence, the compiled version of PHP script is not created. A C program is first compiled to obtain the object code, which is then linked to the required libraries to build an executable. There is no separate compilation step for PHP scripts. A PHP script cannot be turned into a self executable. Permissiveness − As a general matter, PHP is more forgiving than C (especially in its type system) and so will let you get away with new kinds of mistakes. Unexpected results are more common than errors.
Bugs Debugging
A bug in a PHP code refers to an error in the program that leads to unexpected results or crash. A systematic approach towards the process of finding bugs before users do is called debugging. In this chapter, some important tips to trace bugs in a PHP code are given. Programs rarely work correctly the first time. Many things can go wrong in your program that can cause the PHP interpreter to generate an error message. You have a choice about where those error messages go. The messages can be sent along with other program output to the web browser. They can also be included in the “web server error log”. To make error messages display in the browser, set the “display_errors” configuration directive to ON. Ensure that the following settings are enabled in the “php.ini” file. You can also use the ini_set() function to override the “pnp.ini” configuration − To send errors to the web server error log, set “log_errors” to ON. You can set them both to On if you want error messages in both places. PHP defines some constants that you can use to set the value of error_reporting such that only errors of certain types get reported − While writing your PHP program, it is a good idea to use PHP-aware editors like BBEdit or Emacs. One of the special features of these editors is syntax highlighting. It changes the color of different parts of your program based on what those parts are. For example, strings are pink, keywords such as if and while are blue, comments are grey, and variables are black. VS Code from Microsoft is also a good choice for editing PHP code. If you install VS Code extension Intelephense, you will get type hints and error message as you enter PHP statements in the editor window. Another feature is quote and bracket matching, which helps to make sure that your quotes and brackets are balanced. When you type a closing delimiter such as “}”, the editor highlights the opening “{” that it matches. Points to Check while Debugging a Code One needs to verfity the following points while debugging a program code − Missing Semicolons Every PHP statement ends with a semicolon (;). PHP doesn’t stop reading a statement until it reaches a semicolon. If you leave out the semicolon at the end of a line, PHP continues reading the statement on the following line. Not Enough Equal Signs When you ask whether two values are equal in a comparison statement, you need two equal signs (==). Using one equal sign is a common mistake. Misspelled Variable Names If you misspelled a variable then PHP understands it as a new variable. Remember: To PHP, $test is not the same variable as $Test. Missing Dollar Signs A missing dollar sign in a variable name is really hard to see, but at least it usually results in an error message so that you know where to look for the problem. Troubling Quotes You can have too many, too few, or the wrong kind of quotes. So check for a balanced number of quotes. Missing Parentheses and curly brackets They should always be in pairs. Array Index An array in PHP is a collection of items, each item assigned an incrementing index starting with 0. Moreover, handle all the errors properly and direct all trace messages into system log file so that if any problem happens then it will be logged into system log file and you will be able to debug that problem.
Try…Catch
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 − 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. 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 − getCode() This function returns the exception code as int in Exception − Take a look at the following example − getFile() This function returns the filename in which the exception was created − Take a look at the following example − It will produce the following output − getLine() This function returns the line number where the exception was created − Example Take a look at the following example − It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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. To begin with, since denominator is 0, “divide by 0” error will be displayed − Set $b=3 which will cause TypeError because divide function is expected to return integer but division results in float. If just one variable is passed to divide function by changing $res=divide($a); this will result in an ArgumentCountError − If one of arguments is not integer, it is a case of InvalidArgumentException. Change $b to a string − The Finally Block A 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. It will produce the following output − Case 1 − Case 2 − 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. Open Compiler It will produce the following output −
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 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 doesn’t find a file, otherwise proceeds to open it for subsequent processing. Open Compiler It will produce the following output − 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 − 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 − Parameters Parameter Importance Description errno Required It specifies the error level for the user-defined error. It must be numerical value. errstr Required It specifies the error message for the user-defined error. errfile Optional It specifies the filename in which the error occurred. errline Optional It specifies the line number at which the error occurred. errcontext Optional It 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.No Constant & Description Value 1 E_ERROR (int)Fatal run-time errors that can not be recovered from. Execution of the script is halted. 1 2 E_WARNING (int)Run-time warnings (non-fatal errors). Execution of the script is not halted. 2 3 E_PARSE (int)Compile-time parse errors. Parse errors should only be generated by the parser. 4 4 E_NOTICE (int)Run-time notices. Something that could indicate an error, but could also happen in the normal course of running a script. 8 5 E_CORE_ERROR (int)Fatal errors that occur during PHP’s initial startup. This is like an E_ERROR 16 6 E_CORE_WARNING (int)Warnings (non-fatal errors) that occur during PHP’s initial startup. This is like an E_WARNING, 32 7 E_COMPILE_ERROR (int)Fatal compile-time errors. This is like an E_ERROR. 64 8 E_COMPILE_WARNING (int)Compile-time warnings (non-fatal errors). This is like an E_WARNING. 128 9 E_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 10 E_USER_WARNING (int)User-generated warning message. This is like an E_WARNING, generated in PHP code by using the function trigger_error(). 512 11 E_USER_NOTICE (int)User-generated notice message. This is like an E_NOTICE generated in PHP code by using the function trigger_error(). 1024 12 E_STRICT (int)Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. 2048 13 E_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 14 E_DEPRECATED (int)Run-time notices. Enable this to receive warnings about code that will not work in future versions. 8192 15 E_USER_DEPRECATED (int)User-generated warning message. This is like an E_DEPRECATED, generated in PHP code by using the function trigger_error(). 16384 16 E_ALL (int)All errors, warnings, and notices. 32767 Example Take a look at the following example − Open Compiler It will produce the following output − PHP’s error class hierarchy starts from throwable interface. All the predefined Error classes in PHP are inherited from Error class. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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 − Open Compiler It will produce the following output − 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 − Open Compiler It will produce the following output − 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: Open Compiler It will produce the following output − 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 − Open Compiler It will produce the following output − 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 − Open Compiler It will produce the following output − 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 − Open Compiler It will produce the following output − 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 − Open Compiler It will produce the following output − 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. 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
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 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.No Expression & 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.No Expression & Description 1 p+It matches any string containing at least one p. 2 p*It matches any string containing zero or more p’s. 3 p?It matches any string containing zero or one p’s. 4 p{N}It matches any string containing a sequence of N p’s 5 p{2,3}It matches any string containing a sequence of two or three p’s. 6 p{2, }It matches any string containing a sequence of at least two p’s. 7 p$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.No Expression & Description 1 [^a-zA-Z]It matches any string not containing any of the characters ranging from a through z and A through Z. 2 p.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>. 5 p(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.No Expression & 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.No Function & Description 1 ereg()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. 2 ereg_replace()The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found. 3 eregi()The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive. 4 eregi_replace()The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive. 5 split()The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string. 6 spliti()The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive. 7 sql_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. Modifiers Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in multiple lines etc. PHP’s Regexp PERL Compatible Functions PHP offers following functions for searching strings using Perl-compatible regular expressions − Sr.No Function & Description 1 preg_match()The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. 2 preg_match_all()The preg_match_all() function matches all occurrences of pattern in string. 3 preg_replace()The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters. 4 preg_split()The preg_split() function operates exactly like split(), except that regular expressions
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 − 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 You can write the switch statements as follows: 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 − Function Definitions Function declarations follow the “BSD/Allman style” − 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 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. 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. Example Take a look at the following example − Open Compiler It will produce the following output − 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. To destructure this array the list() statement associates each array key with a independent variable. Instead, you can also use the [] alternative destructuring notation. Try and execute the following PHP script − Open Compiler 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 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 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 Destructuring works well even if the nested array is also an associative array. Open Compiler
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: Loaded Configuration File Locate the Loaded Configuration File setting that displays the location of php.ini file 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 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
MySQL Login
MySQL is a popular choice as a backend database for PHP powered web applications. In this chapter, we shall learn to develop a login page for a PHP application that authenticates the given username and password. You should have a web server having PHP and MySQL installed for experimenting with the example discussed in this chapter. The bundled binaries of Apache, PHP and MySQL (MariaDB) in the form of XAMPP for your operating system can be easily installed. Before running the example code, you should have a MySQL database called mydb in which there must be a table called admin. You can use following SQL script to create the table and insert a test data The first part of PHP login application is to establish database connection object. We use myqli API to obtain connection object. Save following code as “config.php” Config.php This PHP script is called inside the login script. It presents the user with a HTML form to enter username and password. In case the form is submitted, PHP runs a SELECT query to retrieve a row in the admin table where the username and passcode matches with the user inputs. If the row count is one, it indicates that the username and the password entered matches. The username is save to the $_SESSION variable and the browser is directed to welcome.php script. Login.php Save the following code as “login.php” − Open Compiler Learn MySQL in-depth with real-world projects through our MySQL certification course. Enroll and become a certified expert to boost your career. Session.php The following is the session.php code file. It checks if the session variable is set; then the user credentials will be assigned to the $login_session variable. If not, the user is redirected back to the login.php file. Welcome.php The “welcome.php” script gets invoked when the user is authenticated. It reads the session variable to display a welcome message. Logout.php Finally, the logout script removes the destroys the session and redirects the user to the login page. To start the login application, visit “http://localhost/login.php” Enter the username and password. On pressing the submit button, these inputs are checked against the rows in admin table. On success, you get the following message − If the query doesn’t fetch any matching row, the error message is displayed as follows −
Paypal Integration
PayPal is a payment processing system. We can integrate PayPal with websites by using with PHP. PayPal Integration File System PayPal integration file system included four files as shown below − The user has to download a PayPal SDK file from here and exact a zip file. The zip file contains four PHP files. We don’t need to change any file except “constants.php”. constants.php The “constants.php” file contains code as shown below − The user will declare the username, password and signature in the above syntax which are placed in “constants.php”. This is an experimental example so the last amount will be added to sandbox’s account.