php mysql + create a friend request system - php

i am creating a friend request system that allow user to send request to each other to add as friends like facebook
and i have 2 conditions that if :
the user is the profile owner he can not add him self i will echo an
error msg
the user is not the owner of the profile it will echo a message that
say wait then the request is send
if the user has already send the request i will echo a message to infor the user that a request had been send.
but the error is that i am in the first condition because the system display that the user is the owner profile but this is wrong
can anyone help me ??
this is a chunk of code
function addAsFriend(a,b){
//alert("Member with id:" + a + "request friendship with the memeber with id:" + b);
var url = "script_for_profile/request_as_friend.php";
$("#add_friend").text("please wait...").show();
$.post(url,{request:"requestFreindship",mem1:a,mem2:b},function(data){
$("#add_friend").html(data).show().fadeOut(12000);
});
}
<div class="interactContainers" id="add_friend">
<div align="right">Cancel</div>
Add <?php echo $username ?> as Friend?
Yes
request_as_friend.php
<?php
//var we need for both members
$mem1=preg_replace('#[^0-9]#i','',$_POST['mem1']);
$mem2=preg_replace('#[^0-9]#i','',$_POST['mem2']);
if(!$mem1||!$mem2)
{
echo "Error .missing data";
exit();
}
if($mem1==$mem2)
{
echo "Error you can not add yourself as friend";
exit();
}
require_once('../include/connect.php');
if($_POST['request']=="requestFriendship")
{
//check that there is not a request pending where this viewer is requesting this profile owner
$sql = mysql_query("SELECT id FROM friend_requests WHERE mem1='$mem1' AND mem2='$mem2'limit1")or die(mysql_error());
$numRows = mysql_num_rows($sql);
if($numRows > 0)
{
echo "You have a friend request pending already for this member. they must approve it when they view their request list";
exit();
}
//check that there is not a request pending where this profile owner is not already requesting this viewer
$sql = mysql_query("SELECT id FROM friend_requests WHERE mem1='$mem2' AND mem2='$mem1'limit1")or die(mysql_error());
$numRows = mysql_num_rows($sql);
if($numRows > 0)
{
echo "This user has requested you as friend already! Check your friend Request on your profile";
exit();
}
$sql = mysql_query("INSERT INTO friend_requests(mem1,mem2,timedate) VALUES('$mem1','$mem2',now())") or die (mysql_error("friend request insertionn error"));
//$sql = mysql_query("INSERT INTO pms(to,from,time,sub,msg) VALUES('$mem2','XXXXX',now(),'New Friend Request','YOU Have a New friend request waiting for approval.<br /><br />Navigate to your profile and check your friend request.<br /><br />Thank you.')") or die (mysql_error("friend request PM insertionn error"));
echo "Friend Request sent succesfully. this member must approve the request";
exit();
}
?>

I was totally wrong, you don't need to create any extra flag, just store the user_id -which you retrieve from the database when the user logs in - store it in the session then when he/she clicks on the add friend button check the $_SESSION['user_id'] with the id of the other user before completing the friendship function, if they're both the same, means it's the same person, otherwise add friends.

What the post array returns for mem1 and mem2?
However, you shouldn't compare the post data. Or not both.
For example you have logged in, your id is stored in session. You are opening a user profile i.e.: http://yoursite.com/viewprofile.php?id=1001 . Then after passing from the jquery you should check in PHP smth like:
if ($_GET['id'] = $_SESSIOM['id']) {
//you cannot add yourself
}

Related

How to store user id session from login page in php

i am creating login page where user will be redirected to his/her profile page. Profile page contains the articles of that user...
I have problem in login page, actually i want to store user id in
session from login page.. as i am storing user_email in session and it
does successfuly.. but it gives error on user_id session (undefined
index)....
addition
i want to show articles of logged in user through user_id session...
Here is the code of login page..
<?php
if(isset($_POST['login'])){
$user_email=mysqli_real_escape_string($con,$_POST['user_email']);
$user_password=mysqli_real_escape_string($con,$_POST['user_password']);
$encrypt= md5($user_password);
$check_login="select * from users where customer_email='$user_email'
AND customer_pass='$user_password'";
$run_login= mysqli_query($con, $check_login);
$row = mysqli_fetch_array($run_login);
$num = mysqli_num_rows($run_login);
$user_id=['customer_id'];
if($num==1){
$_SESSION['customer_email']="$user_email";
$_SESSION['customer_id']="$user_id";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "This Username Doesnt Exists or Empty Login !";
}
}
?>
</div>
Step 1:
Do not forget to put session_start();
Step 2:
Change $user_id=['customer_id']; to $user_id=$row['customer_id'];
You must set $user_id only if there is a return from DB (otherwize you don't know this id)
if($num==1){
$user_id=$row['customer_id'];
// ....
}

session variable getting null or lost when I didn't update information

In my page, I have:
1. Registration Page
2. Login Page
3. Successful Registration Page
4. Referral Form
In my registration Page, User can register through this.
In my Log-in page, I have two types of user, Applicant and Employee
In my Successful Registration Page, there is a button directs to Referral Form.
In my Referral Form Page, I have a modal there to update referral information provided by the user during the registration.
The following information are:
Referrer ID
Fullname
Current Position
ContactID
Email Address
MObile Number
Member Since
If you created an account on my page, either you are a Applicant or Employee, if you successfully register, my successful registration page will prompt to you and once you have click the button going to Referral Form The following information will be displayed to your referral information based on you supplied during the registration.
If you register as an Applicant, your Referrer ID is always set into 0 and you may edit it through Referral Form Page
or if you register as an Employee, your Referrer ID is based on you provide during the registration.
Example:
Referrer ID (Allowed to edit if you register as an applicant)
Fullname Sherlock Holmes
Current Position (This has no value and may be edit once you created an account)
ContactID CON12344
Email Address SherlockHolmes#gmail.com
MObile Number +987676758857
Member Since 2014-05-06 04:41:21
Here's my problem that I encounter.
I created an account and Successful registration page prompt to me, and I click the button going to Referral Form Page to edit my information. I edit it and Log-it out and try to relog-in, My Information updated and now reflecting on my Information. It works well.
But
When I created an account and promt successful registration page and click the button going to Referral Form Page, If I did not edit my information and tried to log it out and try to re-login, my information becomes having all null values. Like this,
Referrer ID 0
Fullname
Current Position
ContactID
Email Address
MObile Number
Member Since
Which was incorrect because even I did not edit my information, my information should just becomes like this.
Referrer ID 0(You can edit it)
Fullname Sherlock Holmes
Current Position (You can edit it)
ContactID CON12345678
Email Address sherlockholmes#gmail.com (You can edit it)
MObile Number +93456789 (You can edit it)
Member Since 2014-05-06 04:41:21
Problem Occurs when I don't edit my information for a new created account, but when I edit it before I log it out, it's okay.
here is my Successful registration PHp
<?php
include('../include/dbconnection.php');
include('../include/functions.php');
if(!isset($_SESSION))
{
session_start();
}
$empid = $_SESSION['SESS_EMP_ID'];
$conid = $_SESSION['SESS_CONID'];
$fName = $_SESSION['SESS_FIRSTNAME'];
$lName = $_SESSION['SESS_LASTNAME'];
$contactNo = $_SESSION['SESS_CONTACT_NO'];
$mobile = $_SESSION['SESS_MOBILE'];
$email = $_SESSION['SESS_EMAIL'];
$bday = $_SESSION['SESS_BDAY'];
if($conid == '')
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='index.php';
</SCRIPT>");
}
else
{
//Nothing
}
?>
Here is my code in Referral Form
/**** Start Session ****/
session_start();
//Check whether the session variable SESS_EMP_ID is present or not
if(!isset($_SESSION['SESS_EMP_ID']) || (trim($_SESSION['SESS_EMP_ID']) == '')) {
header("Location: LoginPage.php");
exit();
}
/**** End ****/
/**** Redirects automatically to index ****/
header("Refresh: 15 * 60; url=index.php");
/**** End ****/
/**** authentication ****/
//require_once('../function/auth_emp.php');
/**** End ****/
$empid = $_SESSION['SESS_EMP_ID'];
$bdate = $_SESSION['SESS_BDAY'];
/**** Database connection ****/
require_once('../include/config.php');
/**** End ****/
include'../GlobalConstants.php';
include_once ('../refer/updateInfo.php');
mysql_select_db($db_name, $con) or die("ERR_COULD_NOT_SEE_DB");
if($empid == 0)
{
$fname = $_SESSION['SESS_FIRSTNAME'];
$lname = $_SESSION['SESS_LASTNAME'];
$bdate = $_SESSION['SESS_BDAY'];
$pos = $_SESSION['SESS_POSITION'];
$empid = $_SESSION['SESS_EMP_ID'];
$qry= "SELECT vtiger_contactdetails.firstname,
vtiger_contactdetails.contact_no,
vtiger_contactscf.cf_703,
vtiger_contactscf.cf_715,
vtiger_contactscf.cf_717,
vtiger_contactdetails.email,
vtiger_contactdetails.lastname,
vtiger_contactdetails.mobile,
vtiger_contactdetails.contactid,
vtiger_crmentity.createdtime
FROM vtiger_contactdetails
INNER JOIN vtiger_contactscf
ON vtiger_contactdetails.contactid = vtiger_contactscf.contactid
INNER JOIN vtiger_crmentity
ON vtiger_contactdetails.contactid = vtiger_crmentity.crmid
INNER JOIN vtiger_contactsubdetails
ON vtiger_contactsubdetails.contactsubscriptionid= vtiger_contactdetails.contactid
WHERE vtiger_contactdetails.firstname = '".$fname."'
AND vtiger_contactdetails.lastname = '".$lname."'
AND vtiger_contactsubdetails.birthday = '".$bdate."'";
$result = mysql_query($qry);
} else
{
$qry= "SELECT vtiger_contactdetails.firstname,
vtiger_contactdetails.contact_no,
vtiger_contactscf.cf_703,
vtiger_contactscf.cf_715,
vtiger_contactscf.cf_717,
vtiger_contactdetails.email,
vtiger_contactdetails.lastname,
vtiger_contactdetails.mobile,
vtiger_contactdetails.contactid,
vtiger_crmentity.createdtime
FROM vtiger_contactdetails
INNER JOIN vtiger_contactscf
ON vtiger_contactdetails.contactid = vtiger_contactscf.contactid
INNER JOIN vtiger_crmentity
ON vtiger_contactdetails.contactid = vtiger_crmentity.crmid
WHERE vtiger_contactscf.cf_739 = '".$empid."'";
$result = mysql_query($qry);
}
if($result)
{
if(mysql_num_rows($result)> 0)
{
$row = mysql_fetch_assoc($result);
$contact_no = $row['contact_no'];
$fname = $row['firstname'];
$mname = $row['cf_703'];
$lname = $row['lastname'];
$mobile = $row['mobile'];
$pos = $row['cf_715'];
$program = $row['cf_717'];
$email = $row['email'];
$conid = $row['contactid'];
$memberdate = $row['createdtime'];
}
}
$erp = "ERP";
/**** Stores the firstname and lastname in the session ****/
$_SESSION['SESS_EMP_ID'] = $empid;
$_SESSION['SESS_CONID'] = $conid;
$_SESSION['SESS_FIRSTNAME'] = $fname;
$_SESSION['SESS_MIDDLENAME'] = $mname;
$_SESSION['SESS_LASTNAME'] = $lname;
$_SESSION['SESS_MOBILE'] = $mobile;
$_SESSION['SESS_EMAIL'] = $email;
$_SESSION['SESS_POSITION'] = $pos;
$_SESSION['SESS_GEN'] =$erp;
$_SESSION['login_time'] = time();
?>
Do I have problem passing the session variable when the user didn't fill up the information after they created an account?
If user edit and fill up all information and try to re-logout and re-login. It seems okay and works.
But after user created an account, and If I didn't edit the information and log it out and try to re-login, it does not reflect the values.
I won't reflect the value of session when I didn't update the information if I logout and try to re-login. Thanks
Your code is simple to debug.
Try to test it step by step.
Check this variable - $empid
1) When it is 0 then try to output the whole your query on the page and check these conditions.
WHERE vtiger_contactdetails.firstname = '".$fname."'
AND vtiger_contactdetails.lastname = '".$lname."'
AND vtiger_contactsubdetails.birthday = '".$bdate."'";
2) If this whole query outputs correctly (fname, lname, bdate are not empty) then check the result variable. It should return an object and it should not be null.
3) Check the ELSE block. Especially this condition
WHERE vtiger_contactscf.cf_739 = '".$empid."'";
4) If the query is correct (no empty spaces), check the result variable. It must be an object.
I think the issue occurs when you logout the user, you might be flushing all the session values, please add your logout code here so that we can check if their any cause.
There is another this that you can try for this issue.
1) When the user successfully register to you application save the data into temp table with user info along with the non-edited flag.
2) when the user comes on the referral page fetch the current login user data and assign to referral form.
3) If the form get submitted change the flag value.
This will help you to track on the users whose not update their referral form, and you can prompt them on some other pages also, this will make lesser dependency on session, because session will get destroyed eventually when you do logout or might be happen due to server session handling variables also and you will not have any track for those information. Hope this will help you.

Where request comes from (php)

I have 3 php pages. These are related to my message system.
1st file is inbox.php
2nd file is sent.php
3rd file is delete_message.php
My questions is about redirecting with header('Location:xxx'); I want to redirect user to where from he/she request delete query.
For example if he/she delete a message from inbox I want to redirect him to inbox.php, else he/she must redirected to sent.php
What I should add to my delete script?
<?php
include '../config/db.connect.php';
$m_id = $_GET['message_id'];
$delete = $db->exec("DELETE FROM message WHERE message_id ='$m_id'");
if ( $delete ) {
header("Location:../message_sent.php");
}
else {
echo "delete error..";
echo "An error message...");
}
?>
Use $_SERVER['HTTP_REFERER'] to get the previous page url.

If user doesnt exist dont show jQuery and ordering

I have an application ive built that users can register and link their twitter account.
If somebody creates a user for spam purposes however Twitter then deletes this user, they still stay on my site however. If another user then tries to follow them I bounce back a message saying user is no longer valid only this has become a serious problem and there's a lot of spam accounts.
My current solution is when the page loads, with jQuery check to see if the twitter users image loads and if not set that user to display none.
Im wondering however, is there a way to check BEFORE outputting my page, so this way my users arent presented with a list of users, that when the page loads X of them dissapear, but a list of users who are all active?
Thanks
This is the php I have on my page, I know its old but is there a way to check if the user exists with Twitter and mix it with what I currently have?
Sorry im very new to PHP!
$rs = mysql_query("select produgg_users.id, twitterUser, coff, credits from produgg_users where twitterUser != '' and active !='' and credits >= coff and
produgg_users.id IN (select concat_ws(',', id) from produgg_users where credits > 0 and id != ".$usersClass->userID().") and produgg_users.id NOT IN (select concat_ws(',', followedID) from produgg_activity where followerID = '".$usersClass->userID()."') and produgg_users.id NOT IN (select concat_ws(',', userid) from produgg_featured) ORDER BY coff DESC LIMIT 30;") or die(mysql_error());
$nr = #mysql_num_rows($rs);
if($nr != 0) {
print "<h2>More Friendr Users!</h2><div>";
while($row=#mysql_fetch_object($rs))
{
$divLeft = '<div class="user-box" id="thediv_'.$row->id.'"><div class="twithandlepic"><img src="http://api.twitter.com/1/users/profile_image/';
$divRight = '<div class="twithandle">';
$clearDiv = '<div style="clear:both;"></div>';
$row->coff = $row->coff - 1;
print $divLeft.strip_tags($row->twitterUser)."?size=bigger\" style=\"width:73px; height:73px;\"/><br \/>".$row->twitterUser.$divRight."<a href='javascript:void(0);' id='vote_$row->id' class='getPoint'>Get $row->coff <input type='hidden' value='$row->coff' class='credoff' name='credoff'/> credit(s)</a><br /></div>$clearDiv</div></div>";
} print "</div>";
echo " <a href='earn-credits.php' class='refreshlist'>Refresh</a>";
}else{
print "<p>No twitter users to show</p>";
}
You can just send a request to twitter.com/username and look at the response code: 200 if the user exists, 404 if they don't. For example, try http://twitter.com/somefakeperson and you'll get a 404.
Using CURL it'd look something like this:
while($row=#mysql_fetch_object($rs))
{
$ch = curl_init('http://twitter.com/'.$row->twitterUser);
curl_exec($ch);
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
if($info['http_code'] == '200') {
$divLeft = '<div class="user-box" id="thediv_'.$row->id.'"><div class="twithandlepic"><img src="http://api.twitter.com/1/users/profile_image/';
$divRight = '<div class="twithandle">';
$clearDiv = '<div style="clear:both;"></div>';
$row->coff = $row->coff - 1;
print $divLeft.strip_tags($row->twitterUser)."?size=bigger\" style=\"width:73px; height:73px;\"/><br \/>".$row->twitterUser.$divRight."<a href='javascript:void(0);' id='vote_$row->id' class='getPoint'>Get $row->coff <input type='hidden' value='$row->coff' class='credoff' name='credoff'/> credit(s)</a><br /></div>$clearDiv</div></div>";
}
}
curl_close($ch);
}
As an aside, it might also be good to send an update back to the DB any time you hit an invalid user to either remove or flag the user somehow. You could then filter out those users in the future right at the DB level.
The Twitter API call GET users/lookup allows you to see if a user is active. So for example issuing a REST API call to the endpoint here:
https://api.twitter.com/1/users/lookup.json?
screen_name=twitterapi&include_entities=true
will give you a HTTP 200 OK response if the user exists. However a call with a screen name that doesn't exist returns a 404, for example:
https://api.twitter.com/1/users/lookup.json?
screen_name=dsklfjdkl&include_entities=true
Before displaying a page to the user, your server can check whether the username exist (and if not, just remove them from the page/mark them as dead in the database).

Sessions?? How can I display a the users row?

I want to display the attributes of the game character, which is under the users TABLE. So, I want it to display the specific attributes of the user who has logged in, since it should be in his row. Do I need to register my users with session, because I didn't.
This is the code I used to get the sessions for the user in when login in
<?
if(isset($_POST['Login'])) {
if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
echo "Invalid Username.";
}else{
$query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.
if(empty($row['id'])){
// check if the id exist and it isn't blank.
echo "Account doesn't exist.";
}else{
if(md5($_POST['password']) != $row['password']){
// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
echo "Your password is incorrect.";
}else{
if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already
$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
}else{
$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {
$row['login_ip'] = $row['login_ip'];
}else{
$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
}
}
$_SESSION['user_id'] = $row['id'];// this line of code is very important. This saves the user id in the php session so we can use it in the game to display information to the user.
$result = mysql_query("UPDATE users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
or die(mysql_error());
// to test that the session saves well we are using the sessions id update the database with the ip information we have received.
header("Location: play.php"); // this header redirects me to the Sample.php i made earlier
}
}
}
}
?>
you need to find which user you are logged in as. How do you log in to your system? You have several options which you can try out:
use sessions (save the userID in the session, and add that to the query using something like where id = {$id}
Get your userid from your log-in code. So the same code that checks if a user is logged in, can return a userid.
Your current code shows how you log In, and this works? Then you should be able to use your session in the code you had up before.
Just as an example, you need to check this, and understand the other code. It feels A bit like you don't really understand the code you've posted, so it's hard to show everything, but it should be something like this.
<?php
session_start();
$id = $_SESSION['user_id'];
//you need to do some checking of this ID! sanitize here!
$result = mysql_query("SELECT * FROM users" where id = {$id}) or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
}

Categories