How do I notify a message posted from the application? - php

When my application publishes a message on the user's wall (through permits streampublish) I want you to get a notification to the user in red. How can I do?
If I can not there are alternative solutions? . For example, I thought to send a private message to you through my application. how can I do?

Showing Notifications
You can do this by using a db column that holds the notification status lets say when the notification_status = 0 the user didn't see the notification yet
when the notification_status = 1
then you send request to server every mount of time lets say 15 seconds and then test weather there is notification_status = 0 or not if yes show a div and send the number of notifications in it
setInterval(function() {
$.post("notifications_tester.php",function(data){
if(data != 0 )
{
$('#notifications_div').show().html(data);
}
else
{
$('#notifications_div').hide().html("");
}
});
}, 15000);
sample what would be in notifications_test.php
session_start();
//connect to the DB
$user_id = $_SESSION['user_id'];
$q = mysql_query("SELECT * FROM posts WHERE user_id = '".$user_id."' AND notification_status = 0");
echo mysql_num_rows($q);

Related

PHP how to connect two players

I'm making a website. and one of the features i want it to have is to have a simple game that connects 2 players together. my problem is I don't know how to make it so both player are in the same "room" because on room holds only 2 players.
On way i approached this is once one player joined, he gets a "wait for next player" message and waits while sending to the database that one player have joined. how do i make it keep checking for the next 3 minutes if the next player joined?
UPDATE
First here is the code so far:
<html>
<title>SiteName (test)</title>
<head>
<?php
$servername = "localhost";
$u
sername =
$password =
$dbname =
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM game');
$stmt->execute(array('gameID' => $gameID));
while($row = $stmt->fetch()) {
print_r($row);
echo "<br />\n";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
<button onclick="myFunction()" id="w">Look for Game</button><br>
<script>
function myFunction() {
var elem = document.getElementById("w").innerHTML = "Wait";
var counter = 10;
var label= document.getElementById("lbl");
var counter = 10;
var clabel= document.createElement("p");
clabel.innerHTML = "You can download the file in 10 seconds.";
var id;
label.parentNode.replaceChild(clabel, label);
id = setInterval(function() {
counter--;
if(counter < 0) {
clabel.parentNode.replaceChild(label, clabel);
clearInterval(id);
} else {
clabel.innerHTML = "You can download the file in " + counter.toString() + " seconds.";
}
}, 1000);
}
</script>
<?php
$conn = null;
?>
</body>
</html>
Am trying to make it so that if the first player joined, he will be waiting (i have it for 10 seconds here as a test) until the other joins. the way am trying to do it is to have a field in the database will know if the a player is in that page and await the next player. I read something about long polling but not sure how to implement it for my case.
Any feed back would be helpful, Thank you
PHP is not the best language to do this in, but if you still want to do it.
Look into using Ratchet (http://socketo.me/), which is a PHP websocket library. A websocket is full duplex, meaning that a connection between the server and client is kept open. Game state and player actions can then be communicated through this.
http://socketo.me/docs/hello-world is an example you can learn from.
first you will want javascript or some client side code to handle this. as php will execute on the server side then display to the user. if you use ajax with javascript you can get the client side and server side to work together.
you will want to use a while loop, in this loop you will set a timeout.
in the while loop you can call the ajax script you want untill you get your result you want. I'm assuming you plan on making this a turn by turn game for the players. you will want a table that sets "true" to if player 1 or player 2 are in the game. if both are turn then the game begins.
Hope this logic helps

php mysql + create a friend request system

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
}

Display Notifications

I'm trying to follow the first answer here in order to accomplish my alert feature on my app. Facebook like notifications tracking (DB Design)
but in that example, the user has to open the notifications page to check for new notifications. For me, i need to let user knows that there is a notification (database updated) by displaying an icon like Facebook alerts or something like that.
is there any clear idea about how to do that ?
EDIT
i did something but can't test it coz i don't have my laptop right now.
would you please take a look and let me know if something not OK ?
PHP file
$userID=$_GET["userid"];
//Database connection
$sql = 'SELECT count(*) as count FROM list_notifications WHERE userid ='.$userID;
$qry = pg_query($sql);
$row = pg_fetch_array($qry);
echo $row['count'];
jQuery & JavaScript
var old_count = -1;
setInterval(function() {
$.get("file.php", { userid: "userid" },
function(data){
if (data > old_count) {
alert("the list is updated with: " + data);
//OR
//console.log('the list is updated with:' + data);
old_count = data;
}
}
)},5000); // every 5 seconds
once the user is logged in, the userid must be sent periodically to the php file to check for new notifications. then display them to the user.
for count variable, i made it Increases incrementally with Database trigger.

Limt the amount a user downloads from a website, and redirect when limit is reached?

Sorry for the vague, title! I have a website with a lot of PDF files and limited monthly bandwith. What i would like to achieve (in PHP) is a way to limit each user ($_SESSION?) to a certain limit - say 50MB, and beyond that when they clicked to download another file they would be redirected to a webpage denying any further downloads (for the next 24 hours, say).
Is this possible? I'm not sure if my download "counter" can only count .pdf files (I dont want vistors to be blocked from browsing the site if they reach the limit). Any psuedo code would be greatly appreciated.
If you have all of your downloads go through a single php script:
<a href="download.php?file='filename.pdf'" />
You can do pretty much whatever you want. That php file can deliver all of your files (keeping them out of the webroot), write to your _SESSION, and it can perform your redirect. Enjoy.
If you already have a user system, I would recommend to store all information within the users profile.
So there's no problem if he deletes all his cookies and relogins!
And for guests, I would recommend captchas and session or IP based restrictions.
// Pseudo code
// download.php
function UserHasReachedLimit($file)
{
$info = $Database->QueryUserInfo('limit');
$max = $Database->GetLimitForFile($file);
if ( $info[$file] > $max )
return false;
else
return true;
}
if ( IsUser() )
{
if ( UserHasReachedLimit() )
error();
else
download();
}
else // guest
{
// session or IP based restrictions...
}
I'd probably stay away from sessions for this. Sessions are volatile and susceptible to various browser behavior. For example, in Firefox if a session is initialized, I can close Firefox, visit the same site, and session is still active. However in IE if I open up multiple tabs and visit the same site, each tabbed instance gets a new session id.
I'd recommend setting up an account system where a user has to log into your site. Then you can track their download amount at the account level, which will persist between multiple sessions.
I think you are trying to avoid forcing user to register in your site, while you are trying to track per visitor bandwidth with is unpractical with the common ways(cookies, ip ...). So, the best way(in my opinion, of course there are many improved solutions) is to make a simple registration form, say name, password and email, put an activation system per email to protect your site from of user, now each user logged in and tried to download a file, you process his request in the following steps:
1) user request for file name.pdf (check its availability and size(important)).
2) check user bandwidth:
$query = sql_query("SELECT Bandwidth, LastDownload FROM Users, Stats WHERE USER_ID=5");
$result = sql_fetch($query);
if ($result['Bandwidth'] < 50M)
showDownloadLink();
else if($result['LastDownload'] - currentTime() !=0)
echo "please wait to the next 24h";
Database should be like this:
Users:
ID_U int(key, auto increment), Name varchar(25), email varchar(255), password varchar(32), Bandwith float
Stats:
ID_S int(key, auto increment), LastDownload time, ID_U integer
Note:
Each time user download a file, you update Bandwidth row for the right user, so later you can check if particular user reach its limit or not. You have also to reset it after each 24H.
This is a generic solution and many thinks have to be checked, like the counter bandwidth must be reset every 24H.
Create a table to store count downloads
CREATE TABLE IF NOT EXISTS `downloaded` (
`ip` varchar(200) NOT NULL,
`count` int(11) NOT NULL DEFAULT '0',
`last_access` datetime DEFAULT NULL,
UNIQUE KEY `ip` (`ip`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<?php
/*
$limit => Number of Downloads Allowed
$period => In minutes
*/
function UserHasReachedLimit($limit, $period) {
$ip = addslashes($_SERVER['REMOTE_ADDR']);
$dl = false;
$sql = sprintf("SELECT UNIX_TIMESTAMP(last_access) last_time, count FROM downloaded WHERE ip = '%s' ORDER BY last_access DESC", $ip);
$res = mysql_query($sql);
if (mysql_num_rows($res) > 0) { // There is a registered IP already
$last_xs = mysql_result($res, 0, 'last_time');
$last_xs += $last_xs+$period * 60;
$count = mysql_result($res, 0, 'count'); // number of downloads by this ip
if ($count == $limit && $last_xs > time()) { // we check if downloads reached in this period
$dl = true;
} else {
$sql = sprintf("UPDATE downloaded SET count = CASE WHEN count >= %s THEN 0 ELSE count+1 END, last_access=now() WHERE ip ='%s'", $limit+1, $ip); // we just update download count + 1
mysql_query($sql);
}
} else { // There is not a registered IP and we create it
$sql = sprintf("INSERT INTO downloaded VALUES ('%s', '0', NOW());", $ip); mysql_query($sql);
}
return $dl;
}
/*
Usage
*/
$limit = 2;
$period = 2;
if(UserHasReachedLimit($limit, $period) == true) {
// User reached number of 2 downloads in 2 minutes
} else {
// Continue downloading
}
?>

How do I script a friend request using php/ajax/jquery?

I would appreciate help with this script:
I have this script on a page called members, what I want this script to do is when a member, let's say member A, sends a friends request by clicking the button, first the status changes to something say 'requesting...', then the script sends the request to php via the script this is what I have:
<script type="text/javascript">
var email_cont = '<?=$mem_com[email]?>';
var cont_email = '<?=$_SESSION[email]?>';
$('#connectButton').click(function() {
var counter = 0;
$.ajax({
url: 'requests.php? cont_email='+cont_email+'&email_cont='+email_cont+'&counter='+counter,
success: function( data ) {
$('#connectButton').val(data); // set the button value to the new status.
$('#connectButton').unbind('click');
}
});
});
</script>
For clarity:
the button has a default values called form the database.
cont_email is the email of the member sending request
email_status is the email receiving the request
counter is the request count for every request sent to the members
However, my problem with script is that it only allows for one click on the request button as there are more than one posts from members on the page as it changes the status for all members even when a particular member have not sent any request. ie members A sends request to B, the status should show that request has been sent but however members C login the status of Member A/B request is still display, I want a way to make the status exclusive to each members, status should only show for a particular memeber if request has been sent else the status bears the default value.
Here is my PHP code:
$email_cont = $_GET['email_cont'];
$cont_email = $_GET['cont_email'];
$counter = $_GET['counter'];
$status = "Connection Sent!";
$insert = mysql_query("INSERT INTO reqst VALUES ('','$cont_email','$email_cont','$status', '$counter', NOW())");
if(!$insert) {
//If it fails to run the SQL return an error.
echo "Connection Failed!";
} else {
$update = mysql_query("UPDATE upd SET request ='$status' WHERE email ='$email_cont'");
//If all goes well, return the status
echo $request;
}
I need a way to separate the request made by member A to B from members B to C so that the $update only update the table called upd status for A to B while B and C or C to D maintains the default values as no request is sent yet. so that when the $request is echoed it only carry the request status of the members according to the request status, ie X if request is made, Y if no request is made, Z if request is accepted .
Use jQuery $.get function to send get request to requests.php
$.get('requests.php' , {email_cont: "name#domain.com", cont_email: "name#domain.com", counter: "counter..", function(data){
$('#connectButton').val(data);
$('#connectButton').unbind('click');
});

Categories