Friday, January 25, 2008

Tutorial: Writing Classes in PHP

Some consider classes one of the hardest components of PHP to figure out, but the reality is that classes are extremely straightforward and easy to use. The trouble comes from the fact that not all programmers have worked with Object-Oriented Programming (OOP) before.

Classes are little more than a container for variables and functions affecting those variables, but they can be very useful for building small components - almost miniture programs. The difference is that you dont need to shell out to them or anything, and they can be plugged into most scripts with ease - Just a require or include statement at the top. A class describes an 'object'. An object is a collection of smaller objects, just like in a class. Say for instance, we want to describe a simple door lock. A lock class might contain:

variable $Bolt
variable $Position

function TurnKey( $Direction, $Distance )
function CheckLock( )

TurnKey would accept a direction value that would in turn determine if the bolt should be locked or unlocked. Once the key is turned far enough in either direction ($Distance) the Bolt will either set or clear. The $Bolt variable shows the current state of the door lock, and $Position is used to track how far the key has been turned in any direction. Now, obviously this could all be done with regular variables and functions, and if you only need to use one lock in the code, it would probably work just fine. But what if you want more than one lock? One if you wanted more details about the lock, or even something else? Maybe you want a door in the code, too - And the lock would just be a subset of the door. Maybe you have a whole house. You might have more than one door, or you might not. But each door certainly needs a lock. You can see how complex object-related problems can get.

By using classes, you can define an object once, and then include it in several scripts also. You'll be assured that your object will funciton the same in all of the scripts! Its good practice to write your classes in a seperate file usually, that way you only have to change it in one location. Make full use of PHP's include and require functions, they have many uses.

In the next section, I will walk you through creating a simple class.

Class Structures

For lack of a better example right now, i'm going to show you how to create a simple page object. The page object encompasses a few of the basic page necessities in building an HTML page. Now, there is a lot more you could do with this class, but i'm going to keep it simple for the time being. You guys can expand on it if want later. Okay, lets start by looking at what the basic elements of an HTML page are. First, you have the open and closing tags, and . Those will need to be included in the output. Also, you have the page Title, Keywords for the Metatag field, and naturally the main content, or body. Now that we know what we need, lets start building our class.

First thing we need is the class itself:




This is a basic class. No variables, no functions, nothing - Completely empty. All class structures look the same here with the exception of the 'Page' name. Every class/object is assigned a name for reference. You'll need to know this to create new copies of the object, so pick something straightforward and sensible.

Next, we need to put in our variables. We need a title for the page, keywords, and a content body, like so:




Now, we could actually start using the class here. We have an object. But it isn't done - We still want to add some functions, to make it easier to work with.

What functions do we need? Well, we need something to build the output HTML. Lets call that 'Display'. Lets create simple functions for displaying the Title and Keywords, also. Lets make a function for setting the content as well.

The final class code is:

\n\n";
$this->DisplayTitle( );
$this->DisplayKeywords( );
echo "\n\n\n";
echo $this->Content;
echo "\n\n\n";
}

function DisplayTitle( ) {
" . $this->Title . " echo "\n";
}

function DisplayKeywords( ) {
echo 'Keywords . '">';
}

function SetContent( $Data ) {
$this->Content = $Data;
}
}
?>

Now, at first glance this looks pretty simple. And you know what? It is. Its just basic PHP code wrapped into a class. Let me point a few things out before we go any farther though.

VAR -
All variables declared in the class must be placed at the top of the class structure, and preceeded with the VAR statement.
$THIS -
$this is a variable that incidates the current object. That way, the object knows how to find itself while running functions contained within it.
For instance, $this->Keywords gets the data from the $Keywords variable in the object. You'll also notice that when using variables contained
within a class, you can't use the $ to reference them - But you have to use it to reference the object itself.

Lets save this class file out before we continue. If your following along, save it out as page.class for now. You'll need it for the example coming up.
Using the Class

Now that we have a class created, lets try using it in a normal script.

This page was generated by the Page Class example.

";

$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent( $Content );

$Sample->Display( );

?>

Doesn't get much simpler than that, does it? We use the include statement to bring in the class from its external file. We use the 'new' statement to create a new copy of the object so we can work with it. The new copy is stored into a variable called $Sample. Then we just set some variables - The Title, Keywords and Content - And use the Display function to output it. Easy or what?

[Via - Tutorial: Writing Classes in PHP] Garbage Bags Make Money Online

Forum Login using cURL

Forum Login using cURL

In this article, we're going to walk you through how you might
login to a forum such as phpbb2 programatically. First off, why
would you care to do such a thing? Well, out of the box forum
scripts such as SMF and phpbb2 won't make much impact on their
own for simply that reason, that they are out of the box and a
few clicks in cPanel or Plesk can get you up and running in a
couple of minutes. Ordinarily, to pack any punch (and of course
to be useful and provide value to the end user), the forum script
of choice will need to be installed and integrated as part of a
larger container site.

Now that that scenario has been painted, continue down this
imaginary path ever so briefly. Say you have an existing members
area with which you wish to integrate your new forum, it would be
generally unacceptable practice to ask your users to first login
to your existing members area and then once inside, ask them to
login again to the forum.

We won't go over in detail the whole integration process here,
just the actual login process which is definitely the most
complicated aspect of integration. For the sake of completeness,
the other aspects of integration include creating the record in
the new forum when a user signs up to your existing
'members-only' area, deleting the record if their account becomes
deactivated and ensuring database integrity on account management
functions, i.e. the user changing their password, their username,
language preferences &c.

At a high level of abstraction, this is what we are going to do;
we are going to validate the supplied username and password using
our existing login system. Then we are going to establish any
session variables and cookies that we use in our existing system,
i.e. you might set a cookie with the md5'd value of the users
password along with their id and validate this each time the user
requests a 'members-only' page. After that, we will construct a
cURL request to our forum login page passing along the supplied
username and password and a bit of other information which we'll
get to shortly. We process the response including cookies and the
session id and then we redirect over to our 'members-only' index
page. Done and dusted!

Let's get down to it. We'll encapsulate this logic in a function
called checkLogin which will take 3 parameters (the
supplied username, the supplied password and a flag indicating
whether the user would like us to remember him/her on subsequent
visits). The function which logs a user into a phpbb2 forum might
look like this:




/*
$pu = passed username
$pp = passed password
$pr = passed remember flag
*/

function checkLogin($pu, $pp, $pr)
{

// Validate the username password combo
// using the current system. This assumes
// that you are working off a table called
// members and that all user passwords are
// stored as md5'd strings.

$sql = "SELECT * FROM members WHERE username = '$pu' AND
password = '".md5($pp)."' LIMIT 1;";
$result = mysql_query($sql, $GLOBALS['db']);
if (mysql_num_rows($result)>0)
{

// At this point, we have validated the
// user credentials, we should now
// perform any perfunctory login actions,
// such as setting cookies for remembering
// the user, establishing the session
// variables. Details on this are beyond
// the scope of this article.

setSession(mysql_fetch_array($result), $pr);

// This is where it gets interesting,
// construct an array of POST variables
// that will be passed to the login script
// of the phpbb2 forum. To modify this
// function for a different forum,
// download a HTTP packet sniifer (such
// as HTTPLook), login to your forum in
// the normal manner and see what POST
// variables are passed to the login
// script in the HTTP request. Then simply
// replicate those variables here.

$post_data = array();
$post_data['username'] = $pu;
$post_data['password'] = $pp;
$post_data['autologin'] = ($pr) ? 'on' : '';
$post_data['login'] = 'Log in';

// The forum login script may attempt to
// set cookies depending on what the login
// mode is (i.e. whether the user should be
// remembered or not). To facilitate that
// functionality, we need to define a
// temporary file to hold the contents of
// the cookie.

$cookie_new = tempnam("/tmp","MKUP");

// Construct the cURL request, the
// options to note here are:
// 1) The URL of the forum login script
// using CURLOPT_URL
// 2) The incorporation of post data using
// CURLOPT_POST/CURLOPT_POSTFIELDS
// 3) The cookie handlers, CURLOPT_COOKIEFILE
// and CURLOPT_COOKIEJAR
// 4) The inclusion of the response header
// in the result using CURLOPT_HEADER

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
"http://mysite.com/forum/login.php");
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_new);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_new);
curl_setopt($ch, CURLOPT_HEADER,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Storing the result of the request
// including the HTTP response header is
// highly recommended as it can be used most
// effectively to decipher what, if anything,
// has gone wrong.

$postResult = curl_exec($ch);

// Trigger any cURL related errors at this point

if (curl_errno($ch))
{
// Trigger error
}

// Close the cURL session

curl_close($ch);

// If everything went according to plan,
// the contents of any cookies the login
// script wanted to set will be stored in
// $cookie_new. At this point then we must
// actually set the cookies as simply requesting
// them via cURL will not set them on the client
// browser. Read the contents into a variable
// using the file_get_contents function.

$cookie_status = array();
$cookie_contents = file_get_contents($cookie_new);

// Now that we have the contents of the
// "cookie jar", we can delete the temporary
// file to save resources.

if(file_exists($cookie_new))
{
unlink($cookie_new);
}

// Split the jar into it's individual cookies
// by using the "\n" delimiter.

$cookie_contents_array = explode("\n",$cookie_contents);

// Cycle through each cookie in
// $cookie_contents_array and if the cookie
// applies to our domain "mysite.com",
// process it. It's hard to imagine a situation
// where a cookie belonging to another domain
// would get into the temporary cookie file yet
// I can't help but check!

for($i = 0; $i < cookie_array =" explode(" expires=".date(" path="/" path="/" phpsessid=".session_id()." path="/" url="/members/index.php&delay=" equiv="refresh" content="">;url=">







This way, the page where the cookies were sent in the header
actually loads, but the user doesn't really see this. This gives
your cookies the best chance of actually being interpreted and
processed by the browser. All your unsuspecting user sees is the
"members-only" index page after the meta refresh. Easy as!

That's it, I hope this article offers a little bit of insight
into the faculty of remote login using cURL. It need not apply
specifically to phpbb2 or even a forum, it can be used to login
to any web based login system where, of course, you are
privileged to have the password. Enjoy!

As with all articles on Celtic Productions, this article is
protected by international copyright laws. It may be linked to
(we are of course most grateful of links to our articles),
however, it may never be reproduced without the prior express
permission of its owners, Celtic Productions. It's not a case of
writing to Sony Music and asking can you lawfully reproduce and
distribute their hottest selling CD, if you do actually want to
reproduce this article on your website, just ask, you might be
surprised ;-)

[Via - Forum Login using cURL]2.

Practical Web 2.0 Applications with PHP by Quentin Zervaas released

The owner of PhpRiot, Quentin Zervaas, has released his first PHP book, entitled Practical Web 2.0 Applications with PHP. This book walks the reader through creating a complete web application from start to finish.

The back cover of the book reads as follows:

Many programming books on the market today focus specifically on a particular methodology or software package, and although you will gain a solid understanding of the subject matter from these books, you won't always know how to apply what you've learned in a real-world situation. This book is designed to show you how to bring together many different ideas and features by starting with a clean slate and gradually building the code base so it evolves into a complete web application.
Read the rest of the back cover »

The premise of the application we build in this book is that it is a "Web 2.0" application. What this means is that (among other things) our application generates accessible and standards-compliant code while making heavy of use of Ajax. We achieve this by using the Smarty Template Engine and Cascading Style Sheets, as well as the Prototype JavaScript library. Additionally, we create a fun and intuitive interface by applying simple visual effects on various pages using the Scriptaculous JavaScript library.

To help with the development of the extensive PHP code in this book, we use the Zend Framework. This is an open source PHP 5 library that contains many different components that you can easily use in any of your day-to-day development. We use many of the Zend Framework components in this book, such as database abstraction (with a focus on MySQL and PostgreSQL), logging, authentication, and search.

The application we build in this book is a collaborative blogging tool. It will allow users to register and create a personal blog. When creating blog posts, users will be able upload images, apply tags, and assign locations (using Google Maps). We will also look at how to use microformats when displaying user blog posts.

More information about can be found on this web site at
Web 2.0 Applications with PHP.

Monitoring File Uploads using Ajax and PHP

Introduction

Because of the limitations of HTTP, it is difficult to monitor the status of files as they are uploaded via HTML forms. While other programming languages have built-in methods to monitor file uploads, PHP does not. This article shows how to implement such a solution in PHP.

In order to achieve this, the APC (Alternative PHP Cache) PHP extension is required, as well as PHP 5. Specifically, APC 3.0.13 or newer and PHP 5.2 or newer are required for the code in this article to work. We will cover installation of APC in the next section. It is assumed you already have a working PHP 5.2 installation.

In this article we will develop a solution that will allow users to upload a file from their computer using HTML forms. We will then determine the progress of the upload while it is in progress using Ajax, and display the status to the user.

In addition to using PHP, we will also be using the Prototype JavaScript library (version 1.6.0), which you can download for free from http://www.prototypejs.org.

The steps we will follow in this article are as follows:

* Installation of the APC extension for PHP.
* How to monitor uploads using APC.
* Creating a PHP class to manage file uploads.
* Implementing a traditional file uploader.
* Extending the uploader to display upload status.

* Next: Installing APC

[Via - Ajax and PHP]