How to set random cookie value using rand function in PHP - php

How to set random cookie value using rand function in PHP
I don't want to change the value while page refreshed when it once assigned.. until cookie destroy
My code is as follows
<?php
global $random;
$random= rand(0, 9999999);
if(!isset($_COOKIE[$random])) {
setcookie('user_cookie',$random, time() + (1), "/"); echo $_COOKIE[$random];
}
else {
echo "Cookie '" . $_COOKIE[$random] . "' is set!<br>";
}
exit();
?>

if(!isset($_COOKIE['lg'])) {
setcookie('lg', rand(1,10000), time() + (86400 * 30), "/"); // 86400 = 1 day
}
echo $_COOKIE['lg'];
You can check if it is not set then set it.

<?php
define('COOKIE_KEY', 'COOKIE_KEY');
if (!array_key_exists(COOKIE_KEY, $_COOKIE)) {
setcookie(COOKIE_KEY, mt_rand(1, 10), time()+3600);
}

Your set cookie code is incorrect and the cookie time is only 1 second
change your code as follows...
<?php
//cookie_start();
global $random;
$random= rand(0, 9999999);
if(!isset($_COOKIE['user_cookie'])) {
setcookie('user_cookie',$random, time() + (86400), "/");//86400 = 1 day
}
else {
echo "Cookie '" . $_COOKIE['user_cookie'] . "' is set!<br>";
}
exit();
?>

Related

mt_rand math numbers

I want to create an application that shows multiplication, addition, subtraction and division with 2 random numbers. I made a function that shows random numbers:
function Numbers() {
echo(mt_rand() . "<br>");
echo(mt_rand() . "<br>");
echo(mt_rand(1,10));
}
Numbers();
Can someone explain to me how I can make it go +/- and x each other?
I now changed my code to this:
function Numbers() {
$Number1= echo(mt_rand() . "<br>");
$Number2= echo(mt_rand() . "<br>");
$Number1 + $Number2;
$Number1 - $Number2;
$Number1 / $Number2;
}
Numbers();
Here's an example for the addition, you figure out the rest:
$a = mt_rand();
$b = mt_rand();
echo "$a + $b = " . ($a + $b);
function printRnd()
{
$a_ = rand(1,10);
$b_ = rand(1,10);
echo "a={$a_}, b={$b_}<br><br>";
$plus_ = $a_+$b_;
$minus_ = $a_-$b_;
$multi_ = $a_*$b_;
$divid_ = $a_/$b_;
echo "a+b={$plus_}<br>";
echo "a-b={$minus_}<br>";
echo "a*b={$multi_}<br>";
echo "a/b={$divid_}<br>";
}
printRnd();

Retain the value of a random generated number

I am learning php atm and i decided to make a simple game but now im confronted with a problem. I have the following code:
<form action="wolf.php" method="POST">
<input type="submit" value="Attack" name="submit"/> <br />
<?php
$hp = 100;
if(isset($_POST['submit'])) {
$attack = $_POST['submit'];
$damage = mt_rand(5, 30);
$newhp = $hp - $damage;
if ($attkdamage = $hp - $damage ) {
echo "Your HP is: ". $newhp . "<br / >";
echo "You took: " . $damage . " damage!";
}
}
?>
As you can see I have a variable with an integer (100) and a simple mt rand. What I want is that after I submit and get a $newhp (100 - the random number), that number to replace $hp. and the next time I submit the button I want the value of $damage to be subtracted from the previous action, so basically to save the $newhp as $hp.
If possible storing this value in a session variable that will be saved in the browser you use, for more information read here $_SESSION
<?php
session_start();
if(!isset($_SESSION["hp"]))
$_SESSION["hp"]=100;
if(isset($_POST['submit'])) {
$attack = $_POST['submit'];
$damage = mt_rand(5, 30);
$newhp = $_SESSION["hp"] - $damage;
if ($attkdamage = $_SESSION["hp"] - $damage ) {
echo "Your HP is: ". $newhp . "<br / >";
echo "You took: " . $damage . " damage!";
}
echo "<pre>previus hp " .$_SESSION["hp"];
$_SESSION["hp"]= $newhp;
echo "next hp " . $_SESSION["hp"]."</pre>";
}
?>

get rid of "dividing by zero" warning in sessions

This is a game of guessing number, I want the page to keep track of the wins, losses and totals and the %of winning by using sessions. I want to reset everything when I click "reset", but when I click reset everything equals to zero and there will be a warning saying "dividing by zero". How do I rearrange this php for it to only do the %calculation when the game is played but not when it's being reset?
<?php
// initialize wins and losses
if ($_SESSION['wins'] == "") {
$_SESSION['wins'] = 0;
}
if ($_SESSION['losses'] == "") {
$_SESSION['losses'] = 0;
}
echo "<h1>PHP SESSIONS</h1>";
if ($_GET['reset'] == "yes") {
$_SESSION['wins'] = 0;
$_SESSION['losses'] = 0;
$_SESSION['total'] = 0;
echo "<p>The game has been reset.</p>";
} else {
$randNum = rand(1,5);
echo "<p>The random number is <b>" . $randNum . "</b></p>";
if ($randNum == 3) {
echo "<p>The number equalled 3. YOU WIN!</p>";
$_SESSION['wins'] = $_SESSION['wins'] + 1;
} else {
echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
$_SESSION['losses'] = $_SESSION['losses'] + 1;
}
$_SESSION['total'] = $_SESSION['total'] + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
echo "<p>WINS: " . $_SESSION['wins'] . " | LOSSES: " . $_SESSION['losses'] . "| TOTAL: " . $_SESSION['total'] . "</p>";
echo "<p>Percentage of Winning: ". $_SESSION ['percentage'] . " % </p>"
?>
ROLL AGAIN :)
RESET :)
Move up the line in which you are dividing:
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
Put it inside the else bracket. Once I reformatted your code, it was easy to see the problem. I'd advise always using proper indenting. :)
When $_GET['reset'] == 'yes' is satisfied, you are setting $_SESSION['total'] = 0.
Then, you're dividing $_SESSION['wins'] by a 0 valued $_SESSION['total'] in the following line (which is executed regardless of the current state of $_SESSION['total']:
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
It's easier to see what's going on when the code is properly formatted. Have a look:
if ($_GET['reset'] == "yes") { // reset called
$_SESSION['wins'] = 0;
$_SESSION['losses'] = 0;
$_SESSION['total'] = 0; // set to zero(0)
echo "<p>The game has been reset.</p>";
} else {
$randNum = rand(1,5);
echo "<p>The random number is <b>" . $randNum . "</b></p>";
if ($randNum == 3) {
echo "<p>The number equalled 3. YOU WIN!</p>";
$_SESSION['wins'] = $_SESSION['wins'] + 1;
} else {
echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
$_SESSION['losses'] = $_SESSION['losses'] + 1;
}
$_SESSION['total'] = $_SESSION['total'] + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100; // chance that $_SESSION['total'] is zero(0)
So again, when you call the reset action, $_SESSION['total'] is given a value of int(0). Later in the script you then divide by that int(0), giving you the error in question. Make sense?
So you first need to ensure $_SESSION['total'] is greater than 0 before dividing by it.

cookie value not shown

This is my code:
<?php
$friendid = 10;
$friendname = "enco";
$max=count($_COOKIE['rooms']);
$i = $max + 1;
setcookie("rooms[$i]['type']", "1on1", time() + 3600, "/", ".mywebsite.com");
setcookie("rooms[$i]['name']", $friendname, time() + 3600, "/", ".mywebsite.com");
?>
The code below is in another page:
<?php
$max=count($_COOKIE['rooms']);
$k = 0;
for($k = 0; $k<$max; $k++) {
echo "Cookie 1 show: " . $_COOKIE['rooms'][$k]['type'] . "<br /><br />";
echo "Cookie 2 show: " . $_COOKIE['rooms'][$k]['name'] . "<br /><br />";
}
?>
But it does not work.
When I try to echo the cookies like I did in the example above, nothing appears.
My question is:
Are these structures correct:
setcookie("rooms[$i]['type']", "1on1", time() + 3600, "/", ".mywebsite.com");
setcookie("rooms[$i]['name']", $friendname, time() + 3600, "/", ".mywebsite.com");
in order to show these in another page (not in the same page where the cookies are written):
echo "Cookie 1 show: " . $_COOKIE['rooms'][$i]['type'] . "<br /><br />";
echo "Cookie 2 show: " . $_COOKIE['rooms'][$i]['name'] . "<br /><br />";
Thanks
PHP's superglobals _GET, _POST, _REQUEST, _COOKIE are all created at script startup, and then NEVER modified by PHP for the duration of the script's execution.
The cookie you create with setcookie() will therefore NOT be available in _COOKIE until the NEXT time you run this code.

php: getting a cookie value and adding by one

<?php
$cwd = getcwd();
$dir = 'onlytest';
// get file names from logos directory
$files = scandir($dir);
// count total files in directory
$totalFiles = count($files) - 1;
// loop through file names and output the images
$desc = $files;
echo 'Hello '.($_COOKIE['number']!='' ? $_COOKIE['number'] : '2'); // number of cookie!
for ($i = (10 * $_COOKIE['number']) - 18; $i <= 10 * $_COOKIE['number']; $i++)
{
$text = substr($desc[$i],0,20).'...';
$filepath = $dir . "/" . $files[$i];
echo '<img src="' . $filepath . '" target="_blank" width="25%" height="33%" />';
echo "<a href='$filepath' target='_blank'>$text</a>";
}
echo "</br>";
?>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething()
{
$.get("opentext.php");
return false;
}
</script>
'next 20 pictures'
My other file opentext.php is like this!
<?php
$number = ($_COOKIE['number'] + 1);
setcookie('number',$number,time() + (86400 * 1)); // 86400 = 1 day cookie
?>
I'm trying to take the value of cookie and add + 1, as you can see i want to take the 20 first pictures in folder and then i want to change the cookie when clicking the link below using javascript onclick function, it redirects me to the php file that adds + 1 to the cookie and gives the next 20 pictures, i have been doing this for hours and i just can't seem to get myself to find a solution.

Categories