Tải bản đầy đủ - 0 (trang)
Chapter 20. Bringing It All Together

Chapter 20. Bringing It All Together

Tải bản đầy đủ - 0trang

www.it-ebooks.info

Download at Boykma.Com



• Adding members as friends

• Public and private messaging between members

That’s 8 main elements, but in the end it turned out that because the project would

require a main index.html page and a separate include file for the main functions, 10

PHP program files were required.

I decided to name the project Robin’s Nest, but you have to modify only one line of

code to change this to a name of your choice. Also, all the filenames (except

index.html) start with the letters rn to separate them from any other files you have saved

from this book. If you change these names, make sure you also change all references

across all the files.



About Third-Party Add-Ons

For reasons of simplicity and size, and so that you don’t have to install add-ons to your

server if you don’t wish to, I have deliberately not used either PEAR (see Appendix E)

or Smarty (see Chapter 12) in these examples. But if you plan on extending the code,

I strongly recommend you consider them, as PEAR can make the programming process

simpler. Furthermore, if you will be working with separate designers, Smarty can remove the programming layer from the presentation layer, leaving them free to create

at their heart’s content.

However, where I have implemented an Ajax call, I have also included an alternative

YUI version, as you can use it without installing any software on your server.



On the Website

All the examples in this chapter can be found on the companion website located at

http://lpmj.net, where the code syntax is color-highlighted, making it easier to follow.

You can also download the examples from there to your computer by clicking on the

“Examples” link. This will download an archive file called examples.zip, which you

should extract to a suitable location on your computer.

Of particular interest to this chapter, within the ZIP file there’s a folder called

robinsnest, in which all the following examples have been saved using the correct filenames required by this sample application. So you can easily copy them all to your web

development folder to try them out.



rnfunctions.php

So let’s jump right into the project, starting with Example 20-1, rnfunctions.php, the

include file of main functions. This file contains a little more than just the functions,

though, because I have added the database login details here instead of using yet another



406 | Chapter 20: Bringing It All Together



www.it-ebooks.info

Download at Boykma.Com



separate file. So the first half-dozen lines of code define the host, database name, username, and password of the database to use.

It doesn’t matter what you call the database, as long as it already exists (see Chapter 8 for how to create a new database). Also make sure to correctly assign a MySQL

username and password to $dbuser and $dbpass. With correct values, the subsequent

two lines will open a connection to MySQL and select the database. The last of the

initial instructions sets the name of the social networking site by assigning the value

“Robin’s Nest” to the variable $appname. If you want to change the name, here’s the

place to do so.



The Functions

The project uses six main functions:

createTable



Checks whether a table already exists and, if not, creates it.

tableExists



Returns a value of 1 if a table already exists, otherwise 0.

queryMysql



Issues a query to MySQL, outputting an error message if it fails.

destroySession



Destroys a PHP session and clears its data to log users out.

sanitizeString



Removes potentially malicious code or tags from user input.

showProfile



Displays a user’s image and “about me” if they have one.

All of these should be obvious in their action to you by now, with the possible exception

of showProfile, which looks for an image of the name user.jpg (where user is the username of the current user), and if found, displays it. It also displays any “about me” text

the user may have saved.

I have ensured that error handling is in place for all the functions that need it, so that

they can catch any typographical or other errors you may introduce. However, if you

use any of this code on a production server, you will probably want to provide your

own error-handling routines to make the code more user-friendly.

So type this file in and save it as rnfunctions.php and you’ll be ready to move on to the

next section.

Example 20-1. rnfunctions.php


$dbhost

$dbname

$dbuser



rnfunctions.php

= 'localhost';

// Unlikely to require changing

= 'publications'; // Modify these...

= 'username';

// ...variables according



rnfunctions.php | 407



www.it-ebooks.info

Download at Boykma.Com



$dbpass = 'password';

// ...to your installation

$appname = "Robin's Nest"; // ...and preference

mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());

mysql_select_db($dbname) or die(mysql_error());

function createTable($name, $query)

{

if (tableExists($name))

{

echo "Table '$name' already exists
";

}

else

{

queryMysql("CREATE TABLE $name($query)");

echo "Table '$name' created
";

}

}

function tableExists($name)

{

$result = queryMysql("SHOW TABLES LIKE '$name'");

return mysql_num_rows($result);

}

function queryMysql($query)

{

$result = mysql_query($query) or die(mysql_error());

return $result;

}

function destroySession()

{

$_SESSION=array();

if (session_id() != "" || isset($_COOKIE[session_name()]))

setcookie(session_name(), '', time()-2592000, '/');

}



session_destroy();



function sanitizeString($var)

{

$var = strip_tags($var);

$var = htmlentities($var);

$var = stripslashes($var);

return mysql_real_escape_string($var);

}

function showProfile($user)

{

if (file_exists("$user.jpg"))

echo "";

$result = queryMysql("SELECT * FROM rnprofiles WHERE user='$user'");



408 | Chapter 20: Bringing It All Together



www.it-ebooks.info

Download at Boykma.Com



}

?>



if (mysql_num_rows($result))

{

$row = mysql_fetch_row($result);

echo stripslashes($row[1]) . "

";

}



rnheader.php

For uniformity, each page of the project needs to have the same overall design and

layout. Therefore I placed these things in Example 20-2, rnheader.php. This is the file

that is actually included by the other files and it, in turn, includes rnfunctions.php. This

means that only a single include is required in each file.

rnheader.php starts by calling the function session_start. As you’ll recall from Chapter 13, this sets up a session that will remember certain values we want stored across

different PHP files.

With the session started, the program then checks whether the session variable

'user' is currently assigned a value. If so, a user has logged in and the variable

$loggedin is set to TRUE.

Using the value of $loggedin, an if block displays one of two sets of menus. The nonlogged-in set simply offers options of Home, Sign up, and Log in, whereas the loggedin version offers full access to the project’s features. Additionally, if a user is logged in,

his or her username is appended in brackets to the page title and placed before the

menu options. We can freely refer to $user wherever we want to put in the name,

because if the user is not logged in, that variable is empty and will have no effect on the

output.

The only styling applied in this file is to set the default font to Verdana at a size of 2 via

a tag. For a more comprehensive design and layout, you’ll probably wish to

apply CSS styling to the HTML.

Example 20-2. rnheader.php


include 'rnfunctions.php';

session_start();

if (isset($_SESSION['user']))

{

$user = $_SESSION['user'];

$loggedin = TRUE;

}

else $loggedin = FALSE;

echo "$appname";<br /><br />if ($loggedin) echo " ($user)";<br /><br /><br /><br />rnheader.php | 409<br /><br /><br /><br /> www.it-ebooks.info<br /><br />Download at Boykma.Com<br /><br /><br /><br />echo "";

echo "

$appname

";

if ($loggedin)

{

echo "$user:

Home |

Members |

Friends |

Messages |

Profile |

Log out";

}

else

{

echo "Home |

Sign up |

Log in";

}

?>



rnsetup.php

With the pair of included files written, it’s now time to set up the MySQL tables they

will use. This is done with Example 20-3, rnsetup.php, which you should type in and

load into your browser before calling up any other files—otherwise you’ll get numerous

MySQL errors.

The tables created are kept short and sweet, and have the following names and columns:

rnmembers



username user (indexed), password pass

rnmessages



ID id (indexed), author auth (indexed), recipient recip, message type pm, message

message

rnfriends



username user (indexed), friend’s username friend

rnprofiles



username user (indexed), “about me” text

Because the function createTable first checks whether a table already exists, this program can be safely called multiple times without generating any errors.

It is very likely that you will need to add many more columns to these tables if you

choose to expand on this project. If so, you may need to issue a MySQL DROP TABLE

command before recreating a table.



410 | Chapter 20: Bringing It All Together



www.it-ebooks.info

Download at Boykma.Com



Example 20-3. rnsetup.php


include_once 'rnfunctions.php';

echo '

Setting up

';

createTable('rnmembers', 'user VARCHAR(16), pass VARCHAR(16),

INDEX(user(6))');

createTable('rnmessages',

'id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

auth VARCHAR(16), recip VARCHAR(16), pm CHAR(1),

time INT UNSIGNED, message VARCHAR(4096),

INDEX(auth(6)), INDEX(recip(6))');

createTable('rnfriends', 'user VARCHAR(16), friend VARCHAR(16),

INDEX(user(6)), INDEX(friend(6))');

createTable('rnprofiles', 'user VARCHAR(16), text VARCHAR(4096),

INDEX(user(6))');

?>



index.php

This file is a trivial file but necessary nonetheless to give the project a home page. All

it does is display a simple welcome message. In a finished application, this would be

where you sell the virtues of your site to encourage signups.

Incidentally, seeing as all the MySQL tables have been created and the include files

saved, you can now load Example 20-4, index.php, into your browser to get your first

peek at the new application. It should look like Figure 20-1.



Figure 20-1. The main page of the site



index.php | 411



www.it-ebooks.info

Download at Boykma.Com



Example 20-4. index.php


include_once 'rnheader.php';

echo "

Home page



Welcome, please Sign up and/or Log in to join in.";

?>



rnsignup.php

Now we need a module to enable users to join the new network, and that’s Example 20-5, rnsignup.php. This is a slightly longer program, but you’ve seen all its parts

before.

Let’s start by looking at the end block of HTML. This is a simple form that allows a

username and password to be entered. But note the use of the empty span given the

id of 'info'. This will be the destination of the Ajax call in this program that checks

whether a desired username is available. See Chapter 18 for a complete description of

how this works.



Checking for Username Availability

Now go back to the program start and you’ll see a block of JavaScript that starts with

the function checkUser. This is called by the JavaScript onBlur event when focus is

removed from the username field of the form. First it sets the contents of the span I

mentioned (with the id of 'info') to an empty string, which clears it in case it previously

had a value.

Next a request is made to the program rnchecker.php, which reports whether the username user is available. The returned result of the Ajax call, a friendly message, is then

placed in the 'info' span.

After the JavaScript section comes some PHP code that you should recognize from the

Chapter 17 section of form validation. This section also uses the sanitizeString function to remove potentially malicious characters before looking up the username in the

database and, if it’s not already taken, inserting the new username $user and password

$pass.

Upon successfully signing up, the user is then prompted to log in. A more fluid response

at this point might be to automatically log in a newly created user but, as I don’t want

to overly complicate the code, I have kept the sign-up and login modules separate from

each other.

When loaded into a browser (and in conjunction with rncheckuser.php, shown later)

this program will look like Figure 20-2, where you can see that the Ajax call has identified that the username Robin is available.



412 | Chapter 20: Bringing It All Together



www.it-ebooks.info

Download at Boykma.Com



Figure 20-2. The sign-up page

Example 20-5. rnsignup.php


include_once 'rnheader.php';

echo <<<_END



Sign up Form



_END;



XMLHttpRequest()



ActiveXObject("Msxml2.XMLHTTP")



new ActiveXObject("Microsoft.XMLHTTP")



false



$error = $user = $pass = "";

if (isset($_SESSION['user'])) destroySession();

if (isset($_POST['user']))

{

$user = sanitizeString($_POST['user']);

$pass = sanitizeString($_POST['pass']);

if ($user == "" || $pass == "")

{

$error = "Not all fields were entered

";

}

else



414 | Chapter 20: Bringing It All Together



www.it-ebooks.info

Download at Boykma.Com



{



$query = "SELECT * FROM rnmembers WHERE user='$user'";

if (mysql_num_rows(queryMysql($query)))

{

$error = "That username already exists

";

}

else

{

$query = "INSERT INTO rnmembers VALUES('$user', '$pass')";

queryMysql($query);

}



}



}



die("

Account created

Please Log in.");



echo <<<_END

$error

Username
onBlur='checkUser(this)'/>


Password
value='$pass' />


           





_END;

?>



On a production server, I wouldn’t recommend storing user passwords

in the clear as I’ve done here (for reasons of space and simplicity). Instead, you should salt them and store them as MD5 or other one-way

hash strings. See Chapter 13 for more details on how to do this.



rnsignup.php (YUI version)

If you prefer to use YUI, here’s an alternative version of rnsignup.php (see Example 20-6). I have highlighted the main differences in bold type and, as you can see, it’s

substantially shorter. Please refer to Chapter 19 for details on how the YUI Ajax implementation works.

Example 20-6. rnsignup.php (YUI version)


include_once 'rnheader.php';

echo <<<_END









Sign up Form



_END;

$error = $user = $pass = "";

if (isset($_SESSION['user'])) destroySession();

if (isset($_POST['user']))

{

$user = sanitizeString($_POST['user']);

$pass = sanitizeString($_POST['pass']);

if ($user == "" || $pass == "")

{

$error = "Not all fields were entered

";

}

else

{

$query = "SELECT * FROM rnmembers WHERE user='$user'";

if (mysql_num_rows(queryMysql($query)))

{

$error = "That username already exists

";

}

else

{

$query = "INSERT INTO rnmembers VALUES('$user', '$pass')";

queryMysql($query);

}

}



die("

Account created

Please Log in.");



416 | Chapter 20: Bringing It All Together



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 20. Bringing It All Together

Tải bản đầy đủ ngay(0 tr)

×