PHP controlling the output of rand - php

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;

Related

What I'm doing wrong? "session start"

The first code below should show random numbers between 10-400
The second code should show random numbers between 400-3000
If I use one code alone it will works correctly.
But If I post both codes like this in one page the second code will work on the first code between 10-400.
What I'm doing wrong?
Here is my code:
<?php
session_start();
if(isset($_SESSION['num'])){
$num = mt_rand($_SESSION['num']-5, $_SESSION['num']+5);
}else{
$num = mt_rand(10, 400);
}
echo $num . " Gold coin";
$_SESSION['num'] = $num;
?>
<?php
session_start();
if(isset($_SESSION['num'])){
$num = mt_rand($_SESSION['num']-5, $_SESSION['num']+5);
}else{
$num = mt_rand(400, 3000);
}
echo $num . " Pink Coin";
$_SESSION['num'] = $num;
?>
It's because you're using the same session variable for both pieces of code, and after your first piece you set $_SESSION['num'] (which will be a value between 10 and 400), so the second piece of code will then take the first if branch and generate a value between the first value -5 and +5 (so it will be between 5 and 405). You should use different session variables for each coin type e.g.
session_start();
if(isset($_SESSION['gold'])){
$gold= mt_rand($_SESSION['gold']-5, $_SESSION['gold']+5);
}else{
$gold= mt_rand(10, 400);
}
echo $gold. " Gold coin";
$_SESSION['gold'] = $gold;
if(isset($_SESSION['pink'])){
$pink= mt_rand($_SESSION['pink']-5, $_SESSION['pink']+5);
}else{
$pink= mt_rand(10, 400);
}
echo $pink. " Pink coin";
$_SESSION['pink'] = $pink;
Note you should only call session_start() once.

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;
}
}

My countdown doesnt start on my betting site

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>

Making a virtual shelf and populating it via a database

I'm trying to make a virtual shelf type of thing which is populated via a MySQL database. The column shelfPos holds the position of the item on the shelf. Each row/'shelf' starts with <div class="shelfRow"> and obviously ends with </div> so it's styled and positioned correctly. Items on the shelves can be moved around using the jQuery UI droppable interaction.
The overall layout is this: http://jsfiddle.net/aRA5D/
Each shelf can hold 5 items (left to right).
I'm having trouble populating the shelves. At the moment I've got this: (This is in the place of the HTML)
<?php
$sql="SELECT * FROM shelf WHERE userID='$userID'";
$result=mysql_query($sql);
if (mysql_num_rows($result) == 0) {
// Show a message of some sort? (No items)
}
else {
$tries = 1;
$times = 10; // How many shelves. (10 = 2 shelves)
while(($row = mysql_fetch_array($result)) && ($tries <= $times)) {
while ($tries <= $times) {
if ($tries == $row['shelfPos']) {
echo '<div class="drop" id="drop'.$tries.'"><div class="boxArt" id="'.$row['gameID'].'">'.$row['gameID'].'</div></div>';
}
else {
echo '<div class="drop" id="drop'.$tries.'"></div>';
}
$tries = $tries + 1;
}
$times = $times + 5;
}
}
?>
There's several things wrong with it. It doesn't include the <div class="shelfRow"> html (didn't know how/where to put it, as it needs to be echoed after every 5 'blank' and real items - for loop maybe?) and it requires me to input the number of shelves (2 in this case). Would it be possible to determine how many shelves are required based on the item's position? It's awkward to do because it also needs to echo 'blank' .drop divs before and after them so that the items can be moved around.
Hope this all makes sense. Thanks for the help!
First u need to get data in order of ShelfPos
"SELECT * FROM shelf WHERE userID='$userID' order by shelfPos asc"
And try this code:
...
$i = 0;
while($row = mysql_fetch_array($result)) {
//Each 5
if($i % 5 == 0) echo '<div class="shelfRow">';
if ($i == $row['shelfPos']) {
echo '<div class="drop" id="drop'.$i.'"><div class="boxArt" id="'.$row['gameID'].'">'.$row['gameID'].'</div></div>';
}
else {
echo '<div class="drop" id="drop'.$i.'"></div>';
}
//close shelfrow div
if($i % 5 == 4) echo '</div>';
$i++;
}
//to complete the loop
$shelv_left = 5 - ($i % 5);
if($shelv_left < 5) {
for($j=0; $j < $shelv_left; $j++) {
echo '<div class="drop" id="drop'.($i+$j).'"></div>';
}
echo '</div>'; // end shelfrow div
}
...

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.

Categories