Tải bản đầy đủ (.pdf) (10 trang)

Học php, mysql và javascript - p 44 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.58 MB, 10 trang )

Example 20-3. rnsetup.php
<?php // rnsetup.php
include_once 'rnfunctions.php';
echo '<h3>Setting up</h3>';
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
Example 20-4. index.php
<?php // index.php
include_once 'rnheader.php';
echo "<h3>Home page</h3>
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 Exam-
ple 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 user-
name 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 func-
tion 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 iden-
tified that the username Robin is available.
412 | Chapter 20: Bringing It All Together
Figure 20-2. The sign-up page
Example 20-5. rnsignup.php
<?php // rnsignup.php
include_once 'rnheader.php';
echo <<<_END
<script>
function checkUser(user)
{
if (user.value == '')
{
document.getElementById('info').innerHTML = ''
return
}
params = "user=" + user.value
request = new ajaxRequest()
request.open("POST", "rncheckuser.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)

rnsignup.php | 413
{
document.getElementById('info').innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
}
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}

catch(e3)
{
request = false
}
}
}
return request
}
</script>
<h3>Sign up Form</h3>
_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<br /><br />";
}
else
414 | Chapter 20: Bringing It All Together
{
$query = "SELECT * FROM rnmembers WHERE user='$user'";
if (mysql_num_rows(queryMysql($query)))
{
$error = "That username already exists<br /><br />";
}
else

{
$query = "INSERT INTO rnmembers VALUES('$user', '$pass')";
queryMysql($query);
}
die("<h4>Account created</h4>Please Log in.");
}
}
echo <<<_END
<form method='post' action='rnsignup.php'>$error
Username <input type='text' maxlength='16' name='user' value='$user'
onBlur='checkUser(this)'/><span id='info'></span><br />
Password <input type='text' maxlength='16' name='pass'
value='$pass' /><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<input type='submit' value='Signup' />
</form>
_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). In-
stead, 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 Exam-
ple 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 im-
plementation works.
Example 20-6. rnsignup.php (YUI version)
<?php // rnsignup.php (YUI version)

include_once 'rnheader.php';
echo <<<_END
<script src="yahoo-min.js"></script>
<script src="event-min.js"></script>
<script src="connection-min.js"></script>
<script>
function checkUser(user)
{
rnsignup.php (YUI version) | 415
if (user.value == '')
{
document.getElementById('info').innerHTML = ''
return
}
params = "user=" + user.value
callback = { success:successHandler, failure:failureHandler }
request = YAHOO.util.Connect.asyncRequest('POST',
'rncheckuser.php', callback, params);
}
function successHandler(o)
{
document.getElementById('info').innerHTML = o.responseText;
}
function failureHandler(o)
{
document.getElementById('info').innerHTML =
o.status + " " + o.statusText;
}
</script>
<h3>Sign up Form</h3>

_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<br /><br />";
}
else
{
$query = "SELECT * FROM rnmembers WHERE user='$user'";
if (mysql_num_rows(queryMysql($query)))
{
$error = "That username already exists<br /><br />";
}
else
{
$query = "INSERT INTO rnmembers VALUES('$user', '$pass')";
queryMysql($query);
}
die("<h4>Account created</h4>Please Log in.");
}
416 | Chapter 20: Bringing It All Together
}
echo <<<_END
<form method='post' action='rnsignup.php'>$error
Username <input type='text' maxlength='16' name='user' value='$user'

onBlur='checkUser(this)'/><span id='info'></span><br />
Password <input type='text' maxlength='16' name='pass'
value='$pass' /><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<input type='submit' value='Signup' />
</form>
_END;
?>
rncheckuser.php
To
go with rnsignup.php
, here’s Example 20-7, rncheckuser.php, the program that looks
up a username in the database and returns a string indicating whether it has already
been taken. Because it relies on the functions sanitizeString and queryMysql, the pro-
gram first includes the file rnfunctions.php.
Then, if the $_POST variable 'user' has a value, the function looks it up in the database
and, depending on whether it exists as a username, outputs either “Sorry, already
taken” or “Username available.” Just checking the function mysql_num_rows against the
result is sufficient for this, as it will return 0 for not found, or 1 if it is found.
The HTML entity &larr; is also used to preface the string with a little left-pointing
arrow.
Example 20-7. rncheckuser.php
<?php // rncheckuser.php
include_once 'rnfunctions.php';
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$query = "SELECT * FROM rnmembers WHERE user='$user'";
if (mysql_num_rows(queryMysql($query)))
echo "<font color=red>&nbsp;&larr;

Sorry, already taken</font>";
else echo "<font color=green>&nbsp;&larr;
Username available</font>";
}
?>
rnlogin.php
With users now able to sign up to the site, Example 20-8, rnlogin.php, provides the
code needed to let them log in. Like the sign-up page, it features a simple HTML form
rnlogin.php | 417
and some basic error checking, as well as using sanitizeString before querying the
MySQL database.
The main thing to note here is that, upon successful verification of the username and
password, the session variables 'user' and 'pass' are given the username and password
values. As long as the current session remains active these variables will be accessible
by all the programs in the project, allowing them to automatically provide access to
logged-in users.
You may be interested in the use of the die function upon successfully logging in. This
is used because it combines an echo and an exit command in one, thus saving a line of
code.
When you call this program up in your browser, it should look like Figure 20-3. Note
how the <input > type of password has been used here to mask the password with
asterisks to prevent it from being viewed by anyone looking over the user’s shoulder.
Figure 20-3. The login page
Example 20-8. rnlogin.php
<?php // rnlogin.php
include_once 'rnheader.php';
echo "<h3>Member Log in</h3>";
$error = $user = $pass = "";
if (isset($_POST['user']))
{

$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
418 | Chapter 20: Bringing It All Together
if ($user == "" || $pass == "")
{
$error = "Not all fields were entered<br />";
}
else
{
$query = "SELECT user,pass FROM rnmembers
WHERE user='$user' AND pass='$pass'";
if (mysql_num_rows(queryMysql($query)) == 0)
{
$error = "Username/Password invalid<br />";
}
else
{
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
die("You are now logged in. Please
<a href='rnmembers.php?view=$user'>click here</a>.");
}
}
}
echo <<<_END
<form method='post' action='rnlogin.php'>$error
Username <input type='text' maxlength='16' name='user'
value='$user' /><br />
Password <input type='password' maxlength='16' name='pass'
value='$pass' /><br />

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<input type='submit' value='Login' />
</form>
_END;
?>
rnprofile.php
One
of the
first things that new users may want to do after signing up and logging in
is to create a profile, which can be done via Example 20-9, rnprofile.php. I think you’ll
find some interesting code here, such as routines to upload, resize, and sharpen images.
Let’s start by looking at the main HTML at the end of the code. This is like the forms
you’ve just seen, but this time it has the parameter enctype='multipart/form-data'.
This allows us to send more than one type of data at a time, enabling the posting of an
image as well as some text. There’s also an <input > type of file, which creates a
browse button that a user can press to select a file to be uploaded.
When the form is submitted, the code at the start of the program is executed. The first
thing it does is ensure that a user is logged in before allowing program execution to
proceed. Only then is the page heading displayed.
rnprofile.php | 419
Adding the “About Me” Text
Then the POST variable 'text' is checked to see whether some text was posted to the
program. If so, it is sanitized and all long whitespace sequences (including returns and
line feeds) are replaced with a single space. This function incorporates a double security
check, ensuring that the user actually exists in the database and that no attempted
hacking can succeed before inserting this text into the database, where it will become
the user’s “about me” details.
If no text was posted, the database is queried to see whether any already exists in order
to prepopulate the textarea for the user to edit it.
Adding a Profile Image

Next we move on to the section where the $_FILES system variable is checked to see
whether an image has been uploaded. If so, a string variable called $saveto is created,
based on the user’s username followed by the extension .jpg. For example, user Jill will
cause $saveto to have the value Jill.jpg. This is the file where the uploaded image will
be saved for use in the user’s profile.
Following this, the uploaded image type is examined and is only accepted if it is a jpeg,
png, or gif image. Upon success, the variable $src is populated with the uploaded image
using one of the imagecreatefrom functions according to the image type uploaded. The
image is now in a raw format that PHP can process. If the image is not of an allowed
type, the flag $typeok is set to FALSE, preventing the final section of image upload code
from being processed.
Processing the Image
First, the image’s dimensions are stored in $w and $h using the following statement,
which is a quick way of assigning values from an array to separate variables:
list($w, $h) = getimagesize($saveto);
Then, using the value of $max (which is set to 100), new dimensions are calculated that
will result in a new image of the same ratio, but with no dimension greater than 100
pixels. This results in giving the variables $tw and $th the new values needed. If you
want smaller or larger thumbnails, simply change the value of $max accordingly.
Next, the function imagecreatetruecolor is called to create a new, blank canvas $tw
wide and $th high in $tmp. Then imagecopyresampled is called to resample the image
from $src, to the new $tmp. Sometimes resampling images can result in a slightly blurred
copy, so the next piece of code uses the imageconvolution function to sharpen the image
up a bit.
420 | Chapter 20: Bringing It All Together

×