Services
Blog
Map
Contact Me
Rss
About
This page contains blog records from 'PHP Development' category.
PHP commands are inserted right into HTML documents. But how does the web server can tell the PHP code to be executed embedded into the HTML document? Actually, it’s very easy: Special tags are used to indicate the beginning and the end of the PHP code. Everything outside of these tags is treated as HTML code.
Most often, the beginning and the end of PHP commands are marked in the following way:
<?php PHP code ?>
Everything between the tags the web server treats as PHP code and processes it accordingly. Everything outside of these tags is treated as HTML code and is sent to the client as is and is processed in the browser.
This is the most preferential format of the PHP code delimiting tags; using it you can be certain that it will processed by the server correctly. There also are other currently supported PHP code delimiting formats. Despite this, you should realize that only the tags are guaranteed support in all PHP versions. Use of other PHP code delimiting tags may be discontinued or limited in any future version of the language. This may lead to the problem of having to rewrite all the scripts in which discontinued delimiters are used. It’s no big deal if you have only a few of them, but if you have a big site with lots of PHP scripts, then you’ve got a problem.
Every programmer tries to reuse existing code and any programming language tries to provide support for this. When we develop a new project, we don't feel at all as solving the same problems that had been solved in previous projects. Being able to reuse already developed code allows us to avoid doing the same mundane routines over and over again.
You have probably heard a lot about Windows dynamic libraries. These libraries store various different resources (images, icons, dialog window forms, menus, etc.) and/or program code. Any program can load this library and use the resources stored in it. For example, the OpenGL graphics library stores functions for creating 3D graphics of practically any complexity. Any programmer can load this library into the computer memory and use its resources in his or her own projects. Accordingly, it is not necessary to write graphic functions code for each new program, but use code already developed by other programmers.
Dynamic libraries not only allow a programmer use his or her own code in different projects, but also share it with other programmers, as we saw in the example with the OpenGL library.
Being able to reuse code is even more important when programming web pages. Your site may contain hundreds of files doing the same thing. Writing the same piece of code in each of them is a tedious time-consuming task. Moreover, this results in bloated, slow-executing files.
We already used the print function to observe the results of script execution. We have to explore the available output functions more closely, because if you can`t see the results of your scripts` work, you may have problems digesting the material presented. The best way to learn anything is to personally touch and see every detail.
In addition to the print function, information can be displayed by the echo function. There are two ways of calling it. These are the following:
echo("Hello, this is text");
echo "Hello, this is text";
In the first case, the text to be displayed in placed into parenthesis, and in the other, it is simply placed after the function name after a space. In either case, the output text is enclosed into quotation marks. Both calling method are equivalent to each other, and you can use the one you feel more comfortable with. You can output several strings with the echo function by separating them with a comma. For example:
If you have experience programming in high-level languages (e.g., C++, Delphi), you must know that all variables must be of a strictly defined type, and the code must follow quite stringent syntax rules. PHP is more flexible and does not impose strict rules. This flexibility, however, comes at the price of greater chances of erroneous script execution and being much more difficult to provide proper security. Lots of break-ins have been perpetrated exactly because variables in PHP are not assigned a specific type when declared.
Suppose a hacker passes a database query string through a parameter that the programmer intended to be used to pass a numerical value. (By the way, this is how the PHPNuke site management system was cracked.) If the parameter variable were defined of a specific type, such action would return an error, because the string could not be converted into a number. Because PHP is weak-typed language, programmers must implement data type checks and handle incorrect data type errors themselves.
If you have programmed in C, Java, or Perl before, many concepts in PHP will be familiar to you, because PHP is very similar to C/C++.
We have already touched slightly on variables and know that a variable is a memory area in which values can be stored and can be referenced by a name. We don't care where exactly in the memory our variables are stored, because their values can always be retrieved or changed by referencing their names. PHP variables have the following properties:
Variables are created to perform some operations on them. At present, we will consider only the following simple mathematical operations:
As is common in mathematics, mathematical operations in PHP are performed in the order of operator precedence. Multiplication and division are performed before addition and subtraction. Consider the following classical example:
$index = 2 + 2 * 2;
If you ask, for example, a third-grader to evaluate the above expression, the most likely answer will be 8. But those with further advances in math will not fall into the sequential evaluation trap. Their answer will be 6, because pursuant to the mathematical operator precedence order, first the multiplication operation is performed, yielding 4, which is then added to 2, thus producing 6.
Constants are similar to variables in that they are named memory locations holding certain values; unlike variables, however, once a constant was assigned a value at its declaration, it cannot be changed during script execution.
Constants are used to store some frequently used numbers or strings. For example, your site may be programmed for 640-pixel wide pages and you want to switch to using 800-pixel wide pages. If you used number 640 explicitly in your code, you will have to find all instances it was used in the code and change it. Even though this task can be automated, there is no guarantee that you will find all the numbers that need to be changed or not change a number 640 referring to something other than the page width. Instead of using the number 640 explicitly, you can declare a constant, for example $PgWdth, at the beginning of the file, set it to 640, and then use the constant throughout the file wherever you need to use number 640. Then, if you need to change 640 to 800, all you need to do is to reassign the value of the constant $PgWdth to 800 once at the beginning of the file.
I recommend always using constants or at least variables if a number or a string is used more than once in the code. These constants and variables can be stored in a separate file, which can then be included into the PHP files using these constants or variables. Based on my personal experience, I can tell that using constants can make software maintenance and modification significantly easier.
It is a rare program that simply executes from the beginning to the end, because in most cases there are some conditions that can change the program execution flow. Thus, these conditions have to be checked and reacted to in one way or another. Let's consider an example of a site's main page. When a user visits the site for the first time, he or she can be shown some additional information or greeted with some funny presentation to get him interested in the site. For succeeding visits by the same user, the presentation is no longer shown. The script logic for these actions will be something like the following:
As another example, we have to do numerous checks to ensure that a script is reliable and secure. For example, if a script is intended to send a mail message, it is a good idea to check whether the address is specified correctly before mailing the message. Here, the logic can be the following:
Loops are important program flow control. For example, the problem of raising a number to a power that we used as an example when considering the switch statement, can be solved much easier and more efficient using one of the loop statements. A number is raised to a certain power by multiplying it by itself this number of times. For example, the operation of raising 2 to the power of 3 can be written as follows: 2*2*2. But what if a number has to be raised to the power of 100? This task is somewhat more difficult. Even more difficult is the problem when the power is not known in advance. Here is where loops come to the rescue.
The most often used loop is the for loop. It is also the easiest to understand, so we start our study of loops with it. In the general format it looks as the following:
for (start counter value; end counter value; counter step) Statements
Let's use the for loop to raise a number to a power. The code for this may look like the following:
Sometimes a situation will arise when a loop execution has to be terminated. Quite often, this is necessary when an error occurs and further execution may have serious consequences. For example, the required file is not available or a user provided wrong parameters. In either case, further script execution may display confidential information or perform some other undesirable actions. Do not experiment in such case and stop the script execution.
Script execution can be interrupted with the exit() function. Script execution is terminated at once when this command is executed. The die() command is an alias for exit(), and both command allow a message to be displayed in the browser to be specified as a parameter. Consider the following classical example of connecting to a database:
When I was beginning to learn programming in Pascal, for a long time I could not fathom what functions were needed for. All my programs had flat structure without branchings or any kind. But once I ran into a problem: I had to write a program whose code looked like shown in next code.
print("Select one of the actions<BR>");
print("===========================<BR>");
print("Search <BR>");
print("===========================<BR>");
print("===========================<BR>");
print("Print <BR>");
print("===========================<BR>");
print("===========================<BR>");
print("Exit <BR>");
print("===========================<BR>");
An array is list of values that can be referenced with a single variable. This is achieved by using an index to reference individual array elements. Either a number or a word can be an index. Number indices start with zero.
Arrays are named in exactly the same way as variables, but with square brackets after the array name. In the following example, words "cake," "bread," and "carrot" are added to an array.
$goods[]= "cake"; $goods[]= "bread"; $goods[]= "carrot";
A particular array element is referenced by specifying its index in square brackets. For example, the following code displays the contents of the zero element, which is "cake":
At certain configuration settings, PHP may not issue error messages. For production web sites, I recommend to keep this feature disabled. An extra message for a hacker is an extra hint to a successful break-in. For example, a message informing of excessive parameters tells me that the script does not check for the number of parameter passed to it, so it may not do other checks either, for example, whether the system function is called the right way. We will talk about the dangers inherent to this function repeatedly in this book.
A system used for application development must issue messages for any errors; otherwise, it is more likely than not that you will miss some potential errors, and will not be able to understand why the script code is not performing the way you intend it to.
The error reporting feature is enabled by setting the error_reporting parameter in the php.ini file to E_ALL. Error messages may be issued when numerical data is compared with string data. For example, adding a command error_reporting (E_ALL) command at the beginning of the script in which we considered the print_max() function (see Section 2.8) will produce the following error when a number and string are compared:
All environmental variables passed to a script are placed by the interpreter into the $HTTP_ENV_VARS array. The format of this array is different on different computers. In Windows, environmental variables can be checked by executing the set command in the command line; in UNIX-like systems, environmental variables can be viewed by executing the env command.
You can find the following PHP environmental variables of use:
Static web pages are a rarity nowadays. Practically any more or less big web site asks for some data from the users. The data supplied by the users are passed as parameters to the specified script using HTML forms. The following example shows how to create a form for entering a user name:
<form action="param.php" method="get"> User Name: <input name="UserName"> </form>The <form> tag takes the following two parameters:
The mechanism of using the POST method is the same as that for the GET method. You only have to change the name of the method to be used (i.e., replace GET with POST) and your code will work without requiring any additional modifications. This, although, is conditional on that global parameters had been used to pass data and not the $HTTP_GET_VARS array (the POST method uses a different array). The earlier example demonstrating passing parameters using the GET method can be changed to use the POST method as follows:
<form action="param.php" method="post"> User Name: <input name="UserName"> <input type="hidden" name="Password" value="qwerty"> </form>
Other than replacing GET with POST, no other changes are necessary.
When the POST method is used, all parameters are also included in the request body in the parameter_name=parameter_value format. Additionally, the variable's names and their values are placed into the $HTTP_POST_VARS array, or $_POST for short.
You should exercise extreme care when working with parameters. If the register_globals parameters is set to On in the php.ini configuration file, global variables are created. This can be a vulnerability source if you are not being careful enough. Let's consider the following vulnerability demonstration example:
<form action="testpass.php" method="get">
Login: <input name="username">
Password: <input name="password">
</form>
if ($password== $legal_pass) and ($username==$legal_name)
$logged = 1
if ($logged)
{
//The user has been authorized
}
Never trust hidden parameters! You ask why? Because it is very easy to change them. All it takes is to save the web page on the local hard drive, modify the action field to point to the necessary script on the server, modify the necessary parameter, and execute the modified file.
Despite their shortcomings, hidden parameters can still be used; you simply have to be very careful with them. We will start considering using hidden parameters with how to hide parameters from honest users and beginning hackers. Sometimes it is necessary to pass some service information from one page to another without using cookies for this. In this case we can make use of hidden parameters. This can be done is several ways, which we will consider.
The first way is to create an input field of the hidden type as follows:
<form action="param.php" method="post"> <input name="UserName"> <input type="hidden" name="HiddenParam" value="00000"> </form>HTTP does not support protracted connections. A new connection is created to receive each file in a page (i.e., a script, image, Flash animation, etc.). Consequently, the server cannot control whether the same user requested two different item (e.g., a script and an image), because for each of these a different connection would be created.
Page transitions also create new server connections; therefore, pages cannot be interlinked nor have common parameters. There are three ways to save parameter values when moving from one page to another. These are the following:
Let's consider parameter use on the example of a site employing authorization procedure. When a user enters his or her name, a session must be initiated. This allows us to use session variables. A session is initiated by the session_start() function. If the function executes successfully, it returns true; otherwise, false is returned.
Now the PHP interpreter has to be informed which variables are to be saved in the session. This is done using the session_register() function, to which the variable name to be saved is passed as the parameter. Afterward, all the variables that have been placed into the session will be available from all pages of your site for the duration of the session.
Let's consider an example of a session. We'll create a file named session.php for this. The file contains a form to enter the user name, which will be saved in a session variabl:
The format of PHP comments is similar to that of C/C++ and Java, which is another indication of these languages being related. What is a comment as related to a programming language? This is supplementary information given in the code that has no effect on the program execution. For example, you may want to explain how a particular piece of code works. Naturally, you don't want this explanation to execute or to show in the browser. Such explanation is inserted as a comment in the vicinity of the code it explains.
There are single-line and multi-line comments. A single line comment starts with two slashes (like in C++) or with the pound sign (like in Linux). Everything following these characters is disregarded by the interpreter and treated as a comment. For example:
<?php # This is a comment //This is also a comment This is code//But this is a comment ?>
PHP is not sensitive to spaces, carriage returns, and tabs. This means that you can break one command into several lines, or delimit variables, values, or operators with different number of spaces. For example, as the following:
<?php $index = 10; $index = 10 + 20; $index=10+10; $index= 10 + 10; ?>
All of the code above is correct and will work without a hitch.
Each PHP command is terminated with a colon (;). In this way, the interpreter separates one command from another. Do not forget to use this character where it is required, because failing to do so may cause unpredictable errors, which usually cannot be attributed to a missing command separator.
The command separator makes it possible to write one command on several lines or place several commands in one line. The interpreter will be able to tell the commands apart thanks to the command separator.
When the GET method is used, all the parameters that are passed to the script are placed into global variables. In addition, they are also placed into the $HTTP_GET_VARS array, or $_GET for short. But there is more to come. The parameters are also displayed in the browser's URL field. Thus, when the above example code with passing name and password parameters is executed, the URL will change to this: http://192.168.77.1/param.php?UserName=Flenov&Password=qwerty.That is, the original URL is appended with a question sign followed by the parameters passed in the parameter_name=parameter_value format and delimited by the ampersand (&).
How safe do you think this method is? Good thinking! Any of the parameters can be easily changed manually without even changing the form's source code. When developing scripts you should make it as hard as possible for hackers to be able to be able manipulate parameters. For example, do not use the GET method to transmit passwords, because it can be easily intercepted.
Another problem with this method is its openness. Consider the password example again. When a user enters a password via this method, the password will be displayed in the browser's URL field. Anyone passing by at this time can see this password in there.