Pokergame with PHP and Jquery - Browser-Back-Button behaviour - php

For practicing reasons I programmed a little Texas Holdem Game in PHP with some JQuery Animations. Every action (bet, fold, check, raise, call) is submitted via a HTML form to a PHP script.
Now unfortunately the user is able to just go back to the first betting round after seeing the whole board and the computer's cards and adjusting his betting structure accordingly by using the back-ubtton of the browser.
Is there a practical way for me to prevent this?
Thanks,
Coffeehouse
PS:
A buttonscript is for example this:
if (isset($_POST['call']) AND $_SESSION['bettingcap'] == 1){
$_SESSION['kapitalspieler'] -= $smallbet; // deduct money from player
$_SESSION['pot'] += $smallbet; // add this to the pot
$_SESSION['bettingcap'] = 0; // After call go to next street, so cap is 0
$_SESSION['buttonmodus']=1; // I want to show only certain buttons
$_SESSION['whichstreet']=$_SESSION['whichstreet']+1; // go to next street
$_SESSION['animateagain']='yes'; // show JQuery Animation
}

You need to invalidate the request. That means one request follows after the other.
You do this by storing all requests of that user in the game.
If a new request is send, it can be only added at the end.
You can create the game in memory by initializing it and the pass in all events from all sides until a specific one.
This model does allow you to prevent cheating as well as re-playing a game like in a view mode of previous games.
00 created game ID:#7575
01 player joined seat:1; ID:#12
02 player joined seat:2; ID:#56
03 player joined seat:3; ID:#87
04 deck shuffled order:the cards order here.
05 ...
So you keep these events and if a new request is send by a user you can check if it is okay with the current situation or not.

Perhaps something like this will work.
<SCRIPT type="text/javascript">
window.history.forward();
function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
onpageshow="if (event.persisted) noBack();" onunload="">
From link

Related

How to evenly split traffic between two pages

Purely hypothetical at this point, no code yet. Trying to figure out the best way to do this. We are company "A" and we have two partners, company "B" and company "C". On a sign up form, we collect data and then pass it on to either partner "B" or parnter "C" - this part is good to go and working fine. I do this with ajax on the front end and a cURL processor on the back end so no one leaves our site and just post the data directly to the partner's form.
Unfortunately due to partner "B" and "C"'s required data the forms we post to are different and we have to have 2 separate html form files, one for each partner. The problem is that we need to do this all from one URL, not a separate one for each partner.
I would guess we would use a 'handler' page that has the specific url - http://www.example.com/parterForm.php
Then in the 'handler' page we would make the switch serve the correct content. I need a way to evenly split who we send data to. I'd like to do the switch on a very granular, MS level for example:
if the time = 0-500 ms - serve Parter B page;
if time = 501-1000ms -serve Partner C page;
all done within the 'handler' page - calling the forms as php includes?
I realize this is not a specific code question and I aplogize, this is something I've never done before and am trying to figure out how to do this. I'm a Creative Director btw who codes, no other resource avail.
thanks.
Hmm, yes, you could do that. That would work reasonably well, in fact. The important thing is to make sure the form goes to the right partner. You could use $_SESSION for that, or check which fields were sent and deduce from that which partner was chosen.
For example:
if( fmod(microtime(),1) < 0.5) include("forms/partner1.php");
else include("forms/partner2.php");
Then when submitted:
$partner1fields = array("name","email","country","dateofbirth");
$partner2fields = array("name","address","postcode","ethnicity");
// the above are examples - they should correspond to the $_POST keys you expect
// now check if they match. Array equality depends on order, so sort first
$postkeys = array_keys($_POST);
sort($postkeys);
sort($partner1fields);
sort($partner2fields);
if( $postkeys == $partner1fields) { /* submit to partner 1 */ }
elseif( $postkeys == $partner2fields) { /* submit to partner 2 */ }
else {
echo "<p>Given keys did not match either partner</p>";
echo "<p>POST keys: ".implode(", ",$postkeys)."</p>";
echo "<p>Partner 1 keys: ".implode(", ",$partner1keys)."</p>";
echo "<p>Partner 2 keys: ".implode(", ",$partner2keys)."</p>";
echo "<p>Please report this error to the site administrator.</p>";
exit;
}
First, by MS I assume you mean the latency between client and server?
Use javascript to either load a tiny image from the server or make an ajax call that gets one char or something and time this. For testing you'll need to do some real pings and adjust your js time to reflect the ping round trip. For example, if the js time to load the image is 500ms but ping time is only 80ms then maybe divide by 6 for the result. This will never be very precise as the client and the server both have processing overhead. Make sure to echo no cache headers or past expire times with the image or ajax response.
Easy, if time <= 500 redirect to form A, if time > 500 redirect to form B or use ajax to load them up.

preventing duplicates infinite scrolling ajax loader

it might just be too late at night for me to see a clear solution here, but I figured I'd get some thoughts from anybody with an opinion...
the site i'm working on has a long list of user posts. i've got all the scroll event handlers working to ajax in the next batch of 100 posts when you reach or approach the bottom.
my question is... How do i prevent the following scenario?
UserX visits the site and loads posts 1-100
10 more users visit the site and add 10 more posts
UserX scrolls to bottom and loads posts 101-200, which used to to be posts 91-190
UserX ends up with duplicates of posts 91-100 on the page
i'll include a stripped down version of my code below in case it helps anybody else along
$.ajax({
type:'POST',
url:"/userposts.php",
data:{ limit: postCount },
success:function(data) {
$("postsContainer").append(data);
if ( $("postsContainer").find("div[id='lastPostReached']") ) {
// unbind infinite scrolling event handlers
}
},
dataType:'html'
});
in my PHP script I have essentially the following:
if ( ! isset($_POST["limit"]) ) {
$sql .= " LIMIT 101"; // initial request
} else {
$sql .= " LIMIT {$_POST["limit"]},101
}
$posts = mysql_query($sql);
while( $post = mysql_fetch_assoc($posts) ) {
/* output formatted posts */
}
// inform callback handler to disable infinite scrolling
if ( mysql_num_rows($posts) < 101 ) {
echo '<div id="lastPostReached"></div>';
}
This gives me infinite scrolling nice and easy, but how can I prevent the hypothetical duplicates that would show up when new records have been added to the table between ajax requests?
You define a timestamp from php that indicates the servertime at the time the page loads (eg var _loadTime = <?php echo time(); ?>) and then pass this value as part of the Ajax data config object along with limit.
Then on the server side you can exclude any posts that were created after this time and hense preserve your list.
You can also go a step further and use this time along with a basic ajax long polling technique to notify the user of new posts since the page loaded/last loading of new posts - similar to Facebook and Twitters feeds.
Update your ajax request, so that in addition to the limit parameter you pass through the current range of post ids (I'm assuming the posts have some kind of unique id). Update your php to take those parameters into account when retrieving the next set of posts.
That is, instead of saying "give me another 100" the request is "give me 100 starting at id x".
(Sorry, I don't have time now to write an example code for this.)
Just use a unique identifier ID for the posts and count backwards.
First visit user requests posts 603-503
Ten users get on the page and add comments so the highest comment is now 613
User scolls down and requests 503-403
Problem solved? :)

Updating multiple page elements without refreshing the page using PHP & jQuery

I have a PHP page that uses jQuery to let a user update a particular item without needing to refresh the page. It is an availability update where they can change their availability for an event to Yes, No, or Maybe. Each time they click on the link the appropriate jQuery function is called to send data to a separate PHP file (update_avail.php) and the appropriate data is returned.
Yes
Then when clicked the params are sent to a PHP file which returns back:
No
Then, if clicked again the PHP will return:
Maybe
It all works fine and I'm loving it.
BUT--
I also have a total count at the bottom of the page that is PHP code to count the total number of users that have selected Yes as their availability by simply using:
<?php count($event1_accepted); ?>
How can I make it so that if a user changes their availability it will also update the count without needing to refresh the page?
My thoughts so far are:
$var = 1;
while ($var > 0) {
count($day1_accepted);
$var = 0;
exit;
}
Then add a line to my 'update_avail.php' (which gets sent data from the jQuery function) to make $var = 1
Any help would be great. I would like to stress that my main strength is PHP, not jQuery, so a PHP solution would be preferred, but if necessary I can tackle some simple jQuery.
Thanks!
In the response from update_avail.php return a JSON object with both your replacement html and your new counter value.
Or to keep it simple, if they click "yes" incriment the counter, if they click No or maybe and their previous action wasn't No or Maybe decrease the counter.
Assuming your users are logged into the system I'd recommend having a status field in the user table, perhaps as an enum with "offline", "available", "busy", "unavailable" or something similar and use the query the number of available users whilst updating the users status.
If you were to do this you'd need to include in extend your methods containing session)start() and session_destroy() to change the availability of the user to available / offline respectively
The best way is the one suggested by Scuzzy with some improvements.
In your php, get the count from the database and return a JSON object like:
{ count: 123, html: 'Yes' }
In your page, in the ajax response you get the values and update the elements:
...
success: function(data) {
$("#linkPlaceholder").html(data.html);
$("#countPlaceholder").html(data.count);
}
...

Display Ads To % of Users

I have a site that I want to display ads to 10% of my traffic. I am getting on average around 30,000 hits a day and want 10% of those users to see an ad from one of my advertisers.
What's the best way to go about implementing this?
I was thinking about counting the visitors in a database, and then every 10 people that visit 1 user gets an ad. Or is there a better way of going about it?
I'm no good with math, so I'm not sure what's the best approach.
Generate a random number between 1 and 10, and compare it to a fixed number, and your code will run on average 10% of the time:
if (rand(1,10) == 1) {
echo 'ad code';
}
You can make this per-user instead of per-pageview by storing whether that user was 'chosen' in their session.
session_start();
if (isset($_SESSION['show_me_ads']) || rand(1,10) == 1)
$_SESSION['show_me_ads'] = true;
echo 'ad code';
}
I use Google's DFP (Doubleclick for Publishers) to serve ads on my site. It's pretty robust. You have to have an AdSense account, but that's not very hard to obtain, it's just annoying to wait to be approved.
Once you have it set up and your ads loaded in, you can control how many people see your ad by percentage (such as the 10% you were talking about), total pageviews, etc.
Look into it: http://google.com/dfp
If you'd rather not use 3rd party software, I'd think the simplest way would be to randomize it so 1/10 visitors see your ad. The simple way would be:
if (rand(1,10) == 1) {
echo 'YOUR AD CODE HERE';
}
You said you're not good at math, and I understand that, I'm pretty horrible at it too, but basically, every time the page is loaded, it's "rolling" a 10-sided "dice". Every time it "rolls" a 1 (which would be 1 out of 10 times, or 10%), it'll display the ad. Otherwise, it'll be ignored.
The reason this is better than relying on counting the number of users (aside from simplicity) is that it will still roll 1 10% of the time whether you have 30,000 visitors or 3,000,000.
In its simplest form:
if (rand(1,10) == 1) {
echo $ad_content;
}
if(rand ( 1,10) == 1)
display_ads();
You can use
if(mt_rand(1,10)==10){
//show your code;
}
It will show ads to about 10% users
Why would you show ads to a few unlucky ones instead of randomly deciding per page impression (instead of per visitor)?
In php, you can just go ahead and write:
$adPercent = 10;
if (rand(0, 100) < $adPercent) {
echo '<div class="ads">Buy now!</div>';
}
if this was for google ads, then you would need to make the ad insertion optional (using the prob logic above), suggest something along the lines of Google Ads Async (asynchronous)
<script type="text/javascript"><!--
// dynamically Load Ads out-of-band
setTimeout((function ()
{
// placeholder for ads
var eleAds = document.createElement("ads");
// dynamic script element
var eleScript = document.createElement("script");
// remember the implementation of document.write function
w = document.write;
// override and replace with our version
document.write = (function(params)
{
// replace our placeholder with real ads
eleAds.innerHTML = params;
// put the old implementation back in place
document.write=w;
});
// setup the ads script element
eleScript.setAttribute("type", "text/javascript");
eleScript.setAttribute("src", "http://pagead2.googlesyndication.com/pagead/show_ads.js");
// add the two elements, causing the ads script to run
document.body.appendChild(eleAds);
document.body.appendChild(eleScript);
}), 1);
//-->
</script>

Measuring online time on website

I would like to measure how much time a user spends on my website. It's needed for a community site where you can say: "User X has been spending 1397 minutes here."
After reading some documents about this, I know that there is no perfect way to achieve this. You can't measure the exact time. But I'm looking for an approach which gives a good approximation.
How could you do this? My ideas:
1) Adding 30 seconds to the online time counter on every page view.
2) On every page view, save the current timestamp. On the next view, add the difference between the saved timestamp and the current timestamp to the online time counter.
I use PHP and MySQL if this does matter.
I hope you can help me. Thanks in advance!
This is probably pointless.... what if the user has three tabs open and is "visiting" your site while actually working on the other two tabs? Do you want to count that?
Two factors are working against you -
You can only collect point-in-time statistics (page views), and there's no reasonable way to detect what happened between those points;
Even then, you'd be counting browser window time, not user time; users can easily have multiple tabs open on multiple browser instances simultaneously.
I suspect your best approximation is attributing some average amount of attention time per click and then multiplying. But then you might just as well measure clicks.
Why not just measure what actually can be measured?: referrals, page views, click-throughs, etc.
Collecting and advertising these kinds of numbers is completely in line with the rest of the world of web metrics.
Besides—if someone were to bring up a web page and then, say, go on a two week holiday, how best to account for it?
What you could do is check if a user is active on the page and then send an ajax request to your server every X seconds (would 60 secs be fine?) that a user is active or not on the page.
Then you can use the second method you have mentioned to calculate the time difference between two 'active' timestamps that are not separated by more than one or two intervals. Adding these would give the time spent by the user on your site.
google analytics includes a very powerful event logging/tracking mechanism you can customize and tap into get really good measurements of user behavior - I'd look into that
A very simple solution is to use a hidden iframe that loads a php web page periodically. The loaded web page logs the start time (if it doesn't exist) and the stop time. When the person leaves the page you are left with the time the person first came to the site and the last time they were there. In this case, the timestamp is updated every 3 seconds.
I use files to hold the log information. The filename I use consists of month-day-year ipaddress.htm
Example iframe php code. Put this in yourwebsite/yourAnalyticsiFrameCode.php:
<?php
// get the IP address of the sender
$clientIpAddress=$_SERVER['REMOTE_ADDR'];
$folder = "yourAnalyticsDataFolder";
// Combine the IP address with the current date.
$clientFileRecord=$folder."/".date('d-M-Y')." ".$clientIpAddress;
$startTimeDate = "";
// check to see if the folder to store analytics exists
if (!file_exists($folder))
{
if (!mkdir($folder))
return; // error - just bail
}
if (file_exists($clientFileRecord) )
{
//read the contents of the clientFileRedord
$lines = file($clientFileRecord);
$count = 0;
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line)
{
echo($line);
if ($count == 0)
$startTimeDate = rtrim( $line );
$count++;
}
}
if ($startTimeDate == "")
$startTimeDate = date('H:i:s d-M-Y');
$endTimeDate = date('H:i:s d-M-Y');
// write the start and stop times back out to the file
$file = fopen($clientFileRecord,"w");
fwrite($file,$startTimeDate."\n".$endTimeDate);
fclose($file);
?>
The javascript to periodically reload the iframe in the main web page.:
<!-- Javascript to reload the analytics code -->
<script>
window.setInterval("reloadIFrame();", 3000);
function reloadIFrame() {
document.getElementById('AnalyticsID').src = document.getElementById('AnalyticsID').src
// document.frames["AnalyticsID"].location.reload();
}
</script>
The iframe in the main web page looks like this:
<iframe id="AnalyticsID" name="AnalyticsID" src="http://yourwebsite/yourAnalyticsiFrameCode.php" width="1"
height="1" frameborder="0" style="visibility:hidden;display:none">
</iframe>
A very simple way to display the time stamp files:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
Analytics results
<br>
<?php
$folder = "yourAnalyticsDataFolder";
$files1 = scandir($folder);
// Loop through the files
foreach ($files1 as $fn)
{
echo ($fn."<br>\n");
$lines = file($folder."/".$fn);
foreach ($lines as $line_num => $line)
{
echo(" ".$line."<br>\n");
}
echo ("<br>\n <br>");
}
?>
</body>
</html>
You get a results page like this:
22-Mar-2015 104.37.100.30
18:09:03 22-Mar-2015
19:18:53 22-Mar-2015
22-Mar-2015 142.162.20.133
18:10:06 22-Mar-2015
18:10:21 22-Mar-2015
I think client side JavaScript analytics is the solution for this.
You have the google analitycs, piwik, and there also commercials tools in JS that do exactly that.

Categories