My random number generates on page load, but seems to reset when the user clicks the "Guess" button. I still have a lot of building to go with this, but at the end I want the user to be able to make multiple guesses to guess the random number. I want it to generate when the page first comes up and stay the same until correctly guessed. I'm not sure what I'm doing wrong and just starting this program. If you answer, please also explain, as I'm trying to learn what I'm doing. Thank you!
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>PHP Homework 2</title>
<link rel="stylesheet" href="styles/styles.css">
</head>
<body>
<section id="main">
<h1>Play the Guessing Game!</h1>
<section id="left">
<h2>Take a Guess!</h2>
<form action="mine.php" method="post">
<div id="guessBox">
<label id="guessLB">Your Guess:</label>
<input id="guessTB" class="num" type="number" name="guessTB" max="1000" min="1">
</input>
</div>
<input type="submit" id="guessButton" name="guessBTN" value="Guess" />
</form>
</section>
<section id="right">
<h2>Game Stats</h2>
<?php
if(isset($_POST['guessTB']))
{
$randomNum = $_POST['guessTB'];
}
else
{
$randomNum = rand(1,100);
}
echo "<p>Random Number: $randomNum</p>";
?>
</section>
</section>
</body>
</html>
UPDATE: My HTML has remained the same, and I'm posting my new PHP code. But I used a session and wrote some more. However, I've come across two problems:
1) If I refresh the page, I get an error that says that the first instance of $randomNum below the session_start(); is unidentified.
2) It seems that it remembers my very last guess in the game. If I close out the page and reopen it, I immediately get one of the messages that my guess was too high or too low, even before making a guess. Any advice is appreciated!
<?php
session_start();
$randomNum = $_SESSION['randomNum'];
$guess = $_POST['guessTB'];
if(!isset($_SESSION['randomNum']))
{
$_SESSION['randomNum'] = rand(1,1000);
}
else
{
if($guess < $randomNum)
{
echo "<p>Your Guess is Too Low! Try Again!</p>";
}
else if($guess > $randomNum)
{
echo "<p>Your Guess is Too High! Try Again!</p>";
}
else
{
echo "<p>You Won!</p>";
$_SESSION = array();
session_destroy();
}
}
echo "<p>Guess: $guess</p>";
echo "<p>Random Number: $randomNum</p>";
?>
What you can do is use sessions. On every load check if you set it in the session and if it's not set, generate new number and set it, then check what the user input and compare the two numbers. This could also be done with cookies. Another thing you can do is use js. On load store the generated number in some js variable and don't use a form. On button click get the value of the input field and compare with the one you store in the variable.
Related
I've spent a lot of time today researching this site for my solution but I have had no luck. I'm currently trying to learn php and working on my second project. I can only use PHP. I originally had my delete session and redirect in a separate logout.php file. This was working but then I found out that I can't do this. I've been instructed that I need to "clear the login, delete the session, and redirect back to the login page" and do this within an isPostBack in the results.php file. After a lot of research today I thought I was understanding how to do this but I can't get it to work. Hoping I can get some help.
<?php
session_start();
//require_once('cookies.php');
$isPostBack = filter_input(INPUT_GET, 'submit');
//this is where I need to do the isPostBack for user clicking "logout".
if ($isPostBack) {
// clear ALL session data from memory
// clean up the session and remove the session ID.
// redirect to index.php
endSession();
session_destroy();
header("Location: index.php");
} else {
// user did not click logout doNothing();
}
?>
<html lang="en">
<head>
<title>Results</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<form action="results.php">
<input type="submit" id="submit" name="submit" value="Logout" />
</form>
<section>
<?php
foreach($_SESSION['answers'] as $answer){
echo "<p>$answer</p>";
}
?>
</section>
</body>
Try to provide name attribute
<input type="submit" id="submit" value="Logout" name="logout"/>
and use only logout variable in place of submit or provide two different fields
$isPostBack = filter_input(INPUT_GET, 'submit');
$isPostBack = filter_input(INPUT_GET, 'logout');
I seem to have found my solution. I needed to give the isPostBack variable a name that matched the name given to the logout button. I also needed to include !==NULL after the isPostBack. I changed endSession(); to $_SESSION = array(); According to my research, endSession(); "removes all session variables". It seems to be working as it should now. Here is my edited code.
<?php
session_start();
$isPostBack = filter_input(INPUT_GET, 'submit')!==NUll;
//this is where I need to do the isPostBack for user clicking "logout".
if ($isPostBack) {
// clear ALL session data from memory
// clean up the session and remove the session ID.
// redirect to index.php
$_SESSION = array();
session_destroy();
header("Location: index.php");
} else {
// user did not click logout doNothing();
}
?>
<html lang="en">
<head>
<title>Results</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<form action="results.php">
<input type="submit" id="submit" name="submit" value="Logout" />
</form>
<section>
<?php
foreach($_SESSION['answers'] as $answer){
echo "<p> $answer</p>";
}
?>
</section>
</body>
If you need to remove se particular session values you can use unset()
unset ($_SESSION['userid'])
I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what. I've never used PHP with mySQL before so I'm not too sure how it all works. Any help with an explanation of how it's working would be appreciated.
Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.
(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option e.g. the list of options will be - '4', 'blank', '5'... etc)
<!DOCTYPE html>
<?php
include 'connect.php';
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user- scalable=no"/>
</head>
<title>Test Sign Up</title>
<body>
<header>
<h1>Test Sign Up</h1>
</header>
<div class="contactform">
<form action="testinsert.php" method ="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter
your name here" required>
<label for="testsentence">Test Sentence:</label>
<input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>
<label for="course">Course:</label>
<select id="course" name="course">
<?php
$query = "SELECT CourseID FROM Course";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo "<option>" . $row['CourseID'] . "<option>";
}
mysqli_close($conn);
?>
</select>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<p></p>
View Courses
<p></p>
Return to home page
</body>
</html>
Testinsert.php -
<?php
include 'connect.php';
$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';
$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";
if (mysqli_query($conn, $sql)) {
echo "<p></p>New record added successfully";
echo '<p></p>Return to home page';
} else {
echo "<p></p>Error adding record";
echo '<p></p>Return to home page';
}
mysql_close($conn);
?>
You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag. / needs to be written into the second option tag like this:
while ($row = mysqli_fetch_array($result)) {
echo "<option>{$row['CourseID']}</option>";
}
The option tags still render even if you don't properly close them. In this case, the error presents itself by generating twice the desired tags.
I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc
In fact, because $result is iterable, you can write:
foreach ($result as $row) {
echo "<option>{$row['CourseID']}</option>";
}
About using extract($_POST)...
I have never once found a good reason to use extract in one of my scripts. Not once. Furthermore, the php manual has a specific Warning stating:
Warning
Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).
There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data. DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.
Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page
Specifically, this is how you access the expected superglobal data:
$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];
You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.
You must use a prepared statement with placeholders and bound variables on your INSERT query. There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.
Make sure you added extract($_POST) (or something similar) in your PHP code!
You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.
I have the following problem and feel that the solution is simple but after 8 hours of trying and searching, I am giving up.
I have this simple page:
<?php
// Start the session
$lifetime=600;
session_set_cookie_params($lifetime);
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Change the Yoda!</title>
</head>
<body>
<?php
// Set session variables
$_SESSION["post-data"] = $_POST;
?>
<form action="yoda_is.php" method="POST">
YODA IS: <input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
Upon submit, it sends me to this page:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Who is Yoda?</title>
</head>
<body>
<?php
// Echo session variables that were set on previous page
echo "YODA IS " . $_SESSION['post-data'] = $_POST['name'];
?>!
</body>
</html>
The value that you enter in the first page, is successfully being displayed on the second page.
However, once I close the browser window and revisit the second page, the value is no longer there and it returns an error.
My question is simple, what am I doing wrong / do I need to do in order for the value that I entered on the first page, to be there after I revisit the second page?
Thank you so much for your help and suggestions, in advanced.
KR
MD
On your first page remove this:
// Set session variables
$_SESSION["post-data"] = $_POST;
On your second page use this instead:
// If the user filled out the form, set our session variable to the new value
if(isset($_POST['name']))
{
$_SESSION['post-data'] = $_POST['name'];
}
// Echo session variable set above
echo "YODA IS " . $_SESSION['post-data'] . "!";
I'm working on a database-driven quiz that lets users select a series of answers, then submit the results via a form. It was working great, when it suddenly blew up, and I haven't been able to find the problem.
So before I get into the more complex stuff, I'd like to go back to square one and just make something simple work - like passing a hidden value to another page that echoes that value.
Here's the code for my first page # mysite/form.php:
<html>
<head>
</head>
<body>
<!-- g1/form.php -->
<div id="quiz" rel="key">
<form action="form2.php" method="post" id="quiz">
<input type="hidden" name="PreviousURL" id="url" />
<input type="submit" value="Submit Quiz" />
</form>
</div><!-- quiz-container -->
</body>
</html>
And here's the code for the second page:
<html>
<head>
</head>
<body>
<?php ini_set('display_errors', 1);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo $_POST['PreviousURL'];
}
echo 'XXX';
?>
</body>
</html>
I also tried moving the closing bracket, like this:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
}
echo $_POST['PreviousURL'];
echo 'XXX';
In both cases, when I click the submit button and am forwarded to form2.php, I see "XXX," but there's no value for $_POST['PreviousURL'].
I must have accidentally deleted or modified something, because it seems so simple, and it worked fine before. Can anyone tell me what the problem is?
there isn't a value for the hidden input.
In your form script you have missed out the value="" from the hidden input. This is the reason why nothing is displaying on the second page.
In my security course teacher gave us a challenge to do so that we can practice with xss on a dummy website.
This website is composed by 2 php pages.
The first is called xss.php, and this is the code
<html>
<head>
<title>Equations</title>
</head>
<body>
<center>
<?php
if (isset($_POST['result'])){
$result = $_POST['result'];
if (intval($result) == 1){
echo "<h1>Ok, you are able to solve simple equations </h1><br>";
}
if (intval($result) == 0) {
header("Location: error.php?error=Type numbers!");
}
if (intval($result) != 1){
echo "<h1>Wrong result! Try again.</h1>";
}
}
else { ?>
<h1>Can you solve equations?</h1>
<h2>x^2 - 2*x + 1</h2>
<form method=POST action="xss.php">
<table>
<tr> <td>x:</td> <td><input type=text name=result></td> </tr>
</table>
<input type=submit value=Submit />
</form>
</center>
</body>
</html>
<?php }
?>
the second is error.php, and it's this:
<html>
<head>
<title>Error</title>
</head>
<body>
<center>
<h1>Error: <?php echo $_GET["error"]; ?></h1>
<center>
</body>
</html>
the request is to redirect someone to another website (I'll call it "http://whatever.com/" ). When I start the challenge I'm in xss.php and the only thing I can do is writing something in the input form (the one with name=result). What can I write?? Thank you
An XSS attack is one in which the page allows allows users to inject script blocks into the rendered HTML. So, first you must figure out how to do that. For instance, if the input from the user gets displayed on the page and it isn't html escaped then a user could do the following:
User enters :
<script>alert('testing');</script>
Following that, if when when viewing the page an alert is shown then the page is vulnerable to XSS.
Therefore if the user enters JavaScript as follows:
<script>window.location.href = "http://www.whatever.com";</script>
The user would be redirected.
You can pass by "error" GET variable a javascript code to redirect the page for whatever you want.
To do it,you'll access
error.php?error=<script>window.location.href="http://youpageurl.com";</script>
Then you have to be redirected to "yourpageurl.com" website