CHAPTER 7
PHP is an open source, general-purpose scripting language oriented for web development. This language was originally created by Ramsus Lerdorf in 1994, and it was known as Personal Home Page / Forms Interpreter. The first version of PHP/FI was released in 1995. Later, PHP/FI 2.0 appeared in 1997. PHP is now supported by The PHP Group, and the PHP acronym stands for PHP: Hypertext Preprocessor. At this time, the current stable release is 7.0.13. The most important topics about PHP are summarized in the following list.
PHP can be deployed in a Windows environment using IIS (Internet Information Services) as a web server. To perform this deployment, the following requirements should be fulfilled:
To install IIS in a Windows 10 computer, you should go to the Programs section of the Control Panel, and then click on the Turn Windows features on or off link. Next, check the Internet Information Services checkbox in the Windows Features dialog box, in order to install IIS with the default features for a web server.
Now, to install PHP in the computer, you should download a zip installation package from this location for a 32-bit system, or from this location for a 64-bit system. After the download is complete, you should unpack the zip file in a folder named C:\PHP.
To configure PHP, rename the file php.ini-development to php.ini. Then, you can edit it to adjust some PHP working parameters to comply with IIS requirements.
As a final step, you should add C:\PHP to the Path system variable, and open the IIS Manager to set up PHP as the program that will handle all .php web requests coming from any client within the network.
Now, the installation process can be tested by creating a text file named phpinfo.php in the website root folder (commonly C:\inetpub\wwwroot). The file should contain the following programming code: <?php phpinfo(); ?>. Next, type http://127.0.0.1/phpinfo.php into a web browser to display the PHP installation info.
PHP programming relies on scripts. A script in PHP is a text file that contains pure PHP programming code, or PHP programming code embedded into HTML, and is executed in the web server.
As in most programming languages, the main way to store data in a PHP program is by using variables, which are identifiers intended to hold data dynamically, so that data stored in variables can change during the execution flow.
Variables in PHP are declared by denoting their names with a leading dollar sign ($), and then starting with a letter or underscore. Variables can be converted from one data type to another automatically.
A variable can be available in a certain section of a script, starting from the program in which the variable is declared. This is known as variable scope. PHP has the following variable scopes: local, for variables that are available only in the program where they are declared; global, for variables that can be accessed in any part of the executed program; function parameters, which are variables available within the function where they’re employed; and static, which are variables declared inside functions that keep their values between every function call.
PHP also allows you to use constants. A constant is an identifier that holds a simple value and cannot be changed during the execution of the script. Constants’ identifier names are case sensitive. The best practices in PHP dictate that constant names should be uppercase. Constants are defined by the define() function.
PHP uses expressions to perform calculations. A set of symbols are used in order to perform these calculations. These symbols are called operators, and the identifiers declared between the operators are called operands. PHP has the following types of operators: arithmetic operators, which are used to perform operations with numbers; comparison operators, which are used to check if criteria between two operands are met; logical operators, which are employed to get a true or a false value depending the logical state of two operands; assignment operators, which are employed to store the value of an expression into an operand; and conditional operators, which are employed to perform an inline decision making.
When an expression contains several operators, calculations are performed following a strict order. This order is known as operator precedence. To explain this precedence, we can classify operators into the following categories: unary, which are operators preceding a single operand; binary, which take two operands; ternary, which take three operands, evaluating either the second or the third depending on the value of the first one; and assignment operators, which store a value into an operand. Operator precedence is rather complicated. Common operators in an expression are executed in the following order: increment and decrement, unary, multiplicative and division, addition and subtraction, relational, equality, bitwise, ternary, assignment, logical AND, logical XOR, logical OR.
In PHP, we can use sequences of characters stored in variables or directly placed at the right of a statement. These sequences are called strings. Strings can be delimited either by single or double quotes. PHP treats strings in a different way depending on how they’re delimited. Every PHP statement is considered a single-quoted string literal, but when variable names are present in a double-quoted string, PHP replaces the name of the variable with its contents.
When we need to store several values of similar type, PHP provides us with a data structure known as an array. We can use this structure instead of declaring many variables. In PHP we have the following kind of arrays: numeric arrays, which store values that can be accessed using a numeric index; associative arrays, which use strings as indexes and associate them to the values stored; and multidimensional arrays, which contain one or more arrays accessing their values using multiple indexes. An array can be created using the array() function, or by declaring a variable followed by an index enclosed in brackets.
PHP provides a set of statements to take a course of action based on a condition. These statements are known as decision-making statements, and they are: if … elseif … else, which executes a code block when the condition after if statement is true, or the code block within the elseif statement, if the condition of if statement is false, and the condition of the elseif statement is true, or executes the code within the else statement in case both conditions are false; and the switch statement, which executes a block of code depending on a comparison of equality for an expression with a series of values, placed each one after a case clause, which also contains the code to be executed if the expression value is equal to the value associated to this particular case clause.
Looping statements allow us to execute a particular code block repeatedly, either while a certain condition is met, a specific number of times, or until a series of elements from a data structure have been all iterated. These looping statements are: for, which loops through a code block a specified number of times; while, which loops through a code block while a certain condition is met; do … while, which loops through a code block once, and repeats the execution as long as the condition established is true; and foreach, which loops through a code block many times as elements exist in an array. PHP provides two special keywords to be used within a loop: break, which terminates the execution of a loop prematurely; and continue, which halts the execution of a loop and starts a new iteration.
PHP lets the user create functions. A function is a piece of code which receives data by using a set of variables named parameters, then processes this data and returns a value. In PHP, we have user-defined and built-in functions. A user-defined function is created by the developer by using the reserved keyword function, followed by the name of the function.
When you need to pass data to a function, you should use a series of identifiers named parameters. These are a series of identifiers declared after the function name, enclosed in parentheses. You can declare as many parameters as you need. All these parameters will act as variables within the function. A function can return a value to the calling program employing the return statement.
We can set function parameters to have a default value, in case the calling program doesn’t pass any value to any of them. Default values are defined by placing the desired value at the right side of the parameter name, leading by an equal assignment operator (=).
A function can be called dynamically by storing its name into a string variable. Then, we can use this variable as we would the function name itself.
PHP has a large set of built-in functions that can be classified in categories. The most relevant categories are: array functions, which allow the developer to interact with and manipulate arrays; date and time functions, which get the date and time from the server in which scripts are running; string functions, which allow the developer to manipulate strings; character functions, which check whether a string or character falls into certain class; file system functions, which access and manipulate the file system; and directory functions, which are used to manipulate directories.
PHP allows code reusing, which is important for maintaining complex applications with minimal effort. Code reusing is handled by means of file inclusion. File inclusion is the mechanism used to insert the content of a PHP file into another one, and it is performed by two functions: include(), which copies all the text in the specified file into the script, generating a warning message when a problem occurs; and require(), which is similar to include(), except that it halts script execution when a problem occurs.
PHP provides a series of functions that help us to manipulate files by doing operations such as opening, reading, writing and closing a file. The functions fopen(), filesize(), fread(), and fclose() should be used together, in order to read the contents of a file. On the other hand, if we want to write text to a file, we need to use fwrite() function instead of fread().
PHP also supports a wide range of Database Management Systems (RDBMS). MySQL is the database system most commonly used in conjunction with PHP. PHP 7 includes an extension named mysqli (MySQL improved) which allows you to access MySQL 4.1 and above. For the purposes of this book, using MySQL with PHP requires that you have an active instance of MySQL installed in the computer used as a web server, and have the MySQL Workbench utility installed.
The exercises in this book used a database named contactinfo, which contains a single table to save contact information. We used the MySQL Workbench utility to create this database. The exercises explained in this book inserted data and queried the contacts table belonging to the database. These exercises used the mysqli extension through a class also named mysqli. This class works in the following way: the constructor (mysqli()) creates a connection to a MySQL server and uses the property connect_errno to inform if the connection was successful. In case of a successful connection, we can use the query() method to insert or retrieve data. Parameterized SQL sentences are also allowed through the statement object, which binds parameters to data variables using the bind_param() method.
Finally, all themes discussed in this book were gathered and turned into a simple contact list website. The website divided the homepage in four sections: a header, intended to show the name of the website; a toolbar, which holds a button intended to add contacts to the table; a data table, intended to display all contacts stored in the database; and a footer, which displays some copyright information. We also placed a Close button at the right side of the header section. This kind of design employs a complex programming, so we used the file inclusion technique, discussed in Chapter 4, to develop it. We used the index.php document as the website point of entry. Then, we programmed every section of the website’s homepage in a separate file and used the require() statement to include all those files in index.php.