Bringing all that we have learnt together
Designing a Social Networking Site
Things that are needed include:
• A sign-up process
• A login form
• A logout facility
• Session control
• User profiles with uploaded thumbnails
• A member directory
• Adding members as friends
• Public and private messaging between members
• How to style the project
functions.php
The functions uses five main functions:
createTable:Checks whether a table already exists and, if not, creates it
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” message if he has one
1.functions.php
<?php
$dbhost = 'localhost'; // Unlikely to require changing
$dbname = 'rbgtech'; // Modify these...
$dbuser = 'root'; // ...variables according
$dbpass = ' '; // ...to your installation
$appname = "RBG Tech App"; // ...and preference
$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);
function createTable($name, $query)
{
queryMysql("CREATE TABLE IF NOT EXISTS $name($query)");
echo "Table '$name' created or already exists.<br>";
}
function queryMysql($query)
{
global $connection;
$result = $connection->query($query);
if (!$result) die($connection->error);
return $result;
}
function destroySession( )
{
$_SESSION=array();
if (session_id() != "" || isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time()-2592000, '/');
session_destroy();
}
function sanitizeString($var)
{
global $connection;
$var = strip_tags($var);
$var = htmlentities($var);
$var = stripslashes($var);
return $connection->real_escape_string($var);
}
function showProfile($user)
{
if (file_exists("$user.jpg"))
echo "<img src='$user.jpg' style='float:left;'>";
$result = queryMysql("SELECT * FROM profiles WHERE user='$user'");
if ($result->num_rows)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo stripslashes($row['text']) . "<br style='clear:left;'><br>";
}
}
?>
header.php
For uniformity, each page of the project needs to have access to the same set of fea‐
tures. Therefore,I placed these things in header.php
2.header.php
<?php
session_start();
echo "<!DOCTYPE html>\n<html><head>";
require_once 'functions.php';
$userstr = ' (Guest)';
if (isset($_SESSION['user']))
{
$user = $_SESSION['user'];
$loggedin = TRUE;
$userstr = " ($user)";
}
else $loggedin = FALSE;
echo "<title>$appname$userstr</title><link rel='stylesheet' " .
"href='styles.css' type='text/css'>" .
"</head><body><center><canvas id='logo' width='624' " .
"height='96'>$appname</canvas></center>" .
"<div class='appname'>$appname$userstr</div>" .
"<script src='javascript.js'></script>";
if ($loggedin)
echo "<br ><ul class='menu'>" .
"<li><a href='members.php?view=$user'>Home</a></li>" .
"<li><a href='members.php'>Members</a></li>" .
"<li><a href='friends.php'>Friends</a></li>" .
"<li><a href='messages.php'>Messages</a></li>" .
"<li><a href='profile.php'>Edit Profile</a></li>" .
"<li><a href='logout.php'>Log out</a></li></ul><br>";
else
echo ("<br><ul class='menu'>" .
"<li><a href='index.php'>Home</a></li>" .
"<li><a href='signup.php'>Sign up</a></li>" .
"<li><a href='login.php'>Log in</a></li></ul><br>" .
"<span class='info'>⇒ You must be logged in to " .
"view this page.</span><br><br>");
?>
setup.php
With the pair of included files written, it’s now time to set up the MySQL tables they
will use.
The tables created here have the following columns and names:
• members: username user (indexed), password pass
• messages: ID id (indexed), author auth (indexed), recipient recip, message type pm, message message
• friends: username user (indexed), friend’s username friend
• profiles: username user (indexed), “about me” text
Because the functio..
3. setup.php
<!DOCTYPE html>
<html>
<head>
<title>Setting up database</title>
</head>
<body>
<h3>Setting up...</h3>
<?php
require_once 'functions.php';
createTable('members',
'user VARCHAR(16),
pass VARCHAR(16),
INDEX(user(6))');
createTable('messages',
'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('friends',
'user VARCHAR(16),
friend VARCHAR(16),
INDEX(user(6)),
INDEX(friend(6))');
createTable('profiles',
'user VARCHAR(16),
text VARCHAR(4096),
INDEX(user(6))');
?>
<br>...done.
</body>
</html>
index.php
This file gives 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 sign-ups.
Incidentally, seeing as all the MySQL tables have been created and the include files saved,you can now load
4.index.php
<?php
require_once 'header.php';
echo "<br><span class='main'>Welcome to $appname,";
if ($loggedin) echo " $user, you are logged in.";
else echo ' please sign up and/or log in to join in.';
?>
</span><br><br>
</body>
</html>
signup.php
Now we need a module that will allow users to join the social site.
5.signup.php
<?php
require_once 'header.php';
echo <<<_END
<script>
function checkUser(user)
{
if (user.value == '')
{
O('info').innerHTML = ''
return
}
params = "user=" + user.value
request = new ajaxRequest()
request.open("POST", "checkuser.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)
O('info').innerHTML = this.responseText
}
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>
<div class='main'><h3>Please enter your details to sign up</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
{
$result = queryMysql("SELECT * FROM members WHERE user='$user'");
if ($result->num_rows)
$error = "That username already exists<br><br>";
else
{
queryMysql("INSERT INTO members VALUES('$user', '$pass')");
die("<h4>Account created</h4>Please Log in.<br><br>");
}
}
}
echo <<<_END
<form method='post' action='signup.php'>$error
<span class='fieldname'>Username</span>
<input type='text' maxlength='16' name='user' value='$user'
onBlur='checkUser(this)'><span id='info'></span><br>
<span class='fieldname'>Password</span>
<input type='text' maxlength='16' name='pass'
value='$pass'><br>
_END;
?>
<span class='fieldname'> </span>
<input type='submit' value='Sign up'>
</form></div><br>
</body>
</html>
checkuser.php
To go with signup.php,checkuser.php looks for the username in the database and returns a string indicating whether it has already been registered.Because it relies on the functions sanitizeString and queryMysql, the program first includes the file functions.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, this username is taken” or “This username is 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 entities ✘ and ✔ are also used to preface the string with either a cross or a checkmark.
6.checkuser.php
<?php
require_once 'functions.php';
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$result = queryMysql("SELECT * FROM members WHERE user='$user'");
if ($result->num_rows)
echo "<span class='taken'> ✘ " .
"This username is taken</span>";
else
echo "<span class='available'> ✔ " .
"This username is available</span>";
}
?>
login.php
Having signed up to the site,we therefore will need a login.php to allow people to access the site.
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
7.login.php
<?php
require_once 'header.php';
echo "<div class='main'><h3>Please enter your details to log in</h3>";
$error = $user = $pass = "";
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = "Not all fields were entered<br>";
else
{
$result = queryMySQL("SELECT user,pass FROM members
WHERE user='$user' AND pass='$pass'");
if ($result->num_rows == 0)
{
$error = "<span class='error'>Username/Password
invalid</span><br><br>";
}
else
{
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
die("You are now logged in. Please <a href='members.php?view=$user'>" .
"click here</a> to continue.<br><br>");
}
}
}
echo <<<_END
<form method='post' action='login.php'>$error
<span class='fieldname'>Username</span><input type='text'
maxlength='16' name='user' value='$user'><br>
<span class='fieldname'>Password</span><input type='password'
maxlength='16' name='pass' value='$pass'>
_END;
?>
<br>
<span class='fieldname'> </span>
<input type='submit' value='Login'>
</form><br></div>
</body>
</html>
1 Comments
Awesome bro great project
ReplyDelete