| <home / programming / phpanth1 / 1 | [previous] |
|
|
Not all PHP installations are the same. Depending on version and configuration settings in php.ini, your script may or may not run correctly on another server where PHP is installed. However, there are some general good practices you can adopt to make life easier and minimize the need to rewrite code for other servers.
For most PHP applications, it will be necessary to provide information describing the environment in which the script will run, including database user names and passwords, directory locations, and so on. As a general rule, try to keep the majority of this information in a single place—maybe even a single file—so that when the information needs to be modified, you can do it all in the one place. That said, when building modular applications, you may want to store elements of the configuration that are local to a specific “module” with the module itself, rather than centrally.
How exactly you choose to store this information is a matter of personal choice. In some cases, it may be worth considering an XML file or storing some of the information in a database. It’s also worth being aware of the parse_ini_file function, which I’ll explore in Chapter 4, Files .
A simple but effective mechanism is to place all the settings in a single file as PHP constants, which makes them available from any function or class in your application. For example:
Example 1.7. 6.php
<?php
// Configuration settings
define('DOMAIN', 'sitepoint.com');
// In another script
echo 'The domain is ' . DOMAIN;
?>
Constants need to be used with caution, though. To make your functions and classes reusable in other applications, they shouldn’t depend on constants of a fixed name; rather, they should accept configuration information as arguments. In such cases, it’s best to use PHP variables in your central configuration file, which you can then pass to functions and classes as required. If you look at Chapter 3, PHP and MySQL , when connecting to MySQL we can identify a number of variables we need to have in a central location: the server host name, the user name, the password, and the name of the selected database.
Using the require_once command we looked at in the previous solution, we can create a file called, for instance, config.php, and place it outside the public Web directories. This helps ensure that no one accidentally browses to the file containing this critical information, which would place the site’s security at risk.
PHP supports a variety of tag styles to mark up sections of PHP code, including the short tags (<? ?>), and ASP-style tags (<% %>). These are controlled from php.ini with the settings short_open_tag and asp_tags . While you have these settings set to On, other people may not. The short tag style, for example, causes a problem when the PHP is mixed with XML documents, which use processing instructions like this:
<?xml version="1.0"?>
If we have a document which contains PHP and XML, and we have the short_open_tag turned on, PHP will mistake the XML processing instruction <?xml for a PHP opening tag.
It’s possible that your code will need to run in environments where short_open_tags and asp_tags are both off. The best way to be sure that they are is to get into the habit of always using the <?php ?> tag style, otherwise there may be a lot of code rewriting to do in some dark future.
PHP is capable of turning incoming data into native PHP variables. This feature is controlled by the register_globals setting in php.ini. With register_globals switched on, if I point my browser at an address like http://www.mysite.com/index.php?logged_in=1, PHP will automatically create a variable $logged_in and assign it the value of 1. The PHP group now recommends this setting be disabled because it presents a risk to security, as the previous example suggests.
So, in php.ini make sure the following code is in place:
register_globals = Off
This will force you to access incoming data via the special predefined superglobal variables (e.g. $_GET['username']), which means they won’t conflict with variables you’ve created in your script.
Using a .htaccess file with Apache, the same result can be achieved with the following code:
php_flag register_globals off
Further information can be found in the PHP manual, and in Kevin Yank’s article, Write Secure Scripts with PHP 4.2! on SitePoint.
Magic quotes is a feature intended to help prevent security breaches in sites developed by PHP beginners.
It adds escape characters (see Chapter 5, Text Manipulation for more information) to incoming URL query strings, form posts, and cookie data automatically, before your script is able to access any of these values. Should you insert the data directly into your database, there’s no risk of someone being able to tamper with the database provided magic quotes functionality is switched on.
For beginners, this is certainly a useful way to prevent disasters. However, once you understand what SQL injection attacks are, and have developed the habit of dealing with them in your code, the magic quote functionality can become more of a problem than it’s worth.
Magic quotes functionality is controlled by a PHP configuration setting, magic_quotes_gpc , which can be either on or off.
My own preference is to always have magic quotes switched off, and deal with escaping data for SQL statements myself. Unfortunately, this means the code I write won’t port well to PHP installations where magic quotes is switched on (I’ll end up with backslashes in my content). Thankfully, to deal with this problem, PHP provides the function get_magic_quotes_gpc , which can be used to find out whether magic quotes are switched on. To keep the code in this book portable, we’ll use a simple file that strips out magic quotes, should the functionality be enabled:
Example 1.8. MagicQuotes/strip_quotes.php (in SPLIB)
<?php /** * Checks for magic_quotes_gpc = On and strips them from incoming * requests if necessary */ if (get_magic_quotes_gpc()) { $_GET = array_map('stripslashes', $_GET); $_POST = array_map('stripslashes', $_POST); $_COOKIE = array_map('stripslashes', $_COOKIE); } ?>
If we include this at the start of any file in which we accept data from a query string, a form post, or a cookie, we’ll remove any slashes added by magic quotes, should this functionality be switched on. This effectively gives us back what we started with.
The subject of SQL injection attacks is discussed in detail in the section called “How do I solve database errors caused by quotes/apostrophes?”. If you’re not yet confident that you can protect yourself against SQL Injection attacks, use magic quotes. Once you’re happy you have a full grasp of all the issues, switch the magic quotes functionality off and save yourself many headaches. Note that magic quotes can only be switched on or off using the php.ini file or one of Apache’s .htaccess files. For more information, see Appendix A, PHP Configuration .
$result = myFunction(&$myVariable);
Here the & operator tells PHP to use a reference to the variable $myVariable as the argument, rather than creating a copy of its value. This is now generally regarded as bad practice, as it can make the job of understanding someone else’s code extremely difficult.
Switch this off in php.ini using the following command:
allow_call_time_pass_reference = Off
Alternatively, switch it off in a .htaccess file as follows:
php_flag allow_call_time_pass_reference off
For example, if your application has some kind of user authentication system, will it integrate with the one they’re already using—a system that already has a large database of users associated with it?
The best approach is to write object oriented code (the focus of Chapter 2, Object Oriented PHP ) with a mind to creating reusable “components.” Some people argue that writing object oriented code in PHP slows down the application’s performance and should therefore be avoided at all costs. What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!
Some things to consider when measuring the potential of your code for reuse are:
What happens when requirements change?
How easy is it to add new features to your code?
Are you still able to understand the code after a long period of time?
Can your code be integrated easily with other applications?
Will assumptions made in your code apply to your work on other sites?
You’ll find throughout this book many hints and suggestions to encourage you to write reusable code, although an in-depth analysis of PHP applications design as a whole is beyond its scope. As you read this book, you should get a feeling for some of the critical factors as subjects for further investigation. You have one main responsibility to yourself as an experienced PHP developer: to keep expanding your general knowledge of the more esoteric aspects of software development, such as design patterns and enterprise application architecture , as a means to improve your development technique and, more importantly, save yourself time. The broader your knowledge, the lower the risk of failure when you land that big project.
Write Secure Scripts with PHP 4.2!: http://www.sitepoint.com/article/758
A tutorial that explains the importance of writing scripts with register_globals switched off.
Effortless (or Better!) Bug Detection with PHP Assertions: http://www.sitepoint.com/article/1008
Using Strings: http://www.zend.com/zend/tut/using-strings.php
Zend provides a walk-through of the main functions available for working with strings.
String Theory: http://www.devshed.com/Server_Side/PHP/StringTheory/ [Ed. Note: This link is broken.]
DevShed offers an in depth look at strings, going as far as Posix extended regular expressions.
| home / programming / phpanth1 / 1 | [previous] |
Created: March 27, 2003
Revised: January 2, 2004
URL: http://webreference.com/programming/phpanth1