What I'm doing wrong? "session start" - php

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.

Related

PHP condition fails while using Session

I made a card game with PHP but there I'm facing some issue.
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
I'm getting an input from the user. The problem is, when the game loads at first, and the user enters an input and clicks submit, the game won't work. The condition ($_SESSION["bet"] != NULL) is giving true and bankroll is not defined.
Is there a way I can set this up properly? Is there some PHP method that can initialize the variable once then only works it on session start, then the rest of the code can take care of how that variable gets updated? The bankroll variable gets initialized if the user clicks submit without anything in it right now, so the game still works but it starts improperly.
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
The bankroll variable gets initialized to 1000 every time user submits a NULL input. I want to change this.
More code... Updating...
session_start();
$_SESSION["bet"] = $_POST["bet"];
echo "<br>";
//print_r($_SESSION);
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
else if ($_SESSION["bet"] > 1000 || $_SESSION["bet"] < 0)
{
echo " Please enter between 0 and 1000.";
}
else if ($_SESSION["bet"] > $_SESSION["bankroll"])
{
echo "You can't enter more than what you have.";
}
else
{
$deck = array();
for($x = 0; $x < 54; $x++) {
$deck[$x] = $x;
}
shuffle($deck);
//Then more stuff. This one for example...
if(($houseSuits[0] == -100) || ($houseSuits[1] == -100) || ($houseSuits[2] == -100) || ($houseSuits[3] == -100))
{
echo "<br>";
echo '<center> PLAYER WINS! (HOUSE HAS JOKER) </center>';
echo "<br>";
$_SESSION["bankroll"] = $_SESSION["bankroll"] + $_SESSION["bet"]; //THESE NEED TO BE ADDRESSED.
}
I JUST WANT TO FIND A WAY TO INITIALIZE BANKROLL TO 1000 AT START. THE WAY I'M DOING IT IS BY SUBMITTING A NULL VALUE THEN ASSUMING USER NEVER SUBMITS NULL VALUE AGAIN.
I WOULD LIKE BANKROLL TO BE INITIALIZED TO 1000, THEN FOR THE GAME TO TAKE CARE OF HOW BANKROLL GETS UPDATED.
I FOUND A WAY TO DO IT BUT IT'S NOT A PROPER WAY SO THAT'S WHY I'M ASKING FOR HELP.
THANK YOU.
Ok try this.
So if the bankroll is not set, then set it, once it's set it wont get set again because it's set.
Then any conditions after are fine.
session_start();
// Initialise bankroll if not already
if (!isset($_SESSION['bankroll'])) {
$_SESSION['bankroll'] = 1000;
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
}
$_SESSION['bet'] = $_POST['bet'];
if ($_SESSION['bet'] != NULL) {
echo "Your bet is: " . $_SESSION['bet'] . "<br>";
}
if ($_SESSION['bet'] > 1000 || $_SESSION['bet'] < 0) {
echo " Please enter between 0 and 1000.";
} elseif ($_SESSION['bet'] > $_SESSION['bankroll']) {
echo "You can't enter more than what you have.";
} else {
// Your card game stuff
}
Notes: you may have issues with using session as it'll store their bet wherever they are, so issuing a bet sets the session, then navigate elsewhere and come back and their bet will still be as before. Maybe this doesn't matter.
You also might not want to check if the bet is null, more perhaps empty or whatever. Test either way to be sure.

Number Guessing game PHP not functoning

I am trying to write a php game that raises an random ($secretNumber) number between 1 and 100, prints it to the screen, prints a form with buttons for the user to select either 'higher' 'lower' or 'correct'. Upon a button press, the outside values are altered accordingly and the computer raises another random number between the lowest and highest values. This continues until the user select correct and the game resets.
I am using a session to ensure that the values don't reset each time a button is clicked.
My problem is that the $secretNumber resets a couple of times before the $_SESSION locks it in.
Also the $randomGuess doesn't seem to lock in before updating.
Any suggestions as to why this isn't working?
<?php session_start() ?>
<?php
$low = 1;
$high = 100;
//create a function to hold a random number, between 1 and 100 and save it
//to a session variable.
secretNumber();
function secretNumber(){ //********** secretNumber() **********
global $randomGuess;
if(!isset($_SESSION["secretNumber"])){
$secretNumber = rand(1,100);
$_SESSION['secretNumber'] = $secretNumber;
} else {
$secretNumber = $_SESSION["secretNumber"];
echo($_SESSION['secretNumber']);
}
echo 'Secret number is '.$secretNumber;
echo ' <br/> ';
} //********** end secretNumber() ***********
//create a function to create a random guess as to the value of the
//first random number
randomGuess();
function randomGuess() { //********** randomGuess() **********
global $randomGuess;
global $low;
global $high;
if (isset($_SESSION['low'])){
$low = $_SESSION['low'];
}
if (isset($_SESSION['high'])){
$high = $_SESSION['high'];
}
$randomGuess = round($high-(($high-$low)/2));
echo 'Random guess is '.$randomGuess;
echo "<br/>";
$_SESSION['randomGuess'] = $randomGuess;
} // ********** end randomGuess() **********
//create a function to provide a response as to whether the guess is low,
//high or correct, and adjust the limits of the random guess accordingly.
checkGuess();
function checkGuess() { // ********** checkGuess() **********
global $low;
global $high;
global $randomGuess;
// form to show a 'high' button, a 'low' button and a 'correct' button
// Correct button needs to reset $_SESSION["secretNumber"], and start
// process over.
print <<<HERE
<div>
<br/><br/><br/>
<form method = "post" action = "" style="width:35%;
padding-left:35%">
<fieldset>
<button type = "submit" value="high" name ="high">Too High</button> <br/><br/>
<button type = "submit" value="low" name = "low">Too Low</button> <br/><br/>
<button type = "submit" value="correct" name = "correct">Correct</button> <br/><br/>
</fieldset>
</form>
</div>
HERE;
if (isset($_POST['low'])) {
echo "low <br/>";
echo "randomGuess = ".$randomGuess. "<br/>";
unset($_SESSION["low"]);
$low = $randomGuess;
$_SESSION['low'] = $low;
unset($_SESSION["randomNumber"]);
}
if (isset($_POST['high'])){
echo "high <br/>";
echo "randomGuess = ".$randomGuess. "<br/>";
unset($_SESSION["high"]);
$high = $randomGuess;
$_SESSION['high'] = $high;
unset($_SESSION["randomNumber"]);
}
} // ********** end checkGuess() **********
if (isset($_POST['correct'])){
print <<<HERE
<h2>Yes I guessed the correct secret number. Your secret is out</h2>
HERE;
unset($_SESSION["secretNumber"]);// unset the random number as the guess was correct.
unset($_SESSION["high"]);
unset($_SESSION["low"]);
}//end if
echo "low =".$low."<br/>";
echo "high =".$high." <br/>";
?>
Try to check if $secretNumber is same as session.
var_dump($secretNumber);
if($secretNumber != $_SESSION["secretNumber"]) {
echo "Restart is here";
}
Test it after every function and then you can see what is problem.

How to generate auto redirect of php page that takes one input variable to same page php with another input variable?

So I have a set of values let's say 90, 100, 110, 120, 130, 140, 150 The first time I load a php page, the value 90 is the main input variable and the page displays the details about 90.
Now in 60 seconds the page redirects to the same page but with the input variable as 100.
This continues on and when 150-related stuff is also displayed, it goes back to 90-related stuff.
How can this be achieved??
<?php
mysql_connect("localhost", "root", "qwerty") or die(mysql_error());
mysql_select_db("ups_status") or die(mysql_error());
$data = $_POST['input'] ;// <!--This is where the input should change after every redirect-->
$order = "SELECT * FROM ups_status1 WHERE (Ipaddress LIKE '%".$data."%')";
$results = mysql_query($order) or die('Invalid query: ' .mysql_error());
// <!--And then I will echo the results-->
?>
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = array(90, 100, 110, 120, 130, 140, 150);
}
$i = isset($_SESSION['i']) ? $_SESSION['i'] : 0;
echo "Variable is ".$_SESSION['counter'][$i];
/* Put your code here*/
mysql_connect("localhost", "root", "qwerty") or die(mysql_error());
mysql_select_db("ups_status") or die(mysql_error());
$data = $_SESSION['counter'][$i] ;// <!--This is where the input should change after every redirect-->
$order = "SELECT * FROM ups_status1 WHERE (Ipaddress LIKE '%".$data."%')";
$results = mysql_query($order) or die('Invalid query: ' .mysql_error());
/*********************/
if ( $i == count($_SESSION['counter']) - 1) {
$next = 0;
} else {
$next = $i + 1;
}
$_SESSION['i'] = $next;
header( "refresh:5;url=refresh.php" );
echo '<br>You\'ll be redirected in about 5 secs. If not, click here.';
?>
If always increase 10. Try this.
page.php
<?php
$id = isset($_GET['id']) ? $_GET['id'] : 90;
echo $id; // your code HERE
if($id < 150) {
$nextId = $id +10;
header("Refresh:60;url=page.php?id=" . $nextId);
} else {
header("Refresh:60;url=page.php");
}
As you can see you can see in the access log every refresh (I did the test every 5 sec)
Don't use Location header as it will prevent you from showing output first. Use Refresh instead since you're refreshing the same page..
you can store the variable in a session or just simply pass as the page refresh.
Here the php page is named page.php and it will refresh every 5 seconds and passess the variable to itself. Once it reloaded it will simply increment the pass variable or reset it to 90 when it's > 150.
<?php
$data = isset($_GET['input']) ? $_GET['input'] : 90;
echo "Value is ".$data;
$data = ($input >= 150) ? 90: $data;
header( "refresh:5;url=page.php?input=".($data+10));
?>
To try: Copy this code to a file named page.php and open in browser.
update:
assuming your code example works. you can just modify the line below
$data = $_POST['input']
to
$data = isset($_GET['input']) ? $_GET['input'] : 90;
then add a refresh header after you've done your output.
$data = ($data >= 150) ? 90: $data;
header( "refresh:60;url=page.php?input=".$data );

Why does this undefined error occur when storing the first number to a $_SESSION[] variable?

I'm making a mini shopping cart for my project. Im storing the number of items chosen by the user, I don't understand that when i add one to my session variable I always get this error on the first go
Undefined index: cart_1 in D:\wamp\www\MiniCart\cart.php on line 100
And when I add again or refresh the same page it works fine. Why could this error be coming up? I removed the +=1 from the statement and it worked fine, apparently there is no syntax error too.
Cart.php
<!DOCTYPE>
<html>
<head></head>
<body>
<?php
session_start();
//The page where to jump to after adding/editing cart.
$page = 'mini_cart_index.php';
$link = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
echo "Error:".mysqli_connect_error();
echo "<br/>";
} else {
echo "Connected to SQL<br/>";
}
//==================================================
if(isset($_GET['add']))
{
$obt=$_GET['add'];
$quantity_limit = 'SELECT id,quantity FROM products WHERE id='.mysqli_real_escape_string($link,(int)$_GET['add']);
$quantity = mysqli_query($link,$quantity_limit);
while($quantity_row=mysqli_fetch_assoc($quantity))
{
if($quantity_row['quantity']!=$_SESSION['cart_'.$_GET['add']])
{
$_SESSION['cart_'.$_GET['add']]+='1';
}
}
/*
echo 'id='.$obt.' '.'next<br/>';
echo 'Now storing info into session variable and adding one<br/>';
echo $_SESSION['cart_'.$_GET['add']];
echo '<br/>';
echo 'info stored<br/>';
*/
}
//***************************************************
function products()
{
GLOBAL $link;
$get ="SELECT id,name,description,price FROM products
WHERE quantity > 0 ORDER by id ASC";
if($result=mysqli_query($link,$get))
{
echo "Data Selected to be displayed<br/>";
} else {
echo "Error:".mysqli_error($link);
}
if(mysqli_num_rows($result)==0)
{
echo "There are no products to display!<br/>";
} else {
while($get_row=mysqli_fetch_assoc($result))
{
echo '<hr/><br/>';
echo 'displaying data from database<br/>';
echo '==================================';
echo '<p>'.$get_row['name'].'<br/>'.
$get_row['description'].'<br/>'.
number_format($get_row['price'],2).
' Add'.'</p>';
echo '<hr/><br/>';
}
}
}
echo 'outside'.$_SESSION['cart_1'];
?>
</body>
</html>
Mini_cart_index.php
<?php require 'cart.php';?>
<!DOCTYPE>
<html>
<head>
</head>
<body>
<?php products() ?>
</body>
</html>
That code is filled with SQL injection vulnerabilities, you should use PDO and prepare your statements.
PHP is warning you because it has to read the current value and add to it, but the first time you try to access it doesn't exist.
You could suppress the warning with:
#$_SESSION['cart_'.$_GET['add']]+='1';
A better way to do it though would be checking if it exists first
$name = 'cart_'.$_GET['add'];
if(isset($_SESSION[$name]) {
$_SESSION[$name] = 1;
} else {
$_SESSION[$name] += 1;
}
The problem is caused by the fact that...
$var['abc'] += 1
...is the same as
$var['abc'] = $var['abc'] + 1
So if you've got a clean session and $var['abc'] doesn't exist, you're going to get a warning because you're trying to read a non-existant value in order to add 1 to it.
While it's true that 0 + 1 = 1
...what's actually happening here is undefined + 1 = 1 with a warning.
As other answers have mentioned - to fix the issue, you can explicitly check that the array index exists before trying to increment it.
I'd do that with the ternary operator like this:
$key = 'card_' . $_GET['add'];
$_SESSION[$key] = (isset($_SESSION[$key]) ? $_SESSION[$key] : 0) + 1;
This is effectively saying
$val = ($val if it exists, otherwise 0) + 1;
Change your if statement to check if it's empty too:
if (!isset($_SESSION['cart_'.$_GET['add']])) {
$_SESSION['cart_'.$_GET['add']] = 1;
} elseif ($quantity_row['quantity'] != $_SESSION['cart_'.$_GET['add']]) {
$_SESSION['cart_'.$_GET['add']] += 1;
}

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