I`m creating a simple social network site, I need to implement a sophisticated friend request system, one which works like facebook, this will work as follows: If James wants John to be his friend, he will click John's name. John will be notified that James has asked to be his friend( notification will appear on John's profile page) John will then need to agree for James to be his friend. Once agreed, they will both be friends.
And I would also like to restrict access to the user's profile to people who that users friends, in orther words, if the logged in user is trying to view a profile of someone who is not their friend, they should not be able to.
Anyone who have idea on how i can solve this i will really appreciate.

Well you would need some kind of 'friend' table that would link together the different user_ids. It could also have an 'active' flag on it that represents whether a request is pending or active (0 for pending, 1 for active). Depending on how the login system works, if you use classes, you could add an array property that contains a list of the logged in users friend_ids. Then when they hit another members page you check that the member id is within the users friend list.

Thanks very much I have a set up a "friends" table on my database, but i am not sure how to link this with user_ids, and also how to present an active flag representing whether the request is pending or not. this is how my login code looks like.

<?php
session_start();

$i = $_POST["username"];
$e = $_POST["password"];

$conn = mysql_connect("localhost", "PeterJones", "sksksksks");
mysql_select_db("PeterJones");

$q=("SELECT username FROM users WHERE username = '$i' AND password ='$e' ");
$result=mysql_query($q) or die(mysql_error());
$row= mysql_fetch_array($result);

if(mysql_num_rows($result)==0)

{	
}
else 
{
// Correct password : set up the authentication session variable
    // and store the user ID in it
    $_SESSION["gatekeeper"] = $i;  

}

mysql_close($conn);

?>

Sorry to be a pain, but could you please show me on the code(php script how this will be represented.

Kind regards

Ok so for the friends table (this is a basic example) you could have 3 fields:

user_id(int), friend_id(int), active(bool)

when a user decides to add a friend you put the original user_id in the user_id field. The id of the member they want to add goes in the friend_id field and set active to 0. Then send a notification to the user with id 'friend_id' that 'user_id' wants to be their friend. If they accept update that row on the table so that active = 1.

then when a user signs in create an array of all their friends. (this is where someone else might have a better idea of table structure) but what you would do is something like

<?php
//Your login code here
$user_id = $id; //id of logged in user however u store this
$arrFriendlist = new array();
$q = @mysql_query("SELECT friend_id FROM friends WHERE user_id = $user_id AND  active = 1");
while($r = @mysql_fetch_array($q)){
array_push($arrFriendList, $r['friend_id']);
}
//also have to get friends where request was reversed
$q = @mysql_query("SELECT user_id FROM friends WHERE friend_id = $user_id AND  active = 1");
while($r = @mysql_fetch_array($q)){
array_push($arrFriendList, $r['user_id']);
}
?>

Then when a user hits a member page and you want to check if they are friends, get the id of the member they are trying to view and do:

<?php
$mem_id = $_GET['id']; // GRab the id of member you want to view
if(in_array($mem_id,$arrFriendList)){
//code to show member details
}else{
 echo "sorry but this user isn't your friend";
}
?>

thanx for your previous advice on this!!!
Still on the same issue, i need to send a notification whereby if John wants to be Peter's friend, John will click on Peter's name hyperlink "Make Friend", then a notification will be sent to peter and will appear on Peter,s profile page, then once Peter has accepted friendship, these two people can then become friends, then ofcause the "friends" table will be updated, how do I write a PHP code for this, so far

I have got:

<?php 
session_start(); 
$a = $_SESSION["gatekeeper"];
$conn = mysql_connect("localhost", "PeterJones", "PeterJones");
mysql_select_db("JonesPeter");

 if ( !isset ($_SESSION["gatekeeper"]))
{
	echo "You're not logged in. Go away!";

}
else 
{
	
$result=mysql_query("SELECT * FROM users WHERE username = '$a'");

while($row=mysql_fetch_array($result))
{
    echo "You are logged in as!";
    echo " $row[username] <br />";

  // How do I make the currently user's online friends to display like this????? Please help me on this one as well!!!
    echo " Online friends  <br> <br />";
	//John, Josh, Joseph etc ???? Please help me on this one as well!!!!

    echo " Search for your Friends  <br> <br />";
}

}
    
?>

<form method="post" action="search.php"   
<label for="username">Name</label>
<input type="text" name="username" />  
<input type="submit" value="Search" />    
</form>
</body>

	<div>
	<a href="logout.php"> Logout</a>

Ok so assuming $arrFriendList from the previous example holds all the user_ids of the friends you then use these in a query against the user table. Again there will be a more efficient way to do this probably but it would go something like:

$Friends = ""; //string of friends
foreach( $arrFriends as $item=>$value){
$q = @mysql_query("SELECT username, user_id FROM users WHERE user_id = $value");
while($r = @mysql_fetch_array($q)){
$Friends .= $r['username']."<br />";
}
}

Hi, I'm Maxi from Argentina, and I'm here looking for something very similar to what shibobo2001 is asking for.
In my case I'm trying to integrate a phpBB forum with a custom portal I'm developing, but the friend system of phpBB doesn't really works for me.
phpBB comes with this friend & foe system that adds people to your profile in your friend/foe list, but the user you are becoming a friend of, doesn't need to accept any request or something to appear in your list. And your friend doesn't even know you've added him to your list unless he visit your profile and see his name in there, 'cause you don't appear in his friend list either.

And I'm looking for something more reciprocal, a system that works the way Facebook, MySpace, or any other social network does. That's why I've been trying to make some changes:

First of all I added a new colum to the "phpbb_zebra" table, the table that phpBB use for this friend & foe system. This new colum (called "active"), is to verificate if the relationship is pending (0), or active (1), just like TommyBs said in his first post.
So the phpbb_zebra table is now like this:

+------------------+---------------------+--------+-----------+
| Field            | Type                | Null   | Default   |
+------------------+---------------------+--------+-----------+
| user_id          | mediumint(8)        | NO     | 0         |
| zebra_id         | mediumint(8)        | NO     | 0         |
| friend           | tinyint(1)          | NO     | 0         |
| foe              | tinyint(1)          | NO     | 0         |
| active           | tinyint(1)          | NO     | 0         |
+------------------+---------------------+--------+-----------+

Don't worry about the foe colum, it's just the way phpBB has to determinate the relationship, if the foe field is set to 1, then the friend field is set to 0, wich means the zebra_id user is a foe of the user_id user.
Anyway I deactivate the foe list functionality in phpBB, so this field is always set to 0.

Now, all the code I've made is for my custom portal, it's just PHP and it has nothing to do with phpBB, so it won't affect the way the default system works (and you can use this even if you're not using phpBB integration).

To send a request to the user I want to become a friend of, I use this:

// login to the database

$query="SELECT * FROM phpbb_zebra WHERE (user_id = '$_SESSION[user_id]' AND zebra_id = '$profile_id') OR (zebra_id = '$_SESSION[user_id]' AND user_id = '$profile_id')";
$result = mysql_query($query,$cnx);
$row = mysql_num_rows($result);

if ($row == 1) { // means the relationship exist, whether it's active or not
   while($row = mysql_fetch_assoc($result)) {
      if ($row['active'] == 1) {
      echo "You are a friend of this user.";
      } else {
      echo "You've already sent a friend request to this user";
      }
   }
} else { // if the relationship don't exist
echo "<a href='add_friend.php?zebra_id=".$profile_id."'>Add this user as a friend</a>";
}

This could be placed at the profile of every user. First, the query check if the relationship exist, to avoid sending requests to users that are already your friends, or to users you've sent a request before. In case this two conditions are false, then you can see the link to the add_friend.php script.
For this example, $_SESSION is you, the user logged in into the site, and $profile_id is the user you want to become a friend of.

Now, add_friend.php will be something like this:

// login to the database

if ((!isset($_GET['zebra_id'])) || (!isset($_SESSION['user_id']))) {
header("Location: index.php"); exit(); // the zebra_id variable is not set in the URL, or there is no user logged in, so get out the page
}

$profile_id = $_GET['zebra_id'];

$query="SELECT * FROM phpbb_zebra WHERE (user_id = '$_SESSION[user_id]' AND zebra_id = '$profile_id') OR (zebra_id = '$_SESSION[user_id]' AND user_id = '$profile_id')";
$result = mysql_query($query,$cnx);
$row = mysql_num_rows($result);

if ($row == 1) { // check again for the existence of the relationship
   while($row = mysql_fetch_assoc($result)) {
      if ($row['active'] == 1) {
      echo "You are a friend of this user.";
      } else {
      echo "You've already sent a friend request to this user";
      }
   }
} else { // the relationship don't exist, so it's time for the real job
   $insert_query = "INSERT INTO phpbb_zebra ('user_id', 'zebra_id', 'friend') VALUES ('$_SESSION[user_id]', '$profile_id', '1')";
   $insert_result = mysql_query($insert_query,$cnx);
   if (!$insert_result) {
      // error here
   } else {
      echo "The request has been sent.";
   }
}

To notice users they have new friends requests:

// login to the database
$query = "SELECT * FROM phpbb_zebra WHERE zebra_id = '$_SESSION[user_id]' AND active = '0'";
$result = mysql_query($query,$cnx);
$row = mysql_num_rows($result);
if ($row > 0) { // there are new requests
   echo "<a href='requests.php'>You have ".$row." new friend requests</a>";
} else {
 echo "No new requests.";
}

The rest is very simple, the page requests.php show all the new friends requests (rows where zebra_id is the id of the user logged in and viewing his requests, and where the active field is set to 0). All you have to do is give the user two options, to accept or to reject the request. If he accepts, just uptade that row on the data base and change the active field from 0 to 1. And if he rejects the request, you can delete that row or you can change the active value to something like 9, or anything other than 0 or 1.
The difference is that if you delete the row, it's like the request never existed, so the same user can make the request again, and if he gets rejected again, he can do it one more time, and so.
But if you change the active value to 9 (or 8, or 7, or 6...), to the requesting user, it will appear as pendient, but the requested one don't have to worry about being requested by the same user again.

Well, that's all. I really hope this can help you, and if not, you can ask all the questions you want and I'll do my best to answer them.
I know this might not be the best way to implement this functionality, so feedback and corrections to the code are also appreciated =)

And sorry about my english :P

.:ChrC:.

commented: 10 +0

Thanx for your previous help on this,

I am finally making progress with my site!!

Could you please help me with the below
I am looking to implement a birthday notification system working similar to facebook, i would like the birthdays of the users or friends in my table to display as follows.
January:
February:
10th-James Smith
16th-Luke Samuel
19th-Jim Jones
March:
April:
etc

could you please help me write the script for this, or a sample script so i can get some ideas!

Regards
shibobo2005

hi iam suresh..i want learn php from home through internet.iam using windows xp os.And iwas downloaded XAMPP 1.7.2version and intsalled it.After installation finally i got XAMPP CONTROL PANEL.I dont knopw how can we use tht xampp controle panel..Using tht panel how could we start PHP apache and mysql etc..pls telll me how can i use.and once again tell me XAMPP intsallation process also..pls do this favour for me friends.

can anyone add this as downloadable file?
When I try to copy paste code files doe.n't work properly in wampserver

Erm ..... may I just comment on something here! Before you consider making a script it would really be worth you looking at basic user input authenitcation and sanitisation.

You have posted your database connection details on the internet which is not advised as people could hack you database and ruin your website if they have your database username details.

If I was you I would change the user for your database and also make sure you only permit certain access such as SELECT, UPDATE and DELETE (if really needed). This way you limit the damage that can be done to your website.

Also you dont seem to be sanitising the user input $_POST variables. I would first look up user input php sanitisation and look at how you can stop people from hacking your website.

mysql_real_escape_string($input)
stripslashes($input)

There is alot more but basically NEVER ever trust any user input you receieve through forms ($_POST & $_GET).

Currently you could get someone hacking your website without needing to know passwords or usernames!

Hope this helps! :)

Hey frnd!! here is simple code to show whethr the user is online or not..

1. Create table "user_online" in mysql in database "test".
2. Create file user_online.php.

CREATE TABLE `user_online` (
`session` char(100) NOT NULL default '',
`time` int(11) NOT NULL default '0'
) TYPE=MyISAM;

then create useronline.php

<?
session_start();
$session=session_id();
$time=time();
$time_check=$time-600; //SET TIME 10 Minute
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="user_online"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){
$sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
$result1=mysql_query($sql1);
}
else {
"$sql2=UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
echo "User online : $count_user_online "; 
// if over 10 minute, delete session 
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
mysql_close();
// Open multiple browser page for result
?>

Complete Login System in "CLASS" in php(please send feedback at [snipped])

<?php 

class login
{
private $user_name,$user_passw;
function __construct()
{
$this->user_name = $this->remove($_POST['user_name']);
$this->user_passw = $this->remove($_POST['user_passw']);
}
// No one can access this function outside 
private function login_1()
{
$con = mysql_connect("localhost","root","") or die(mysql_error();
mysql_select_db("LOGIN",$con);
$ret  = mysql_query("SELECT * FROM user_info WHERE(user_name = '$this->user_name' , user_passw = '$this->user_passw')");
if($ret)
{
if(mysql_num_row)==0)
{
echo "Login failed !!";
}
else
{
echo "You login successfully";
}
}
}

private function remove($string)
{             
$string = @trim($string);
if(get_magic_quotes_gpc())
{
$string = stripslashes($string);
}
return mysql_real_escape_string($string);
}

public function login()
{
$this->login_1();
}
}


$glob = array();
if(isset($_POST['submit']))
{
process_form();
if(!empty($glob))
{
show_form();
}
else
{
$obj = new login();
$obj->login();
unset($obj);
}
}
else
{
show_form();
}
function process_form();
{
if($_POST['user_name']=="")
{
$glob[] = "enter user name";
}
if($_POST['user_passw'] == "")
{
$glob[] = "emter password";
}
}
function show_form()
{
echo "<form method = "post" name="user_login">
        User Name <input type="text" name="user_name" value=""><br>
       User Password <input type="password" name="user_passw" value=""><br>
<input type="submit" name="submit" value="login">
</form>";
}
?>

This is really working for me... would you please help with sample code on the "requests.php" code and the accept and decline codes.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.