Filed under PHP bits

PHP #3

Performance Issues

Depending on the scale of your application, there are some performances issues you might need to consider when using references.

In simple cases of copying one variable to another PHP’s internal reference counting feature prevents unneccessary memory usage.

E.g
$a = ‘the quick brown fox’;
$b = $a;

The above example, the value of $b would not take up an extra memory, as PHP’s internal reference counting will implicitly reference $b and $a to the same locarion in memory, until their values become different. This is an internal feature of PHP and affects performance without affecting behavior. We don’t need to worry about it much.

In some cases, however, using a reference is faster, especially with large arrays and objects, where PHP’s internal reference counting can’t be used, and the contents must be therefore copied.

As a general guide, you should do the following:

- With simple values such as integers and strings, avoid references whenever possible
- With complex values such as arrays and objects, use references whenever possible

References and PHP5

With PHP5, references cease to be an issue because the default behaviour of PHP, when passing objects, will be to pass by reference. If you ever need a copy of an object, you can use the special _clone method to create copies.

Essentially, the change brings PHP in line with the majority of object-oriented programming languages like Java. Until PHP5 is widely accepted, knowing how references work is important.

How do I take advantage of Inheritance?

<?php
class Hello {
function sayHello( )
{
return ‘Hello world’;
}
}//end simple class

class Goodbye extends Hello ( ) {
function sayGoodbye( )
{
return ‘Goodbye world!’;
}
}

Goodbye is now a child of Hello. Hello is the superclass of Goodbye. Now we can simply instantiate the child class and have access to the sayHello and the sayGoodbye methods using a single object.

$msg = &new Goodbye( );

echo $msg->sayHello ( ) . ‘<br />’;
echo $msg->sayGoodbye( ) . ‘<br />’;

?>

The above example shows how the concept of inheritance works. 

Overriding

PHP Post #2

Heredoc syntax, an alternative to writing PHP strings.

You begin with <<<EOD and a new line, and end it with a new line and then EOD.

$page .= <<<EOD
<p align=”center” >example</p>la
EOD;

Writing your first PHP class

<? php
//page class
class Page {
function doThis( ) { }
function doThat( ) { }
}
//end class

//Initialize the Page variable
$page = ” ;
$page = Page::doThis( );
$page = Page::doThat( );

?>

A complete class example

<?php
//page class
class Page {

//variable
var $page;

//constructor
function Page( )
{
$this -> page = ‘ ‘;
}

function addHeader($title)
{
$this->page .= <<<EOD
<html><head><title>$title</title></head>
<body><h1>$title</h1></body>
EOD;
}

//adds some more text to page
function addContent($content)
{
$this->page .= $content;
}

//gets the contents of the page
function get( )
{
return $this->page;
}

} //end class

Instantiating the Page class

$webPage = new Page( );

$webPage->addHeader(‘Sample page’);
$webPage.addContent(“<p>Adding now content here</p>”);

//display the page
echo $webPage->get( );

Output directly inside a clas, use functions such as echo and printf.

References
The example below shows passing by reference. It is important to pass objects by reference so as to avoid unexpected program outputs.

<?php

$color = ‘blue’;
$settings['color'] = &$color;
//notice the reference operator is passed twice here
function output(&$str)
{
$this->str = &$str;
}
?>

In summary, passing by reference keeps the target variable “linked” to the source variable, so that if one changes, so does the other.

Good Practices

class Bar { }

class Foo {
//return by reference
function &getBar( ) {
return new Bar( );
}
}

//Create Foo
$foo = &new Foo( );

//Get instance of Bar from foo
$bar = &$foo->getBar( );
$foo = &new Foo( );
This line looks odd at first, but remember, a variable created by the new keyword is being passed here – even if you can’t see it. The reference operator saves PHP from having to create the copy of the newly created object to store in $foo.

By preceding the function name with the reference operator, the value of the function returns is passed by reference. Note that we also had to use a reference operator when assigning the return value of getBar to $bar. This technique is commonly used when a class method will return objects.

Bad Practice
function display($message) {
echo $message;
}

$msg = ‘Hello world!’;
//call time pass by reference bad practice!
display(&$msg);

The decision as to whether a variable is passed by reference or not is one that belongs to the function being called, not the code that calls it. The above code written correctly would look like this:

//Accept by reference – good practice
function display(&$message) {
echo $message;
}

$msg = ‘hello world!’;
display($msg);

PHP Post #1

Including one PHP script in another

PHP provides four commands that allow you to add the contents of one PHP script to another, namely include, require, include_onc, and require_once. In each case, PHP fetches the file named in the command, then executes the contents. The difference between include and require is the way they behave should they be unable to find the script they were told to fetch.

include yields a PHP warning message like this:
Warning: Failed opening ‘script.php’ for inclusion.

This will allow the script that is called the include command to continue execution.

require results in a fatal error:
Fatal error: Failed opening required ‘script.php’

The calling script will terminate, bringing everything to a halt. If the file that was required is critical to your application, having the script to terminate is a good thing.

The include_once and require_once commands behave similarly to ther respective cousins, but if the script has already been included or required anywhere else, the statement will be ignored.

At first glance, it may not be obvious how these commands can be used. These commands come in handy under complex applications in which you have PHP scripts that include other PHP scripts, which in turn include yet more PHP scripts. This is particularly important when you use libraries of classes, and they are being used repeatedly by many scripts.

Be aware that the files you include needn’t contain only PHP. The included file could simply contain HTML without PHP.

Generally, we use the require_once command to include one file in another.

Path Finding

The first thing o be aware of is that all includes are calculated relative to the directory which the main script (where execution began) resides. For example, we have 3 files in the following locations:

/www/index.php
/www/includes/script.php
/www/another.php

Let’s consider index.php. The command include ‘includes/script.php’; will correctly include script.php, assuming index.php is the actual file requested.

If we use the following in script.php
include ‘../another.php’;

If script.php is the page we are viewing, it will correctly include another.php. However, if index.php is the page we are viewing, and it includes script.php, this command will fail, because the location of another.php is calculated relative to the location of index.php, not relative to script.php.

We can either modify script.php so that it includes another.php as follows:
include ‘another.php’;

Alternatively we can enter the full path to another.php:
include ‘/www/another.php’;

This leaves no doubt as to where another.php is located.

The PHP configuration file php.ini also contains the directive include_path. This allows you to specify directories from which files can be included, without the need to specify their locations when using one of the include commands.
This approach needs to be used with caution, as it may lead to strange results if an included file of the same name exists in more than one directory, yet it can be an effective means to solve include-related headaches. Note also that it’s not a good idea to specify too many locations in your include path, as it will slow PHP down when it tries to find the scripts.

Writing portable PHP codes

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.

1) Keep all configuration central.
For most PHP applications, it will be necessary to provide information describing the environment in which the script will run, including database usernames and passwords, directory locations, and so on.  Try to keep the majority of these information in a single place, or maybe a single file.

A simple but effective mechanism is to place all the settings in a single file as PHP constantsm which makes them available from any function or class in your application, for example:

<?php
//config 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; they should accept configuration information as arguments. In such cases it’s best to use PHP variables in your central configuration file.

When connecting to MySQL we can identify a number of variables we need to have in a central location: the server host name, user name, password, and the name of the selected database.

Using the require_once command, we can create a file called, for instance, config.php, and place it outside the public Web directories. This helps to ensure that no one accidentally browses to the file containing this critical information, which would place the site’s security at risk.

Use full <?php ?> tags
Self -explanatory

register_globals off
Turning it on presents a risk to security. So in php,ini, make sure the following code is in place:

register_globals = Off

Magic Quotes
A feature intended to help prevent security breaches in sites developed by PHP beginners.

It adds escape characters 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 then it’s worth.

Controlled by a PHP configuration setting, magic_quotes_gpc, which can be either on of off.

Below is a simple file that strips out magic quotes:

<?php

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 querystring, a form post, or a cookie, we’ll remove any slashes added by magic quotes.

Follow

Get every new post delivered to your Inbox.