I have a php script for a number-guessing game and an html script for a congratulation page. If the guess is correct, the game will end and the congratulation page will open. In the php, I have a variable $prize=1000-100 * $_POST['tries'], such that if the first guess is right, the player will win $1000; if the player has a second guess, the prize will be $100 less, and so on. This variable is saved in a hidden field in the php as $_POST['prize']. I hope the final prize can be printed in the congratulation page, but it didn’t work as I expected. Did I do anything wrong in the html? Thanks guys, Maria.
guess.php:
<?php
if(isset($_POST['number'])) {
$num = $_POST['number'];
} else {
$num = rand(1,10);
}
if(isset($_POST['prize'])) {
$prize =1000-100 * $_POST['tries'];
} else {
$prize = 900;
}
$tries=(isset($_POST['guess'])) ? $_POST['tries']+1: 0;
if (!isset($_POST['guess'])) {
$message="Welcome to the Guessing Game!";
} elseif (!is_numeric($_POST['guess'])) {
$message="You need to type in a number.";
} elseif ($_POST['guess']==$num) {
header("Location: Congrats.html");
exit;
} elseif ($_POST['guess']>$num) {
$message="Try a smaller number";
} else {
$message="Try a bigger number";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<p><strong>Guess number: </strong><?php echo $tries; ?></p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p><label for="guess">Type your guess here:</label><br/>
<input type="text" id="guess" name="guess" />
<input type="hidden" name="tries" value="<?php echo $tries; ?>"/><br/>
<input type="hidden" name="number" value="<?php echo $num; ?>"/><br/>
<input type="hidden" name="prize" value="<?php echo $prize; ?>"/>
</p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>
congrats.html:
<! DOCTYPE html>
<html>
<header>
<title>Congratulation!</title>
<body>Congratulation!<br/>
You Won <?php echo $_POST['prize']; ?> dollars!
</body>
</header>
</html>
it looks like your script will work, but you'll need to change congrats.html to congrats.php because html is static and php is dynamic. Also you might want to use sessions because anyone can inspect-element and change the value.
You just need to pass the value to the congrats page, using either GET request or a session. I'd recommend using a session so people cannot alter the prize value.
Just amend this part here:
} elseif ($_POST['guess']==$num) {
$_SESSION['prize'] = $_POST['prize'];
header("Location: Congrats.php");
exit;
}
Then (you need to change the congrats page to a php page to use the session btw to enable php)
Congrats.php
<! DOCTYPE html>
<html>
<header>
<title>Congratulation!</title>
<body>Congratulation!<br/>
You Won <?php echo $_SESSION['prize']; ?> dollars!
</body>
</header>
</html>
PS: Session will also require session_start() at the top of both documents.
Related
I want to learn how to keep value after a post request.
In my code, I have these variables:
myvar
myans
result
myvar is a random val between 0-5. I will get myans from my input if myans == myvar, then result will be true (else it will be false).
I see myvar before I submit my ans just for trying, but although I see the var when I send it, what I see it is sometimes false and sometimes true. What am I missing?
example.php:
<?php
session_start();
if (!isset($_COOKIE['result'])) {
setcookie("result","EMPTY");
}
setcookie("myvar",rand(0,5));
if (!empty($_POST)) {
if ($_POST['myans'] == $_COOKIE['myvar']) {
setcookie("result","TRUE");
}
else {
setcookie("result","FALSE");
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo $_COOKIE['myvar'] ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo $_COOKIE['result'] ?>
</form>
</body>
</html>
The problem you were having was caused by your random number generator making creating a new number before comparing to the original. I made some changes to only set "myvar" if it's empty. this will only set it once, but at least you can see your code working as intended. I recommend you plan out what exactly what functionality you want before adding to it.
I also switched you out from the "$_COOKIE" var to "$_SESSION" vars. They are hidden from the client, and by php default last about 24 minutes if not refreshed. I don't know what you plan on using this for, but using cookies allows the end user to manipulate that info. If this is not a concern for you, by all means just uncomment the "setcookie()" lines.
<?php
session_start();
if (!isset($_SESSION['result'])) {
//setcookie("result","EMPTY");
$_SESSION["result"] = "EMPTY";
}
//setcookie("myvar",rand(0,5));
if(empty($_SESSION["myvar"])){
$_SESSION["myvar"] = rand(0,5);
}
//
if (!empty($_POST)) {
if ($_POST['myans'] == $_SESSION['myvar']) {
//setcookie("result","TRUE");
$_SESSION["result"] = "TRUE";
} else {
//setcookie("result","FALSE");
$_SESSION["result"] = "FALSE";
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo isset($_SESSION['myvar']) ? $_SESSION['myvar'] : ""; ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo isset($_SESSION['result']) ? $_SESSION['result'] : ""; ?>
</form>
</body>
</html>
The website generates the random number from 1 to 100 when accessing the first page(page1.php). And the user will guess the number.
The first page contains
- a text box for accepting a
number from the user, and a submit button.
The second page(page2.php) will be returned to the user if the guess number is too high or too low. And the page shows a message telling the user "Too High" or "Too Low". The page also contains
a button(retry button) that allows the user to go back to the first page(page1.php) to re-enter a new number
a button that allows the user to quit the game.
The third page(page3.php) is returned to the user if the guess is correct. The page displays "Correct", the random number, and the count of tries.
And I have this index.php which is heart for all the pages. And here is the code.
index.php
<?php
$name = '';
$inputnumber = '';
$random = 33; //this is just an assumption to keep it simple
$message = '';
$guesscount = '';
if (isset($_POST['action'])) {
$action = $_POST['action'];
}
if ($action === 'guess') {
$guesscount = $_POST['$guesscount'];
$inputnumber = $_POST['$inputnumber'];
if ($inputnumber == $random) {
$message = "Correct!";
include 'page3.php';
}
if ($inputnumber > $random) {
$message = "Too High";
include 'page2.php';
}
if ($inputnumber < $random) {
$message = "Too Low";
include 'page2.php';
}
}
if ($action === 'retry') {
include 'page1.php';
}
page1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Number Guess: <input type="text" name="$inputnumber" value="<?php if(isset($inputnumber)==1){
echo $inputnumber;}else echo ""; ?>" /><br>
<input type="submit" name="action" value="guess" />
<hr>
Guess Count: <?php echo $guesscount; ?>
</form>
</body>
</html>
page2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
<input type="hidden" name="$guesscount" value="<?php echo $guesscount;?>"/><br>
<input type="submit" name="action" value="retry" />
<hr>
Guess Count: <?php echo $guesscount;?>
</form>
</body>
</html>
page3.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
Number of Tries: <?php echo $guesscount; ?>
<input type="submit" name="action" value="ok" />
</form>
</body>
</html>
page1.php is the page to load first.
Challenge I have faced is, I couldn't keep the $guesscount stable always. It keeps resetting on me. I have tried session but couldn't resolve it.Please help resolving it.
Thanks in advance.
I don't know why but my gut feeling tells me that the reason why the session is not working for you on other pages is because you do not initiate it ??
So what you have to do is:
index.php
<?php
session_start();
$_SESSION['myVariable'] = 'myVariable';
?>
page1.php
<?php
session_start();
$mySessionVar = $_SESSION['myVariable'];
var_dump($mySessionVar); // <- this should print myVariable
?>
You may get an error saying that $_SESSION is null or not set and to prevent that you can just enclose $_SESSION inside and isset method
if(isset($_SESSION['myVariable']) && $_SESSION['myVariable'] != null) {
$mySessionVar = $_SESSION['myVariable'[;
}
I've looked through multiple web articles and stackoverflow answers, however I cannot find the bug in my code. Maybe I've been looking at it too long.
Basically I'm just setting up a simple login for a demonstration, yes I know its inject-able and outdated, this doesn't matter. Basically I'm using a login with sessions and then redirecting the user to secure content when they're logged in. I've also created a script that checks for the session variables, to see if the user is logged in or not. Basically, I'm beating a dead horse and I don't know why this isn't working, could someone please help?
index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome, please log in</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<?PHP require_once"scripts/mysql_connect.php"; // Establish a database connection ?>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<?PHP
echo "<form method='post' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' value='Log In'>
</form>"
?>
</div>
</body>
</html>
checklogin.php:
<!doctype html>
<html>
<head>
<title>Checking login...</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<?php
require_once"scripts/mysql_connect.php";
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
$sql = "SQL";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$active = $row['active'];
$count = mysql_num_rows($result);
// If result matched, table row must be 1 row.
if($count == 1) {
$_SESSION["login"] = "OK";
$_SESSION["aEmail"] = $aEmail;
echo "<h1>Log in successfull!</h1>
<hr><br />
Your details checked out! Redirecting you now...";
// Wait 1 seconds then redirect to the secure content.
header("Location: http://www.website.com/secure_content.php");
} else {
echo "<h1>Log in unsuccessfull!</h1>
<hr><br />
Sorry. It seems your log in detials were incorrect. Please go back and try again.";
// Wait 2 seconds then redirect back to the log in page.
header("Location: http://www.website.com/index.php");
}
exit;
?>
</div>
</body>
</html>
loginstatus.php:
<?php session_start();
if(!(isset($_SESSION["login"]) && $_SESSION["login"] == "OK")) {
header("Location: http://www.website.com/index.php");
exit;
}
?>
Thanks for any help!
In checklogin.php and index.php you need to start the session. Add the following code before <!doctype html>
Add this code:
<?php session_start(); ?>
You forgot to put that line in this file because you are creating a new session during the checks in the database.
Looks like you haven't started the session in the first place. On the top of your page please write the following code:
<?php session_start(); ?>
Now, secondly, I'd suggest you to write your HTML and PHP separately instead of writing your HTML for the form within the echo.
Also, it's better if you add a name to your submit button.
Let me show a sample below.
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<form method='POST' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' name='submit' value='Log In'>
</form>
Now, in your checklogin.php. you should place an isset condition and see if you're getting any POST request.
Try this:
<?php
require_once"scripts/mysql_connect.php";
if (isset($_POST['submit']) { // Add this condition
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
/* Other code */
if($count == 1) {
/* Other code */
} else {
/* Other code */
}
}
Hope this helps.
I'am new to php and I have no idea why my code in php is always echoing FALSE.
I do not want to use another hidden input like:
<input type="hidden" name="storeRandVal" value="<?php echo $randomValue; ?>
to store my generated random value, and then checking if the entered value in input is equal with value that was generated and entered to hidden input. Is there any way around to do it in php also without involving cookies?
Here is my code:
<?php
$buttonPost = $_POST['button_post'];
$enteredValue = htmlspecialchars(trim($_POST['test_input_p']));
$randomValue = rand(1,100);
if(isset($buttonPost))
{
if($randomValue == $enteredValue)
{
echo "TRUE";
}
elseif($randomValue != $enteredValue)
{
echo "FALSE";
}
else
{
echo "Er__!";
}
}
?>
<html>
<head>
<meta></meta>
</head>
<body>
<form action="" method="post">
<fieldset>
<label for="test_input" id="label_input">Enter value: <?php echo $randomValue; ?></label>
<input id="test_input" name="test_input_p">
<input type="submit" id="ibutton_send" name="button_post" value="Send">
</fieldset>
</form>
</body>
</html>
Why not store the random value in a session? Re-set the session only when a form is not submitted (eg; when a user comes to this page from a different page)
As #Fred commented, you have to include the hidden input. By its nature, PHP's rand() function gives you a different answer every time you load the page.
You'll need to compare the $_POST['test_input_p'] and $_POST['storeRandVal'] values in order to confirm that the user entered the correct values.
Here's what you can do:
Store the hidden value in a variable then compare it with that value.
(Unless you will be using this for more than 2 pages, sessions are not needed, not for this since you're using your entire code inside the same page.)
<?php
$buttonPost = $_POST['button_post'];
$enteredValue = htmlspecialchars(trim($_POST['test_input_p']));
$hidden = $_POST['storeRandVal'];
$randomValue = rand(1,100);
if(isset($buttonPost))
{
if($enteredValue == $hidden)
{
echo "TRUE";
}
elseif($randomValue != $hidden)
{
echo "FALSE";
}
else
{
echo "Er__!";
}
}
?>
<html>
<head>
<meta></meta>
</head>
<body>
<form action="" method="post">
<input type="hidden" name="storeRandVal" value="<?php echo $randomValue; ?>">
<fieldset>
<label for="test_input" id="label_input">Enter value: <?php echo $randomValue; ?></label>
<input id="test_input" name="test_input_p">
<input type="submit" id="ibutton_send" name="button_post" value="Send"></input>
</fieldset>
</form>
</body>
</html>
I am currently learning the most basic PHP ever. I have 5 files.
index.php:
<html>
<head>
<title>Budget Calcule</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Put in your: - </h2>
<form action="functions.php" method="post">
<h3>Income</h3>
<label>Salary: <input name="salary" type="text" /></label><br />
<h3>Outgoings</h3>
<label>Living: <input name="living" type="text" /></label><br />
<label>Insurance: <input name="insurance" type="text" /></label><br />
<label>Communication: <input name="communication" type="text" /></label><br />
<label>Loan: <input name="loan" type="text" /></label><br />
<label>Food & Drink: <input name="foodAndDrink" type="text" /></label><br />
<label>Entertaintment / Shopping: <input name="entertainmentOrShopping" type="text" /></label><br />
<label>Transport: <input name="transport" type="text" /></label><br />
<label>Other: <input name="other" type="text" /></label><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
this is my functions.php:
<?php
include('variables.php');
if(!($_POST['Submit'])){
if(isset($_POST['salary'])){
header('Location: output.php');
return $_POST['lon'];
}else{
echo "All fields are required";
}
}
?>
this is my variables.php:
<?php
$salary= $_POST['salary'];
$living= $_POST['living'];
$insurance= $_POST['insurance'];
$communication = $_POST['communication'];
$loan = $_POST['loan'];
$food = $_POST['food'];
$entertaintmentOrShopping = $_POST['entertaintmentOrShopping'];
$transport = $_POST['transport'];
$other= $_POST['other'];
?>
this is my output.php file:
<?php
include('outputFunction.php');
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
and last but not least, this is my outputFunction.php file:
<?php
include('variables.php');
function myText(){
echo "Your salary per month is: " . $_POST['salary'];
}
?>
Now you're thinking "why have he split up his code in different files?" Well first of all, I split the variables from functions.php because I wanted outputFunctions.php to get the variables from variables.php so i could echo my `$_POST['salary']; . The function myText(); outputs the text just fine, but it doesnt output the $_POST['salary'];.
I do not know why it doesnt work, I just wonder if you could be my extra eyes and see if I've done some mistake.
PS! Don't down vote my question just because you think it's stupid. I am having problem with this issue and been working on it for hours without advancing anywhere.
A few things:
You don't need to include a variables.php file. The variables you're accessing are global and you're just creating duplicates that aren't being used. They also go away after the page changes since you're re-declaring them each page load.
You are also trying to call a variable that doesn't exist when you reference $_POST['lon'] instead of 'loan'.
And finally to actually answer your question:
Your myText() function is referencing a variable that is not there anymore.
You need to merge functions.php and outputFunction.php and output.php into one file so the variables aren't lost and all the processing is done without opening a new file each time. I can see your original concept for separated files but an output file is going to be the file to process the input data from the form.
Now in your newly merged output.php, you should have something resembling this:
<html>
<head>
<title>Output</title>
</head>
<body>
<?php
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
echo "Your salary per month is: " . $_POST['salary'];
}
} else {
echo "All fields required.";
}
?>
</body>
</html>
This means only two files - your form page and this page.
A few more tips:
If you want to check if the form was submitted, it has look something like this:
if(isset($_POST['Submit'])){ ... }
Also, you should add a name="" attribute to your submit-Button:
<input type="submit" name="Submit" value="Submit" />
And what is the variables.php for? You don't use any of those variables.
When you redirect the user via header() the data that is stored in the $_POST array gets lost.
You could directly redirect to ouput.php
<form action="output.php" method="post">
And do something like this:
<?php
include('outputFunction.php');
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
<?php
} else {
echo "All field required";
}
}
?>
By the way you can always check what your $_POST contains with print_r($_POST);
This can be very useful for debugging.