Problems with guess a number game - php

Hey, I am so close to fininshing my guess a number game, very simple in PHP, but for some reason I am stuck. I am storing the variable in a hidden form, but obviously each time the page is sent it resets the number so you can never get the right one.
Any ideas? My code is below.
<?php
// generate a random number for user to guess
$number = rand(1,100);
if($_POST["guess"]){
// grab the user input guess
$guess = $_POST['guess'];
$numbe = $_POST['number'];
if ($guess < $number){
echo "Guess Higher";
}elseif($guess > $number){
echo "Guess Lower";
}elseif($guess == $number){
echo "You got it!";
}
echo "<br />Random Number:".$number."<br />";
echo $guess;
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Guess A Number</title>
</head>
<body>
<form action="<?=$_SERVER['PHP_SELF'] ?>" method="post" name="guess-a-number">
<label for="guess">Guess A Number:</label><br/ >
<input type="text" name="guess" />
<input name="number" type="hidden" value="<?= $number ?>" />
<input name="submit" type="submit" />
</form>
</body>
</html>

Change:
// generate a random number for user to guess
$number = rand(1,100);
To:
if(isset($_POST['number'])) {
$number = $_POST['number'];
} else {
$number = rand(1,100);
}

Is it because of this typo?
$numbe = $_POST['number'];
//numbe -> number

I realise you're probably just starting out but the earlier you learn this stuff, the better:
echo "<br />Random Number:".$number."<br />";
This is leaving you open to an XSS attack - I could send $_POST['number'] as <script> doSomethingBad(); </script>
You should either cast it to an integer ($number = (int)$_POST['number']) or escape your output (echo htmlspecialchars($_POST['number']);)
The same goes for $guess of course.
Interestingly, if you're using mod_rewrite, $_SERVER['PHP_SELF'] could also be manipulated to do the same thing.

Do something like:
$number = $_POST['number'];
if ($number == null) {
$number = rand(1,100);
}

Related

User Input from HTML form being cut off

We have an HTML form that takes in user input for an application, and uses PHP to process and send it to HR. The issue is it cutting off the text in the final result (picture below). There are no text limits set anywhere. Any help or ideas would be greatly appreciated.
Parts being cut off:
Cut Off
The form declaration and code for the fields being cut off:
<form id="application" name="application" method="post" action="sendresults.php" align="left">
<p>Work Performed<br />
<label>
<textarea name="workperform1" id="workperform1" tabindex="62" cols="50" rows="3"></textarea>
</label>
</p>
<p>Reason for Leaving<br />
<label>
<input name="reasonleaving1" type="text" onkeypress="return noenter()" id="reasonleaving1" tabindex="63"size="66" />
</label>
<br />
</p>
The PHP code:
<?php session_start();
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Results</title>
</head>
<body>
<?php
//--------------------------Set these paramaters--------------------------
$subject = 'Application for Employment';
$emailadd = 'blahblah#randomemail.org';
// Where to redirect after form is processed.
$url = 'http://www.randomwebsitename/random.html';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
die('The code you entered was incorrect. Go back and try again.');
}
foreach( $_POST as $key => $value ){
if ($req == '1'){
if( $value == '' ){
echo "$key is empty";
die;
}
}
$j = strlen($key);
if( $j >= 20 ) {
echo "Name of form element $key cannot be longer than 20 characters";
die;
}
$j = 20 - $j;
for ($i = 1; $i <= $j; $i++){
$space .= ' ';
}
$value = str_replace('\n', "$line", $value);
$conc = "{$key}:$space{$value}$line";
$text .= $conc;
$space = ' ';
}
mail($emailadd, $subject, $text, 'From: '.$emailadd.'');
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
?>
</body>
</html>

PHP Quiz not working properly

I'm trying to make a simple php quiz,but instead of choices I have to insert answers and compare them with strcasecmp() so it won't be a problem if the first letter is uppercase or anything like that,but the code doesn't work properly.Sometimes it doesn't return the correct result,even though I insert the correct answer.
Here is the code:
<?php
$number = rand(1,2);
$result = "";
$answer = "";
$question = "";
$question1 = "What is the capital of China";
$question2 = "What king of country is China?";
$answer1 = "beijing";
$answer2 = "republic";
if ($number == 1) {
$answer = $answer1;
$question = $question1;
}
if ($number == 2) {
$answer = $answer2;
$question = $question2;
}
if(isset($_POST['submit'])){
if (strcasecmp($answer,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Wrong!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="index.php">
<div class="middle">
<p class="question"><?php echo $question;
?></p>
<p class="result"><?php echo $result;
$result = "" ?></p>
<div class="box">
<input type="text" name="answer" placeholder="Type here" class="text">
</div>
</div>
<input type="submit" name="submit" value="Continue" class="btn">
</form>
</body>
</html>
By looking at your code, we can see that when you submit your form, you are restarting the script, which actually resets $random to a new value. With 2 questions, you have 50% chances to have the 'correct' answer, but you would see that your script doesn't work at all with more questions added.
Basically, you should use another way to achieve what you want. You could try to add the id of the question in an hidden <input> and check when your form is submit to determine which one it was.
if(isset($_POST['submit'])){
switch ($_POST['question']) { // Add '{'
case 1:
if (strcasecmp($answer1,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
}
break;
case 2:
if (strcasecmp($answer2,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
} // Forgot to Add '}'
break;
} // Add '}' It give error in PHP 5.3 Parse error: syntax error, unexpected T_CASE, expecting ':' or '{'
}
For the HTML, you could add this input in your form :
<input type="text" name="question" value="<?php echo $number ?>" hidden>
This is not the best way to achieve what you want, this is just an example of what would work.

Hiding a paragraph if input is empty

I have a small function that grabs the input values from my html page and puts them through a php function that will display them in a list. My goal is that if a field is left blank, the PHP script doesn't echo anything so that it would skip that instance entirely. It's probably better to show you than just talk of course:
HTML
<!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">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<form method="POST" action="test3.php" name="form">
<p>Please enter your name:</p>
<input type="text" name="1"></input>
<br />
<input type="text" name="2"></input>
<br />
<input type="text" name="3"></input>
<br />
<input type="text" name="4"></input>
<br />
<input type="text" name="5"></input>
<br />
<input type="submit" value="Submit" name="subButton" tabindex="50"></input>
</form>
</body>
</html>
PHP
function callNames(){
$body;
for($name = 1; $name <= 6; $name++){
if($name <= 5){
echo "Your name is " . $_POST[$name] . ".<br />";
}
elseif($name =? ){
?;
}
else {
echo "Your out of names!";
}
};
}
callNames();
I left the elseif function blank, as I thought that is where my solution would go. In other words, if you put in a name for everything but field 3, it would only echo "Your name is " 4 times but not leave an extra break where it would have been. Would I not use an elseif to solve this?
First off, as Fred -ii pointed out in the comments, in PHP field names cannot start with a number, but if they could here is how you would do it:
function callNames(){
$body;
for($name = 1; $name < 6; $name++){
if(isset($_POST[$name])){
echo "Your name is " . $_POST[$name] . ".<br />";
}
}
echo 'You are out of names!';
}
However, this assumes that the post variables go up sequentially until there are no more names.
If you explain what this is for, maybe someone can provide a better way to tackle the problem all together.
P.s the body variable seems unused?
Have you tried adding a condition that looks for $_POST[$name] length > 0 or that looks for $_POST[$name] != '';
function callNames(){
$body;
for($name = 1; $name <= 6; $name++){
if($name <= 5){
if ( $_POST[$name] != '' ) {
echo "Your name is " . $_POST[$name] . ".<br />";
}
}
elseif($name =? ){
?;
}
else {
echo "Your out of names!";
}
};
}
callNames();
You can even merge the two conditions in one with &&
function callNames(){
if ($_POST['name'] != ""){
echo "Your name is " . $_POST[$name] . ".<br />";
}
elseif($_POST['name'] == "?"){
echo "?";
}
else {
echo "Your out of names!";
}
}

I can't figure how to make this php form to work

I can't figure how can I make this simple PHP form to work.
What Am I do wrong?
<?php
$first = "firstNumber";
$second = "secondNumber";
$second * $first = "calc";
$calc = "calc";
echo("" . $_GET['$calc'] . "<br />\n");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="new.php" method="get">
<input type="text" name="firstNumber" id="first">
<input type="text" name="secondNumber" id="second">
<input style="background-color: #0094ff;" type="submit" name="calc" value="שלח" id="second">
</form>
</body>
</html>
In short
I guess you want something like
<?php
$first = $_GET["firstNumber"];
$second = $_GET["secondNumber"];
$calc = $second * $first;
echo $calc . "<br />";
?>
Expanded
But in complete, because if you run this you get warnings because you didn't send the form
<?php
if(isset($_GET['calc'])) {
$first = $_GET["firstNumber"];
$second = $_GET["secondNumber"];
$calc = $second * $first;
echo $calc . "<br />";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="new.php" method="get">
<input type="text" name="firstNumber" id="first">
<input type="text" name="secondNumber" id="second">
<input style="background-color: #0094ff;" type="submit" name="calc" value="שלח" id="second">
</form>
</body>
</html>
Example
http://codepad.viper-7.com/LZ7phd
Personally, I keep the name of the input field and the id of the input field the same. This may or may not help you.
<form action="new.php" method="get">
<input type="text" name="firstNumber" id="firstNumber">
<input type="text" name="secondNumber" id="secondNumber">
<input style="background-color: #0094ff;" type="submit" name="calc" value="שלח" id="second">
</form>
$_GET['$calc'] represents nothing here.
You must use $_GET['firstNumber'] and $_GET['secondNUmber']
You're not pulling your parameters from the $_GET stream:
$first = $_GET['firstNumber'];
$second = $_GET['secondNumber'];
$calc = $first * $second;
All your fields are passed in the $_GET stream.
$_GET['calc'] is actually your submit button by the way, not your calculation variable.
You can't use the id property of input to call the values of those fields. You must use $_GET and the name of the input field. You're also assigning variables incorrectly:
<?php
$first = $_GET[firstNumber];
$second = $_GET[secondNumber];
$calc = $second * $first;
echo $calc . "<br />\n";
?>

preg_match help from an input box [duplicate]

This question already has answers here:
php date validation
(13 answers)
Closed 9 years ago.
I need to validate a Date from an input box.
The regular expression is fine but that is about it.
First where in the scope does it go, and second can you help make this work?
When it validates I dont want it to echo anything and when it doesnt I would like it to
tell the user that they must enter it in mm/dd/yyyy format. If you can do this in an alert box that would be even better! Thank you fellow developers!!! The COMPLETE code follows the tag. Youll see my preg_match is commented out. Thank you fellow developers!!!
$input = '<input value="Date" type="text" name="date">';
if (preg_match('/^(|(0[1-9])|(1[0-2]))\/((0… $input)) {
echo "";
} else {
echo "You must Re-enter date in mm/dd/yyyy format.";
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<embed src="Songs/nature.mp3" width=10 height=10 autostart=true repeat=true loop=true></embed>
<title>Post Song</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Post New Song</h1>
<hr />
<br />
<body background="Songs/back.jpg">
<form action= "Postsong.php" method="POST">
<span style="font-weight:bold">Song:</span>
<input value="" type="text" name="song" />
<span style="font-weight:bold">Artist Name:</span>
<input value="" type="text" name="name" />
<span style="font-weight:bold">Date:</span>
<input value="" type="text" name="date" /><br />
<br />
<br />
<input type="submit" name="submit"
value="Post Song" />
</form>
<hr />
<p>
View Songs
</p>
<?php
/*
$input = '<input value="Date" type="text" name="date">';
if (preg_match('/^(|(0[1-9])|(1[0-2]))\/((0[1-9])|(1\d)|(2\d)|(3[0-1]))\/((\d{4}))$/', $input)) {
echo "";
} else {
echo "You must Re-enter date in mm/dd/yyyy format.";
}
*/
if (isset($_POST['submit'])) {
$Song = stripslashes($_POST['song']);
$Name = stripslashes($_POST['name']);
$Date = stripslashes($_POST['date']);
$Song= str_replace("~", "-", $Song);
$Name = str_replace("~", "-", $Name);
$Date = str_replace("~", "-", $Date);
$ExistingSubjects = array();
if (file_exists(
"Songs/songs.txt") &&
filesize("Songs/songs.txt")
> 0) {
$SongArray = file(
"Songs/songs.txt");
$count = count($SongArray);
for ($i = 0; $i < $count; ++$i) {
$CurrSong = explode("~",
$SongArray[$i]);
$ExistingSubjects[] = $CurrSong[0];
}
}
if (in_array($Song, $ExistingSubjects)) {
echo "<p>The song you entered
already exists!<br />\n";
echo "Please enter a new song and
try again.<br />\n"; // Do I need another if statement saying if empty echo you need to enter something?...
echo "Your song was not saved.</p.";
$Song = "";
}
else {
$SongRecord =
"$Song~$Name~$Date~\n";
$SongFile = fopen(
"Songs/songs.txt",
"ab");
if ($SongFile === FALSE)
echo "There was an error saving your
song!\n";
else {
fwrite($SongFile,
$SongRecord);
fclose($SongFile);
echo "Your song has been
saved.\n";
$Song = "";
$Name = "";
$Date = "";
}
}
}
else {
$Song = "";
$Name = "";
$Date = "";
}
?>
</body>
The following regex matches for mm/dd/yyyy
(0[1-9]|1[0-2])/(0[1-9]|1[0-9]|2[0-9]|3(0|1))/\d{4}
The first part i.e. (0[1-9]|1[0-2]) checks for two digits ranging from 01 to 12.
Next part i.e. (0[1-9]|1[0-9]|2[0-9]|3(0|1)) checks for two digits ranging from 01 to 31.
Next part i.e. \d{4} checks for 4 digits.
/ between the parts checks for / as separator.

Categories