My countdown doesnt start on my betting site - php

I have a csgo betting site, when atleast 2 players deposit their skins into the site it the game starts and it takes 2 minutes until the the bot picks a winner.
Everything works fine, the game starts, a winner is picked 2 minutes after the game started, but the countdown text that are supposed to display the seconds left is not working.
this is my code Time left: <h4 id="countdown-timer"><span id="timeleft">0</span></h4>
Accepted trade offer #1211760373 by XXXXXXX (XXXXXXXXXXXXXX)
Current Players: 1
Accepted trade offer #1211760308 by XXXXXXXXX (XXXXXXXXXXXXXXX)
Current Players: 2
Found 2 Players
and that is what the bot says
and this is the timeleft.php http://prnt.sc/b03ute
PHP Code
<?php
#include_once ("set.php");
$game = fetchinfo("value", "info", "name", "current_game");
$r = fetchinfo("starttime", "games", "id", $game);
$somebodywon = fetchinfo("winner", "games", "id", $game);
if ($r == 2147483647)
die("120");
$r += 120 - time();
if ($r < 0) {
$r = 0; /* if(empty($somebodywon)) include_once('getwinner34634f.php'); */
} echo $r;
?>
Found this one aswell, called ssetimeleft.php
<
?php
#include_once ("set.php");
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
/**
* Constructs the SSE data format and flushes that data to the client.
*
* #param string $id Timestamp/id of this connection.
* #param string $msg Line of text that should be transmitted.
*/
function sendMsg($id, $msg) {
echo "id: $id" . PHP_EOL;
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
while (1) {
$game = fetchinfo("value","info","name","current_game");
$r = fetchinfo("starttime","games","id",$game);
if($r == 2147483647){
$var=120;
}else{
$var = $r += 120-time();
if($r < 0)
{
$var = 0;
/*if(empty($somebodywon))
include_once('getwinner34634f.php');*/
}
}
sendMsg(time(),$var);
usleep(500000); //1000000 = 1 seconds
}
?>

It's difficult to see what you are trying to do here without more information but the time() function in your PHP file runs only when the server-side PHP processor processes this file. The countdown display, however, is something that should be handled client side.
I recommend adding a javascript or jQuery file to handle the countdown display for you.

Try this its a very basic example :
$(function() {
var time_out = 10;
var timeout = setInterval(calculate, 1000);
function calculate() {
$('#timeleft').text(time_out--);
if (time_out < 0) {
clearInterval(timeout);
}
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h4 id="countdown-timer"><span id="timeleft">0</span></h4>
</body>
</html>

Related

PHP echo 5000 records and Unset

I would like to echo records from a large data set of 300000.
echo first 5000 records than unset($data) and iterate until end of records in the mysql table.
Something like this,
1)
for ($i=0; $i < 5; $i++) {
$data = openssl_random_pseudo_bytes(1000000);
echo "peak_memory_usage = ” . memory_get_peak_usage(true) . “\n”;
doSomething($data);
//unset($data);
}
echo “for loop completed, memory now at ” . memory_get_usage(true) . “\n”;
function doSomething($data) {
echo “size:” . strlen($data) . “\n”;
}
or something like this?
2)
nRows = $pdo->query('select count(*) from employees')->fetchColumn();
$users = new ArrayIterator(range(1, nRows)); // nRows are 3000000 test records
foreach(new LimitIterator($users, 0, 50000) as $u) {
echo $u, "\n";
}
OR
3) #Sameer would you like to add your suggestion to the query below, I might be doing something wrong adding usleep-my coding flaws, which causes the issue of timeout when usleep is added.
$data = $DB->query("SELECT * FROM user_details")->fetchAll();
foreach ($data as $row) {
echo $row['username']." -- ID :" .$row['user_id']. " -- FirstName :" .$row['first_name']. "<br />\n";
}
The third 3) options works fine 50,000 records not much of load on RAM but CPU, is there a way to optimize this to reduce the load on CPU, imagine if 30 people run the same query it will maxed out the CPU? and if i add usleep(10) - it echos the records but with an error at the end saying timeout.
Any suggestions are highly appreciated please.
many thanks for reading my post.
Modified the original post as the objective is the same to reduce load on
the server.. If you like my lengthy post, please vote guys, I am way
behind and I would like to be a contributor in future.
I stumble across an amazing solution by (Dm4Web) data load - amazing solution - but need HTML tables/append o be added and append the results.
Splitting an AJAX call which returns 5000 rows into multiple AJAX calls with 100 rows
Getting error on line 49 Uncaught SyntaxError: Unexpected identifie, when tried to run the script below:
<!DOCTYPE html>
<html>
<head>
<title>SQL Batch List AJAX and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div id="mainform">
<h2>Fetch REcords 5000 at a time</h2>
<div id="listData">
<div>
<input id="load" name="load" type="button" value ="Load Data">
<input id="cancel" name="cancel" type="button" value ="Cancel">
</div>
</div>
</div>
</body>
<script>
// counter that allows you to get a new set of rows
var step = 0;
// set variable if you want to restrict the number of rows will be loaded
var maxStep = 0;//
// how many rows should be returned
var count = 5000;
// if the cancel button is pressed
var cancel = false;
$(function() {
$('#load').click(function(){
getData();
})
$('#cancel').click(function(){
cancel = true;
})
});
function getData()
{
step++;
//If cancel variable is set to true stop new calls
if(cancel == true) return;
// checks if the variable is set and limits how many rows to be fetched
if(maxStep >0 $$ step >= maxStep)
$.post('ajax.php'
,{
'step':step,
'count':count,
}
,function(data, textStatus, jqXHR){
if(textStatus == "success")
alert("Data: " + data);
/* foreach (data as $row) {
echo $row['username']." -- ID :" .$row['user_id']. " -- FirstName :" .$row['first_name']. "<br />\n";
} */
if(textStatus == "error")
alert("Error: " + jqXHR.status + ": " + jqXHR.statusText);
// when it finishes processing the data, call back function
getData();
}
,'json'
)
}
</script>
</html>
==== ajax.php =====
step = 0;
if(isset($_POST['step'])) $step = (int)$_POST['step'];
$count = 0;
if(isset($_POST['count'])) $count = (int)$_POST['count'];
if($step>0 and $count>0)
{
$offset = ($step-1) * $count;
$limit = $offset.','.$count;
// --------------
// your code here
// --------------
$data = $DB->query("SELECT * FROM user_details LIMIT .$limit")->fetchAll();
$result = mysql_query($sql);
$arr_result = array();
foreach ($data as $row) {
$arr_result[] = $row;
}
$arr_result_enc = json_encode($arr_result);
echo $arr_result_enc;
// echo rows
//echo json_encode($rows);
}
Method 4)
$query = "SELECT COUNT(*) as num FROM employees";
//$select_run = mysqli_query($conn, $select);
$result = mysqli_query($conn, $query) or die(mysql_error());
$row = mysqli_fetch_array($result);
$itemcount = $row['num']; // Roughly 300,000 total items
$batches = $itemcount / 2000; // Number of while-loop calls - around 120.
for ($i = 0; $i <= $batches; $i++) {
$offset = $i * 2000; // MySQL Limit offset number
$query = "SELECT first_name,last_name FROM employees LIMIT 2500, $offset ";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($result)) {
echo $row['first_name'];
}
echo "<BR>";
echo "Run Number: ".$i."<br />";
echo "<BR>";
}
$data is already getting overwritten, so that's not the problem here.
Heavy loops create constant tension on the server, which increases the load.
You can add sleep of few microseconds to allow server free up resources and some breathing time, which will lower the server load. Use usleep and set optimal microseconds.
for ($i=0; $i < 5; $i++) {
usleep(100);
$data = openssl_random_pseudo_bytes(1000000);
}
Ideas to fix your third attempt:
Select the columns you need instead of selecting *.
Cache the result so only need to run it once for each person that loads the page.
Add a LIMIT (paginate) so you only select the first 100 or 1000 rows instead of 50,000. This will also stop the browser from exploding when you load 50k rows at the same time.

How to get the Round Trip Time in my PING using PHP

So i have this code that whenever an IP is ping able or up it'll choose the green line to appear on my screen and in reverse the red line. So what I am trying to do instead if the Round Trip Time of that IP is < 200 then it's green and when it's > 250 it's red . How can i do that?
Anyone help me. Thank you.
<?php
$page = $_SERVER['PHP_SELF'];
$sec = 5;
function pingAddress($TEST) {
$pingresult = exec("ping -c 1 $TEST", $output, $result);
if ($result == 0) {
echo "Ping successful!";
echo "<pre>Your ping: $TEST</pre>";
echo "<hr color = \"green\" width = 40%> GOOD";
} else {
echo "Ping unsuccessful!";
echo "<pre>Your ping: $TEST</pre>";
echo "<hr color = \"red\" width = 40%> BAD";
}
}
pingAddress("66.147.244.228");
?>
<html>
<head>
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
</head>
<body>
</body>
</html>
The exec function is ok to use, but you should parse the contents of the output argument, after declaring it first as an array.
Even if you added -c 1 to only issue one ping, this is the recommended way of using exec.
define('RETRIES', 1);
define('PING_PATH', '/usr/bin/ping');
function pingAddress($IP)
{
$output = array();
exec(PING_PATH . " -c " . RETRIES . " $IP", $output);
// generic way, even for one line. You can also do -c 4,
// and preg_match will pick the first meaningful result.
$output_string = implode("; ", $output);
/// adapt the regular expression to the actual format of your implementation of ping
if (preg_match('/ time=\s+(\d+)ms/', $output_string, $bits)) {
$rt_time = (int)$bits[1];
if ($rt_time < 200) {
// green business
}
else if ($rt_time > 250) {
// red business
}
else {
// default handler business (or not...)
}
}
else {
echo "Hum, I didn't manage to parse the output of the ping command.", PHP_EOL;
}
}

PHP + Javascript parent function not getting called

Alright I've been trying to find an answer to this for hours already but I couldn't resolve it myself.
I'm trying to call a Javascript parent function from a PHP function, however, it is not getting called.
When using the onclick method onclick='parent.dosomething(); everything seems to work fine but if I try to call the function by echo'ing it out, it would just fail for some reason.
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
Here's the PHP function:
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" );
$actualtime = time();
$timetoseconds = $actualtime - $timeposted;
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
}
}
}
}
}
And this is my Javascript function at the parent page:
function reloadprofmessages()
{
$('#friendrequests').load('showprofmessages.php?username=<?php echo $actualuser; ?>').fadeIn("slow");
} //refreshes messages
I pressed CTRL + Shift + I in Google Chrome to get to the developer tools, Network > page that does the request that calls the PHP function > Preview and this was what I received:
<script>parent.reloadprofmessages();</script>
However, the function is not getting called.
Resolving this would solve me a lot of problems, to me it is actually still a mystery to know why it doesn't work since it has worked in other cases.
Thank you for your help in advance.
It's not a good idea to fetch javascript and execute it with AJAX. What I would suggest is to firstly change your PHP to this:
if($activity_type == 1) //Messages
{
echo "1";
}
else {
echo "0";
}
Then change your Javascript to this:
function reloadprofmessages()
{
var can_reload = $.ajax({ url: "showprofmessages.php?username=<?php echo $actualuser; ?>" });
if (can_reload) {
parent.erloadprofmessages();
}
}
Hope that helps
Add the type attribute for script tag
echo "<script type='text/javascript' >parent.reloadprofmessages();</script>";
and remember to define the javascript function before this line
So here is what was wrong: (Showing errors)
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" ); //$timeactivity was not being used
$actualtime = time();
$timetoseconds = $actualtime - $timeposted; //$timeposted doesn't even exist, in other words I wasn't even converting the $activity_date timestamp to time.
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this was not the correct way of calling a function from the parent page.
}
}
}
}
}
About the Javascript function:
This is what I ended with:
var auto_refresh = setInterval(
function reloadstring()
{
$.get("checknewactivity.php?vprofile=<?php echo $actualuser; ?>", function(activity){
if (activity == 1)
{
$('#profcommentsdiv').load('showprofmessages.php?vprofile=<?php echo $actualuser; ?>').fadeIn("slow");
}
});
}, 1000); // refresh every 1000 milliseconds
And now it works, thank you for your help, I really appreciate it, and as usual, I always get to a safer solution after asking it here.

changing title in php on refresh using cookies

while ($row = mysql_fetch_row($result))
{
echo "<tr>";
echo ("<p><td>$row[2]</td><td>$row[0]</td><td>$row[1]</td><td><i>$row[3]</i></td><td><center>[x]</center></td></p>");
echo "</tr>";
$x++;
}
echo "</table>";
}
else
{
echo "*No Accounts*";
}
if (isset($_COOKIE['amountx'])) {
if ($_COOKIE['amountx'] < $x) {
$x = $x - $_COOKIE['amountx'];
echo "<title>'New Logs - ($x)'</title>";
}
else if ($_COOKIE['amountx'] == $x) {
echo "<title>'Logs (0)'</title>";
}
else {
setcookie("amountx", $x, time() + 60 * 60 * 24 * 30);
}
}
else {
setcookie("amountx", $x, time() + 60 * 60 * 24 * 30);
}
The title never updates but the cookie is saved. This was in the while loop but I took it out and it still saves the cookie amount. But I can't get it to display the new title even after refreshing every 5 seconds via meta-refresh. How can I update the title?
Looking at the structure of your code, it appears that you're printing HTML in the <body> tag before you're attempting to echo a different <title> tag.
You can't have a <title> tag anywhere but within the <head> element.
Move your <title> code to take effect within the <head> element, and it should work.
I removed the top <title>Page title</title> at the top of my page now it works properly thanks guys.

PHP controlling the output of rand

Is it possible to control the output of rand, for example if I just want rand to give me the output of the variable $roll1 with the value or number of 1 half the time out of the six possibilities when rand is ran or when the browser is refreshed, how does one accomplish that?
My code sucks but I am fighting to learn, I only get one every now and then, but it's not consistent, I want a 1 every time I refresh the page.
So If I refresh the page 6 times I should get a 1 out of the variable $roll1 three times, and the rest of the values for $roll1 should be random.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>loaded dice</title>
</head>
<body>
<h1>loaded dice</h1>
<h3>loaded dice</h3>
<?php
// loaded dice, should roll the number 1 half the time out of a total of 6.
// So if I refreshed my browser six times I should at least see three 1's for roll1.
$roll1 = rand(1, 6);
// Okay is it possible to divide rand by two or somehow set it up
// so that I get the the value 1 half the time?
// I am trying division here on the if clause in the hopes that I can just have
// 1 half the time, but it's not working,maybe some type of switch might work? :-(.
if ($roll1 == 3) {
$roll1 / 3;
}
if ($roll1 == 6) {
$roll1 / 6;
}
if ($roll1 == 1) {
$roll1 / 1;
}
// This parts works fine :-).
// Normal random roll, is okay.
$roll2 = rand(1, 6);
print <<<HERE
<p>Rolls normal roll:</p>
You rolled a $roll2.
<p>Rolls the number 1 half the time:</p>
<p>You rolled a $roll1.</p>
HERE;
// Notice how we used $roll1 and 2, alongside the HERE doc to echo out a given value.
?>
<p>
Please refresh this page in the browser to roll another die.
</p>
</body>
</html>
You could do something like this
if (rand(0,1))
{
$roll = rand(2,6);
}
else
{
$roll = 1;
}
You can't directly make rand() do that, but you can do something like this:
<?PHP
function roll(){
if(rand(0,1)) //this should evaluate true half the time.
return 1;
return rand(2,6); //the other half of the time we want this.
}
So if you want to guarantee that in the last 6 rolls their would always have been at least 3 ones, I think you would have to track the history of the rolls. Here is a way to do that:
<?php
if (array_key_exists('roll_history', $_GET)) {
$rollHistory = unserialize($_GET['roll_history']);
} else {
$rollHistory = array();
}
$oneCount = 0;
foreach($rollHistory as $roll) {
if ($roll == 1) {
$oneCount++;
}
}
if (6 - count($rollHistory) + $oneCount <= 3) {
$roll = 1;
} else {
if (rand(0,1)) {
$roll = rand(2,6);
} else {
$roll = 1;
}
}
$rollHistory[] = $roll;
if (count($rollHistory) > 5) {
array_shift($rollHistory);
}
echo '<p>Weighted Dice Role: ' . $roll . '</p>';
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="get" >';
echo '<input type="hidden" name="roll_history" value="' . htmlspecialchars(serialize($rollHistory)) . '" />';
echo '<input type="submit" value="Roll Again" name="roll_again" />';
echo '</form>';
Rather than call rand() twice, you can simply do a little extra math.
$roll = $x = rand(1,12)-6 ? $x : 1;
A slightly different solution. It isn't as elegant, but perhaps more conducive to loading the die more finely?
$i = rand(1, 9);
if($i<=3)
{
$num = 1;
}
else $num = $i-2;

Categories