Friday, September 12, 2008

PHP htmlentities Function

Whenever you allow your users to submit text to your website, you need to be careful that you don't leave any security holes open for malicious users to exploit. If you are ever going to allow user submitted text to be visible by the public you should consider using the htmlentities function to prevent them from running html code and scripts that may be harmful to your visitors.

HP - Converting HTML into Entities

The htmlentities function takes a string and returns the same string with HTML converted into HTML entities. For example, the string

"'";

//Lets make it safer before we use it
$userInputEntities = htmlentities($userInput);

//Now we can display it
echo $userInputEntities;

The HTML output of the above script would be as follows:
Safe Raw HTML Code:

I am going to hax0r your site, hahaha!
< script type='text/javascript' >
window.location = 'http://www.example.com/'
< /script >'

If we had not used htmlentities to convert any HTML code into safe entities, this is what the raw HTML code would be and it would have redirect a visitor to example.com.

Dangerous Raw HTML Code:

I am going to hax0r your site, hahaha!
'

Those two HTML code examples are what you would see if you were to view source on the web page. However, if you were just viewing the output normally in your browser you would see the following.

Safe Display:
I am going to hax0r your site, hahaha! '

Dangerous Display:
You'd see whatever spammer site that the malicious user had sent you to. Probably some herbal supplement site or weight loss pills would be displayed.

When Would You Use htmlentities?
Anytime you allow users to submit content to your website, that other visitors can see, you should consider removing the ability to let them use HTML. Although this will remove a lot of cool things that your users can do, like making heavily customized content, it will prevent your site from a lot of common attacks. With some custom coding you can just remove specific tags from running, but that is beyond the scope of this lesson.

Just remember, that when allowing users to submit content to your site you are also giving them access to your website. Be sure you take the proper precautions.

PHP - Filing

Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files.

This section of the PHP tutorial is completely dedicated to how PHP can interact with files. After completing this section you should have a solid understanding of all types of file manipulation in PHP!

PHP - Files: Be Careful

When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.

It is our hope that you will be able to avoid these and other slipups after reading this tutorial. However, we know that there are so many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP.

PHP - Files: Overview

The presentation of the file lessons will begin with how to create, open, and close a file. After establishing those basics, we will then cover other important file tasks, such as: read, write, append, truncate, and uploading files with PHP.

PHP - File Create##########

Before you can do anything with a file it has to exist! In this lesson you will learn how to create a file using PHP.

PHP - Creating Confusion
In PHP, a file is created using a command that is also used to open files. It may seem a little confusing, but we'll try to clarify this conundrum.

In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending (more on this later).
PHP - How to Create a File

The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).

Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.

PHP Code:

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it.

1. $ourFileName = "testFile.txt";

Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName.
2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");

This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform

PHP that we want to write by passing the character "w".
Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on.

3. fclose($ourFileHandle);

We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.

PHP - Permissions

If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a command called CHMOD. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file.

In the near future Tizag.com will have a more in-depth tutorial on how to use CHMOD to set file permissions.

PHP - File Open###########
In the previous lesson we used the function fopen to create a new file. In this lesson we will be going into the details of this important

function and see what it has to offer.

PHP - Different Ways to Open a File
For many different technical reasons, PHP requires you to specify your intentions when you open a file. Below are the three basic ways to open a file and the corresponding character that PHP uses.

* Read: 'r'

Open a file for read only use. The file pointer begins at the front of the file.

* Write: 'w'

Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. This is also called truncating a file, which we will talk about more in a later lesson. The file pointer begins at the start of the file.

* Append: 'a'

Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file pointer begins at the end of the file.

A file pointer is PHP's way of remembering its location in a file. When you open a file for reading, the file pointer begins at the start of the file. This makes sense because you will usually be reading data from the front of the file.

However, when you open a file for appending, the file pointer is at the end of the file, as you most likely will be appending data at the end of the file. When you use reading or writing functions they begin at the location specified by the file pointer.

PHP - Explanation of Different Types of fopen


These three basic ways to open a file have distinct purposes. If you want to get information out of a file, like search an e-book for the occurrences of "cheese", then you would open the file for read only.

If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the "w" option. This would wipe clean all existing data within the file.

If you wanted to add the latest order to your "orders.txt" file, then you would want to open it to append the data on to the end. This would be the "a" option.

PHP - File Open: Advanced


There are additional ways to open a file. Above we stated the standard ways to open a file. However, you can open a file in such a way that reading and writing is allowable! This combination is done by placing a plus sign "+" after the file mode character.

* Read/Write: 'r+'

Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.

* Write/Read: 'w+'

This is exactly the same as r+, except that it deletes all information in the file when the file is opened.

* Append: 'a+'

This is exactly the same as r+, except that the file pointer is at the end of the file.
PHP - File Open: Cookie Cutter Below is the correct form for opening a file with PHP. Replace the (X) with one of the options above (i.e. r, w, a, etc).

Pseudo PHP Code:


$ourFileName = "testFile.txt";
$fh = fopen($ourFileName, 'X') or die("Can't open file");
fclose($fh);

PHP - File Open: Summary
You can open a file in many different ways. You can delete everything and begin writing on a clean slate, you can add to existing data, and you can simply read information from a file. In later lessons we will go into greater detail on how each of these different ways to open a file is used in the real world and give some helpful examples.

PHP - File Close####################
The next logical step after you have opened a file and finished your business with it is to close that file down. You don't want an open file running around on your server taking up resources and causing mischief!

PHP - File Close Description

In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it's a good programming practice and because we told you to!

PHP - File Close Function

In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that example and discuss the importance of closing a file.

PHP Code:


$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

The function fclose requires the file handle that we want to close down. In our example we set our variable "$fileHandle" equal to the file handle returned by the fopen function.

After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function. Write, then this function might not work the way you expect it to.

PHP - File Delete##########
You know how to create a file. You know how to open a file in an assortment of different ways. You even know how to read and write data from a file!

Now it's time to learn how to destroy (delete) files. In PHP you delete files by calling the unlink function.

PHP - File Unlink
When you view the contents of a directory you can see all the files that exist in that directory because the operating system or application that you are using displays a list of filenames. You can think of these filenames as links that join the files to the directory you are currently viewing.

If you unlink a file, you are effectively causing the system to forget about it or delete it!

Before you can delete (unlink) a file, you must first be sure that it is not open in your program. Use the fclose function to close down an open file.

PHP - Unlink Function

Remember from the PHP File Create lesson that we created a file named testFile.txt.

PHP Code:


$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);

Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just needs to know the name of the file to start working its destructive magic.

PHP Code:


$myFile = "testFile.txt";
unlink($myFile);

The testFile.txt should now be removed.PHP - Unlink: Safety First!

With great power comes a slough of potential things you can mess up! When you are performing the unlink function be sure that you are deleting the right file!

PHP - File Append###########
So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.

PHP - File Open: Append
If we want to add on to a file we need to open it up in append mode. The code below does just that.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');

If we were to write to the file it would begin writing data at the end of the file.

PHP - File Write: Appending Data

Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.

PHP Code:


$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);

You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.

The contents of the file testFile.txt would now look like this:

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2

PHP - Append: Why Use It?

The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.

A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append!

PHP - File Truncate###########
As we have mentioned before, when you open a file for writing with the paramater 'w' it completely wipes all data from that file. This action is also referred to as "truncating" a file. Truncate literally means to shorten.

PHP - File Open: Truncate
To erase all the data from our testFile.txt file we need to open the file for normal writing. All existing data within testFile.txt will be lost.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fclose($fh);

PHP - Truncate: Why Use It?
Truncating is most often used on files that contain data that will only be used for a short time, before needing to be replaced. These type of files are most often referred to as temporary files.

For example, you could create an online word processor that automatically saves every thirty seconds. Every time it saves it would take all the data that existed within some HTML form text box and save it to the server. This file, say tempSave.txt, would be truncated and overwritten with new, up-to-date data every thirty seconds.

This might not be the most efficient program, but it is a nice usage of truncate.

PHP substr_replace Function

The function substr_replace introduces some additional functionality to compliment str_replace. substr_replace is a more mathematically based replace function, which relies on starting points and lengths to replace parts of strings, as opposed to searching and replacing.

substr_replace's Four Parameters
There are three required parameters for the substr_replace function (original string, replacement string, starting point) and one that's optional (length).

1. original string - This is your original string that will be operated on.
2. replacement string - This string will be used to replace everything in the string from the starting point to the ending point (specified by length).
3. starting point - This is the place in the original string that will be used to mark the replacement's beginning. A negative value specifies the number of characters from the end of the string.
4. optional length - How many characters from the original string will be replaced. If no length is specified then the end of the string is used. If a value of 0 is used then no characters will be replaced and an insert is performed. A negative value specifies the number of characters from the end of the string.

substr_replace On Your Mark
This example of substr_replace shows what happens when you omit the length parameter at various starting points.

PHP Code:
//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";

//starting point 5
$sp5 = substr_replace($original, "Five", 5);
//starting point 12
$sp12 = substr_replace($original, "Twelve", 12);
//starting point 0
$sp0 = substr_replace($original, "Zero", 0);
//starting point -1
$spneg1 = substr_replace($original, "Negative 1", -1);

//Echo each string
echo "Original String: $original
";

echo "Starting Point 5: $sp5
";

echo "Starting Point 12: $sp12
";

echo "Starting Point 0: $sp0
";

echo "Starting Point -1: $spneg1 ";

Display:
Original String: ABC123 Hello Mr. Cow! DEF321
Starting Point 5: ABC12Five
Starting Point 12: ABC123 HelloTwelve
Starting Point 0: Zero
Starting Point -1: ABC123 Hello Mr. Cow! DEF32Negative 1

As you can see, when you don't specify the fourth parameter, length, everything after the starting point is replaced by the second parameter replacement string.

Note: The first replacement occurred at position 5, which in $original was the character 3. This 3 and everything onward was replaced with the replacement string. Remember that you start counting character to begin from zero. The $original string could be labeled as

so:

* Letter A - Position 0
* Letter B - Position 1
* Letter C - Position 2
* Letter 1 - Position 3
* Letter 2 - Position 4
* Letter 3 - Position 5

substr_replace Specifying a Length
If you want to get any sort of precision out of this function you're going to have to get into the nitty gritty of specifying the exact length of characters you want replaced in your original string.

Imagine that you want to get rid of those ugly pseudo references (ABC123, DEF321) at the beginning and end of the string. Since both of those strings are a length of 6 and we know one is at the very beginning of the string and the other is at the very end of the string

we should probably use a starting point of 0 for ABC123 and a value of -6 for DEF321. By having a replacement string of nothing "" we can do something similar to select and delete that we often do in a word processor.

PHP Code:
//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";

//remove ABC123 and store in $cleanedstr
$cleanedstr = substr_replace($original, "", 0, 6);
//remove DEF321 from $cleanedstr
$cleanedstr2 = substr_replace($cleanedstr, "", -6, 6);

//Echo each string
echo "Original String: $original
";

echo "Clean #1: $cleanedstr
";

echo "Clean #2: $cleanedstr2";

Display:
Original String: ABC123 Hello Mr. Cow! DEF321
Clean #1: Hello Mr. Cow! DEF321
Clean #2: Hello Mr. Cow!

Make sure that you play around with this function some on your own so you can get a feel for how the starting point and length parameters effect this function.

substr_replace Perform an Insert
By setting the length parameter to zero you can stop substr_replace from removing anything from the original string and just add to it.

If we wanted to add a second and third person to our $original string we would want to do this insert operation. Note: instead of counting the characters we've used a couple other PHP functions to figure out the starting positions for us.

PHP Code:
//string that needs to be customized
$original = "Hello Mr. Cow!";

// Get the position of Mr. Cow
$cowpos = strpos($original, "Mr. Cow");

// Find where Mr. Cow ends by adding the length of Mr. Cow
$cowpos_end = $cowpos + strlen("Mr. Cow");

// Insert Mrs. Bear after Mr. Cow
$mrsbear = substr_replace($original, " and Mrs. Bear", $cowpos_end, 0);

// Insert Sensei Shark before Mr. Cow
$senseishark = substr_replace($mrsbear, "Sensei Shark, ", $cowpos, 0);


//Echo each string
echo "Original String: $original
";

echo "After Mrs. Bear: $mrsbear
";

echo "After Sensei Shark: $senseishark";

Display:
Original String: Hello Mr. Cow!
After Mrs. Bear: Hello Mr. Cow and Mrs. Bear!
After Sensei Shark: Hello Sensei Shark, Mr. Cow and Mrs. Bear!

We snuck a new function strlen into that example, but it isn't that complicated of a function, as it stands for "string length."

* $cowpos_end = $cowpos + strlen("Mr. Cow");

The strlen function takes a string and then counts up how many characters are in it then returns that number. So by calculating the length of "Mr. Cow" and adding that to the position, we find out where the end point is!

PHP - String Explode

The PHP function explode lets you take a string and blow it up into smaller pieces. For example, if you had a sentence you could ask

explode to use the sentence's spaces " " as dynamite and it would blow up the sentence into separate words, which would be stored

in an array. The sentence "Hello, I would like to lose weight." would look like this after explode got done with it:

1. Hello,
2. I
3. would
4. like
5. to
6. lose
7. weight.

The dynamite (the space character) disappears, but the other stuff remains, but in pieces. With that abstract picture of the explode

function in mind, lets take a look at how it really works.
The explode Function

The first argument that explode takes is the delimiter (our dynamite) which is used to blow up the second argument, the original string.

explode returns an array of string pieces from the original and they are numbered in order, starting from 0. Lets take a phone number

in the form ###-###-#### and use a hyphen "-" as our dynamite to split the string into three separate chunks.

PHP Code:

$rawPhoneNumber = "800-555-5555";

$phoneChunks = explode("-", $rawPhoneNumber);
echo "Raw Phone Number = $rawPhoneNumber
";

echo "First chunk = $phoneChunks[0]
";

echo "Second chunk = $phoneChunks[1]
";

echo "Third Chunk chunk = $phoneChunks[2]";

Display:
Raw Phone Number = 800-555-5555
First chunk = 800
Second chunk = 555
Third Chunk chunk = 5555
explode Function - Setting a Limit

If you want to control the amount of destruction that explode can wreak on your original string, consider using the third (optional)

argument which allows you to set the number of pieces explode can return. This means it will stop exploding once the number of

pieces equals the set limit. Below we've blown up a sentence with no limit and then with a limit of 4.

PHP Code:

$someWords = "Please don't blow me to pieces.";

$wordChunks = explode(" ", $someWords);
for($i = 0; $i <>
echo "Piece $i = $wordChunks[$i]
";

}

$wordChunksLimited = explode(" ", $someWords, 4);
for($i = 0; $i <>
echo "Limited Piece $i = $wordChunksLimited[$i]
";

}

Display:
Piece 0 = Please
Piece 1 = don't
Piece 2 = blow
Piece 3 = me
Piece 4 = to
Piece 5 = pieces.
Limited Piece 0 = Please
Limited Piece 1 = don't
Limited Piece 2 = blow
Limited Piece 3 = me to pieces.

The limited explosion has 4 pieces (starting from 0, ending at 3). If you forgot how a for loop works, check out PHP For Loops.

PHP - Array implode

PHP implode - Repairing the Damage

The first argument of implode is the string of characters you want to use to join the array pieces together. The second argument is the array (pieces).

PHP Code:

$pieces = array("Hello", "World,", "I", "am", "Here!");

$gluedTogetherSpaces = implode(" ", $pieces);
$gluedTogetherDashes = implode("-", $pieces);
for($i = 0; $i <>
echo "Piece #$i = $pieces[$i]
";

}
echo "Glued with Spaces = $gluedTogetherSpaces
";

echo "Glued with Dashes = $gluedTogetherDashes";


Display:
Piece #0 = Hello
Piece #1 = World,
Piece #2 = I
Piece #3 = am
Piece #4 = Here!
Glued with Spaces = Hello World, I am Here!
Glued with Dashes = Hello-World,-I-am-Here!


The implode function will convert the entire array into a string and there is no optional argument to limit this as there was in the explode function.

PHP Pattern

Singleton Pattern
The singleton pattern applies to those situations in which there needs to be a single instance of a class. Implementing this pattern makes this single instance easily accessible by many other objects.

Example


class Example
{
// Hold an instance of the class
private static $instance;
// A private constructor; prevents direct creation of object
private function __construct()
{
echo 'I am constructed';
}

// The singleton method
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}

// Example method
public function bark()
{
echo 'Woof!';
}

// Prevent users to clone the instance
public function __clone()
{

trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
?>

Magic Methods
The function names _construct, _sleep, _wakeup, _tostring are all magical methods in PHP. There cannot be any functions with these names in the classes. These functions can be had only if we want the magical functionality associated with them.

_sleep
The _sleep magic method is used to close any database connections that the object may have. It is also used to commit pending data and perform similar cleanup tasks. It is also used if there are very large objects which do not have to be saved completely.

_wakeup
The _wakeup magic method is used to reconstruct any resources that the object may have. The basic function of _wakeup is to reestablish any database connections that may have been lost during serialization and perform other initialization tasks.

Example of sleep and wakeup


class Conn {
protected $link;
private $server, $username, $password, $db;
public function __construct($server, $username, $password, $db)
{
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}

private function connect()
{
$this->link = mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->db, $this->link);
}

public function __sleep()
{
mysql_close($this->link);
}

tostring
The _tostring magic method allows a class to decide that how it will react when it is converted to string.

Example


// Declare a simple class
class Test
{
public $foo;
public function __construct($foo) {
$this->foo = $foo;
}

public function __toString() {
return $this->foo;
}
}

$class = new Test('Hello');
echo $class;
?>

Cloning
An object copy is created by using the clone keyword. An object's __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. If a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

Example


class SubObject
{
static $instances = 0;
public $instance;
public function __construct() {
$this->instance = ++self::$instances;
}

public function __clone() {
$this->instance = ++self::$instances;
}
}

class MyCloneable
{
public $object1;
public $object2;
function __clone()
{

// Force a copy of this->object, otherwise
// it will point to same object.
$this->object1 = clone($this->object1);
}
}

$obj = new MyCloneable();
$obj->object1 = new SubObject();
$obj->object2 = new SubObject();
$obj2 = clone $obj;
print("Original Object:\n");
print_r($obj);
print("Cloned Object:\n");
print_r($obj2);
?>

PHP OOPS - Classes and Objects

Classes and Objects are considered to be the most useful and dynamic aspects of a programming language. In PHP, classes are used extensively and are very useful. The concept of classes allows for better performance and more features.

What is a Class?
The Class in PHP is basically the same as in other languages such as Java. The class definition begins with the keyword class, followed by a class name. The form name can be any name except a reserved word or keyword in PHP. The class name is followed by a pair of curly braces which contain the definition of class members and methods.

Example of a Class

Class abc
{
//member functions and variables go here
}
?>

What is an Object?
An Object is an enclosed bundle of variables and functions which is copied from a Class. Objects provide an easy interface and hide a lot of their inner workings. The object sends orders through special functions called methods and they can return information.

While creating a Class, a set of characteristics is laid down. By creating Objects of that type, entities are created that share these characteristics but the Object might initialize them as different values.

Example
Suppose there is a class named building. This class would have a characteristic named floor. All the objects of class building would share the characteristics of floor, but some would initialize it to “one”, some to “two”, others to “three” or “four”, and so on.

The benefit of object oriented code is that it is re-useable. In this the classes can be used to create different objects and classes from one project can be used in other projects as well. Child classes can also be created which inherits the properties of the parent classes.

Creating an Instance
To start with, a class having no member functions and variables is not useful. For a class to be completely useful, member functions and variables have to be added in that class.

Let’s take an example of a class with a variable in it.

Example

Class abc
{
$a = “Hello!”;
}
?>

The class abc is the basis from which many objects can be instantiated. The new keyword is used to create an object. Now any abc object that is created contains a property called $a with the value of “Hello”. This property can be accessed and even be changed with the help of objects.

In this the -> operator is used to access or change the properties of the object.

In the following example $obj1 and $obj2 are the objects of the class abc. In this $obj2 has been assigned the string “Welcome to expertrating!” to its $a property.

Example

Class abc
{
var $a = "Hello";
}

$obj1 = new abc();
$obj2 = new abc();
$obj2->a = "Welcome to expertrating!";
echo "$obj1->a
";

echo "$obj2->a
";

?>

Extends
Another feature of object oriented programming is used in PHP, which is inheritance. In PHP a class a class can inherit methods, functions and members of other class by using the extends keyword in the declaration. In PHP it is not possible to inherit from multiple classes, a class can inherit from only one base class.

The class from which inheritance is done is called the parent class or base class and the class which inherits is called the child class.

The Keyword Final
The final keyword prevents the child classes from overriding a method. This can be done by prefixing the method with the keyword final. If the complete class is being defined as final then that class cannot be extended.

Example

final class test
{
//methods and functions
}

The class defined above i.e. class test cannot be overloaded as it has been finalized by using the keyword final with it.

Abstract
A new concept of abstract classes and methods has been introduced in PHP5. When a class is defined as abstract then it is not allowed to create the instance of that class. A class that contains at least one abstract method must also be abstract. The methods defined as abstract cannot define the implementation; they just declare the method’s signature.

When a child class is inheriting from an abstract parent class, then all the methods marked abstract in parent class declaration must also be additionally defined by the child class. These methods must be defined with the same or weaker access. This means that if an abstract method is declared as protected in the parent class then it must be declared either as protected or public in the child class.

Static Keyword
When class members or methods are declared as static then there is no need to instantiate that class. These members and methods are accessible without the instantiation of the class. If a member is declared as static then it cannot be accessed by an instantiated class object, but a method declared as static can be accessed by an instantiated class object.

The static declaration of a class must be after the visibility declaration (means that after the member or method has been declared as public, protected, or private).

The static method calls are resolved at compile time and static properties cannot be accessed through the object through the arrow operator (->).

Interfaces
Object interfaces allow the creation of a code which specifies that which method a class must implement, without having to define how these methods have to be handled.

Interfaces are defined in the same way as a class is defined. These interfaces are defined with the keyword “interface”. In the interface the contents of the methods do not have to be defined and all the methods declared in the interface must be declared as public.

Implementation of Interfaces
To implement an interface, the implements operator is used. The methods must be defined before implementation and all the methods in the interface must be implemented within a class.


Exceptions
Exception handling in PHP is similar to that of other programming languages. Within a PHP block of code we can throw, try and catch an exception. There must be at least one catch block in a try block. In this multiple catch blocks can be used to catch different class types. In exception handling the execution will continue after the last catch block has been encountered and exceptions can be thrown within catch blocks.

In exception handling when an exception is thrown, the code following the statement will not be executed rather PHP will attempt to find the first matching catch block. If the exception is not caught then it will result in a fatal error with an uncaught exception message.

This chapter will be focusing on some advanced class concepts, which will empower the reader to use classes in a better way and to create dynamic web pages.


Constructor
In PHP 5 developers can declare constructor methods for classes. In this, those classes which have a constructor method call this method for each newly created object. So, it is suitable for any initialization that the object may need before it is used. In this the parent constructors are not called implicitly if the child class defines a constructor.

Example

class ParentClass {
function __construct() {
print "In ParentClass constructor\n";
}
}

class ChildClass extends ParentClass {
function __construct() {
parent::__construct();
print "In ChildClass constructor\n";
}
}

$obj = new ParentClass();
$obj = new ChildClass();
?>


Destructors
The destructor concept is introduced in PHP 5. This destructor concept is similar to other object oriented languages. In this the destructor will be called as soon as all references to a particular object have been removed or when the object has been explicitly destroyed.

Example

class MyClass {
function __construct() {
print "In constructor\n";
$this->name = "MyClass";
}

function __destruct() {
print "Destroying " . $this->name . "\n";
}
}

$obj = new MyClass();
?>

Advanced PHP Topics - Superglobals

In the previous chapters the concept of global variable was explained. A global variable is a variable declared at the top of the script outside the function. This variable is available to the complete script. Superglobal variables are arrays built into PHP. These superglobal variables are populated automatically with useful elements, and they are available in any scope. A superglobal array can be accessed within a function or a method without using the global keyword.

PHP Superglobals


* $_COOKIE – It contains values provided to the script via HTTP cookies.

* $_GET – It contains variables submitted to the script using HTTP get method.

* $_POST – It contains variables submitted to the script using HTTP post method.

* $_REQUEST – It is a combined array containing values from the $_GET, $_POST, and $_COOKIES superglobal arrays.

* $_ENV – It contains keys and values set by the script’s shell.

* $_FILES – It contains information about uploaded files.

* $_SERVER – It contains variables made available by the server.

* $GLOBALS – It contains all the global variables associated with the current script.

Instanceof Operator

The instanceof operator in PHP is used to determine whether a given object, the parents of that object, or its implemented interfaces are of a specified object class.

Example



class X { }
class Y { }
$thing = new X;
if ($thing instanceof X) {
echo 'X';
}
if ($thing instanceof Y) {
echo 'Y';
}
?>

Declare
The declare statement is used to set execution directives for a block of code. The syntax of the declare statement is similar to the syntax of other flow control statements.
Syntax

declare (directive)

statement
The directive section allows the behavior of the declare block to be set. In this only one directive is recognized, which is the ticks directive.

[ Ticks - A tick is an event that occurs for every N low level statements, which are executed within the declare block. The value of N is specified using the statement ticks = N in the directive section.]

The statement part of the declare block will be executed according to the directives set in the directive block.

Example



// how to use declare:
// the first way:
declare(ticks=1) {
// entire script here
}
// the second way:
declare(ticks=1);
// entire script here
?>

Sunday, September 7, 2008

Resizing images with PHP

* File: SimpleImage.php
* Author: Simon Jarvis
class SimpleImage {

var $image;
var $image_type;

function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}

function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}

function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}

function getWidth() {
return imagesx($this->image);
}

function getHeight() {
return imagesy($this->image);
}

function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}

function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}

function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}

function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
?>

-------------------Usage-------------------

Save the above file as SimpleImage.php and take a look at the following examples of how to use the script.

The first example below will load a file named picture.jpg resize it to 250 pixels wide and 400 pixels high and resave it as picture2.jpg

 include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resize(250,400);
$image->save('picture2.jpg');
?>

If you want to resize to a specifed width but keep the dimensions ratio the same then the script can work out the required height for you, just use the resizeToWidth function.


include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth(250);
$image->save('picture2.jpg');
?>

You may wish to scale an image to a specified percentage like the following which will resize the image to 50% of its original width and height

 include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->scale(50);
$image->save('picture2.jpg');
?>

You can of course do more than one thing at once. The following example will create two new images with heights of 200 pixels and 500 pixels

 include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToHeight(500);
$image->save('picture2.jpg');
$image->resizeToHeight(200);
$image->save('picture3.jpg');
?>

The output function lets you output the image straight to the browser without having to save the file. Its useful for on the fly thumbnail generation


header('Content-Type: image/jpeg');
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth(150);
$image->output();
?>


More Information:

This script will eventually be developed further to include functions
for easily sharpening, bluring, cropping, brightening and colouring images.