I wanted to make specific letter counter, but my counter is not increasing more that once. Can some one explain what i'm doing wrong?
Here is my code:
PHP:
<?php
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
$count_v++;
case 's':
$count_s++;
}
}
}
?>
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form action="index.php" method="POST">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': ".$count_v."<br/>";
echo "Count of letter 'S': ".$count_s."<br/>";
?>
</div>
</body>
</html>
Try this it will be work perfectly. paste it in any test file. This will retain no of times you input v and no of times you input s, value of s and v will remain same of input some other value.
<?php
$input = '';
if(!isset($count_v))
{
$count_v=0;
}
if(!isset($count_s))
{
$count_s=0;
}
if (filter_has_var(INPUT_POST, 'submit'))
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$input = $_POST['inp'];
switch ($input)
{
case 'v':
$_POST['count_v']++;
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
case 's':
$count_v=$_POST['count_v'];
$_POST['count_s']++;
$count_s=$_POST['count_s'];
break;
default:
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form method="POST">
<input type="hidden" name='count_v' value="<?php echo $count_v?>">
<input type="hidden" name='count_s' value="<?php echo $count_s?>">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': " . $count_v . "<br/>";
echo "Count of letter 'S': " . $count_s . "<br/>";
?>
</div>
</body>
</html>
you need to store counters in each request, because the variables lifetime is short (request life time), then they will be re-init from 0
to do this you can store the counters in file, database, or session
it depends on the time you want them to persist.
below is a sample for using session
** note the new line session_start(); you need to add it.
<?php
session_start();
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
if(!isset($_SESSION["count_v"])){
$_SESSION["count_v"] = 0;
}
$tmp = $_SESSION["count_v"];
$tmp++;
$_SESSION["count_v"] = $tmp;
break;
case 's':
if(!isset($_SESSION["count_s"])){
$_SESSION["count_s"] = 0;
}
$tmp = $_SESSION["count_s"];
$tmp++;
$_SESSION["count_s"] = $tmp;
break;
}
}
}
?>
and to read the values (in html page) use this:
<?php
echo "Count of letter 'V': ".$_SESSION["count_v"]."<br/>";
echo "Count of letter 'S': ".$_SESSION["count_s"]."<br/>";
?>
if you are going to store more than the 2 letters (s and v) then you can make the session key "count_v" generated dynamically using input itself. this will be a much less code, you will not need a switch/case
Edit: as i saw in your comment above, yes you can maintain counter values using hidden fields in HTML page, and use them to initialize the $count_s and $count_v instead of zero. you need to take care of first request when hidden values might be unset, or they could be zero
Related
I have mainly two question first describe what I going to do. I've created some animal in the code by saying that octopus will have 8 leggs,9 brain,1 stomach,3 heart similarly for other property.And by a html form using post method I'm taking input from user as showing the animals image if the description matches.
I've also declared the corresponding animals name.I want to also show the name of the animal after matching(by printing $name).
2)Here I'm matching user input for each animal(by using if,elseif elseif) but how can I optimize so that if there is more than 100 animal I don't have to do 100 else if.
Here is my code.
<?php
class animal{
var $name;
var $brain;
var $stomach;
public $heart;
public $leg;
function __construct($aBrain, $aStomach, $aHeart, $aLeg)
{
$this->brain = $aBrain;
$this->stomach = $aStomach;
$this->heart = $aHeart;
$this->setLeg($aLeg);
}
function isBipedal(){
if ($this->leg == 2) {
return "it is a bipedal animal";
}else {
return "it is not a bipedal animal";
}
}
function getLeg(){
return $this->leg;
}
function setLeg($leg){
if ($leg == 8 ||$leg == 4 ||$leg == 2) {
$this->leg= $leg;
}else {
$this->leg= "non-pedal";
}
}
}
$octopus = new animal(9,1,3,8);
$cow = new animal(1,4,1,4);
$human = new animal(1,1,1,2);
$octopus->setLeg(8);
//echo "new leg ".$octopus->leg = 0;
echo "<br>".$octopus->getleg();
echo "<br>".$human->isBipedal(). "<br>";
if(isset($_POST['submit'])) {
if(isset($_POST['brain'])
&& isset($_POST['stomach'])
&& isset($_POST['heart'])
&& isset($_POST['leg']) ){
$myBrain = $_POST['brain'];
$myStomach = $_POST['stomach'];
$myHeart = $_POST['heart'];
$myLeg = $_POST['leg'];
// echo "brain = ". $myBrain. "<br>";
// echo "stomach = ". $myStomach. "<br>";
// echo "heart = ". $myHeart. "<br>";
// echo "leg = ". $myLeg. "<br>";
if($myBrain==$octopus->brain
&& $myStomach==$octopus->stomach
&& $myHeart==$octopus->heart
&& $myLeg==$octopus->leg
){
?>
<div class="animal-info">
<div><p class="blinking">You are Octopus</p></div>
<img src="media/octopus.jpg" alt="" class="animal-img">
<img src="media/octopus.gif" alt="" class="animal-img">
</div>
<?php
}
elseif($myBrain==$cow->brain
&& $myStomach==$cow->stomach
&& $myHeart==$cow->heart
&& $myLeg==$cow->leg
){
?>
<div class="animal-info">
<div>
<span class="blinking">You are Cow</span>
</div>
<img src="media/cow.jpg" alt="" class="animal-img">
<img src="media/cow.gif" alt="" class="animal-img">
</div>
<?php
}
elseif($myBrain==$human->brain
&& $myStomach==$human->stomach
&& $myHeart==$human->heart
&& $myLeg==$human->leg
){
?>
<div class="animal-info">
<div>
<span class="blinking">You are Human</span>
</div>
<img src="media/human.jpg" alt="" class="animal-img">
<img src="media/human.gif" alt="" class="animal-img">
</div>
<?php
}else{
echo "you don't match with anything at all";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="post">
<span>How many brain you have?</span>
<input type="text" name="brain" id="brain">
<br>
<span>How many stomach you have?</span>
<input type="text" name="stomach" id="stomach">
<br>
<span>How many heart you have?</span>
<input type="text" name="heart" id="heart">
<br>
<span>How many leg you have?</span>
<input type="text" name="leg" id="leg">
<br>
<input type="submit" name="submit" value="Let me see">
</form>
</body>
</html>
u should either store them in a DB and make a query, or store them in array and search by some linq equivalent in php
Could You try with a Switch case?
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
I'm new to PHP and I'm trying to create an easy form that has multiple steps. For each step, a validation of the input is happening before the user is directed to the next page. If the validation fails, the user should stay on the same page and an error message should be displayed. In the end, all entries that the user has made should be displayed in an overview page.
What I have been doing to solve this, is to use a boolean for each page and only once this is true, the user can go to the next page. This is not working as expected unfortunately and I guess it has something to do with sessions in PHP... I also guess that there's a nicer way to do this. I would appreciate some help!
Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
session_start();
$_SESSION['$entryOne'] = "";
$_SESSION['$entryOneErr'] = $_SESSION['$emptyFieldErr'] = "";
$_SESSION['entryOneIsValid'] = false;
$_SESSION['$entryTwo'] = "";
$_SESSION['$entryTwoErr'] = "";
$_SESSION['entryTwoIsValid'] = false;
// Validation for first page
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryOne'])) {
if (!empty($_POST["entryOne"])) {
// Check for special characters
$_SESSION['$entryOne'] = removeWhitespaces($_POST["entryOne"]);
$_SESSION['$entryOneErr'] = testForIllegalCharError($_SESSION['$entryOne'], $_SESSION['$entryOneErr']);
// If error text is empty set first page to valid
if(empty($_SESSION['$entryOneErr'])){
$_SESSION['$entryOneIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
// Validation for second page
} else if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryTwo'])) {
if (!empty($_POST["entryTwo"])) {
// Check for special characters
$_SESSION['$entryTwo'] = removeWhitespaces($_POST["entryTwo"]);
$_SESSION['$entryTwoErr'] = testForIllegalCharError($_SESSION['$entryTwo'], $_SESSION['$entryTwoErr']);
// If error text is empty set second page to valid
if(empty($_SESSION['$entryTwoErr'])){
$_SESSION['$entryTwoIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
}
//Remove whitespaces at beginning and end of an entry
function removeWhitespaces($data) {
$data = trim($data);
return $data;
}
//Check that no special characters were entered. If so, set error
function testForIllegalCharError($wish, $error){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar,$wish)) {
$error = "Special characters are not allowed";
} else {
$error = "";
}
return $error;
}
?>
<?php if (isset($_POST['submitEntryOne']) && $_SESSION['$entryOneIsValid'] && !$_SESSION['$entryTwoIsValid']): ?>
<h2>Second page</h2>
<p>Entry from first Page: <?php echo $_SESSION['$entryOne'];?></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Entry Two: <input type="text" name="entryTwo" value="<?php echo $_SESSION['$entryTwo'];?>">
<span class="error"><?php echo $_SESSION['$entryTwoErr'];?></span>
<br><br>
<input type="submit" name="submitEntryTwo" value="Next">
</form>
<?php elseif (isset($_POST['submitEntryTwo']) && $_SESSION['$entryTwoIsValid']): ?>
<h2>Overview</h2>
<p>First entry: <?php echo $_SESSION['$entryOne'];?></p>
<p>Second Entry: <?php echo $_SESSION['$entryTwo'];?></p>
<?php else: ?>
<h2>First page</h2>
<span class="error"><?php echo $_SESSION['$emptyFieldErr'];?></span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br><br>
First entry: <input type="text" name="entryOne" value="<?php echo $_SESSION['$entryOne'];?>">
<span class="error"> <?php echo $_SESSION['$entryOneErr'];?></span>
<br><br>
<input type="submit" name="submitEntryOne" value="Next">
</form>
<?php endif; ?>
</body>
</html>
You are setting your session variables to "" at the top of your script.
Check if your variable is set before setting to blank.
Check if Session Variable is Set First
<?php
//If variable is set, use it. Otherwise, set to null.
// This will carry the variable session to session.
$entryOne = isset($_REQUEST['entryOne']) ? $_REQUEST['entryOne'] : null;
if($entryOne) {
doSomething();
}
?>
Tips
Then you can use <?= notation to also echo the variable.
Do this $_SESSION['variable'] instead of $_SESSION['$variable'] (you'll spare yourself some variable mistakes).
<h2>Second page</h2>
<p>Entry from first Page: <?= $entryOne ?></p>
Example Script
This could be dramatically improved, but for a quick pass:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Check that no special characters were entered. If so, set error
function hasIllegalChar($input){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar, $input)) {
return true;
}
return false;
}
session_start();
// Destroy session and redirect if reset form link is pressed.
if(isset($_GET['resetForm']) && $_GET['resetForm'] == "yes")
{
echo "SESSION DESTROY";
session_destroy();
header("Location: ?");
}
// Session
$page = isset($_SESSION['page']) ? $_SESSION['page'] : 1;
$errors = [];
// Value history.
$valueOne = isset($_SESSION['valueOne']) ? $_SESSION['valueOne'] : null;
$valueTwo = isset($_SESSION['valueTwo']) ? $_SESSION['valueTwo'] : null;
// Clean inputs here
$fieldOne = isset($_REQUEST['fieldOne']) ? trim($_REQUEST['fieldOne']) : null;
$fieldTwo = isset($_REQUEST['fieldTwo']) ? trim($_REQUEST['fieldTwo']) : null;
// First form
if ($page == 1) {
// If field two is submitted:
if ($fieldOne) {
//Validate inputs
if(hasIllegalChar($fieldOne)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueOne = $_SESSION['valueOne'] = $fieldOne;
$page = $_SESSION['page'] = 2;
}
}
}
// Second form
else if ($page == 2) {
// If field two is submitted:
if ($fieldTwo) {
//Validate inputs
if(hasIllegalChar($fieldTwo)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueTwo = $_SESSION['valueTwo'] = $fieldTwo;
$page = $_SESSION['page'] = 3;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
// troubleshoot
if (true) {
echo "<pre>";
var_dump($_REQUEST);
var_dump($_SESSION);
echo "</pre>";
}
echo "<h1>Page " . $page . '</h1>';
if (count($errors) > 0) {
$errorMsg = implode('<br/>',$errors);
echo '<div class="error">Some errors occurred:<br/>' . $errorMsg . '</div>';
}
?>
<?php if ($page == 3): ?>
<h2>Overview</h2>
<p>First entry: <?= $valueOne;?></p>
<p>Second Entry: <?= $valueTwo;?></p>
Reset
<?php elseif ($page == 2): ?>
<p>Entry from first Page: <?= $valueOne; ?></p>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
Entry Two: <input type="text" name="fieldTwo" value="<?= $fieldTwo ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php else: ?>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
<br><br>
Entry One: <input type="text" name="fieldOne" value="<?= $fieldOne; ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php endif; ?>
</body>
<html>
You can run the following command to test out the page without using a fancy tool like WAMP or LAMP.
php -S localhost:8000 index.php
You can now access in the browser at http://localhost:8000.
<?php
for ($x = 8; $x < 0; $x--) {
<input type="radio" name="day"
<?php if (isset($day) && $day=="monday") echo "checked";?>
value="mon">Monday 08:30 AM - 10:30 AM <br>;
}
?>
I want the radio button work eight times and then be disabled
<?php
header("Content-type: text/html; charset=utf-8");
session_start();
// store count result in SESSION
if (isset($_SESSION['count_days']) && !empty($_SESSION['count_days'])) {
// if there is already quantity of days
$count_days = $_SESSION['count_days'];
} else {
// or there are no days yet
$count_days = 0;
}
// after data posted look if radio was checked
if (isset($_POST['day'])) {
$day = $_POST['day'];
} else {
$day = 0;
}
$count_days += $day;
// save quanitity in SESSION
$_SESSION['count_days'] = $count_days;
if ($count_days == 8) {
$checkbox_status = ' disabled';
} else {
$checkbox_status = '';
}
// echo $count_days;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="" method="post">
Checkbox1 <input type="radio" name="day" value="1"<?php echo $checkbox_status; ?>>
<input type="submit" value="Send">
</form>
</body>
</html>
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.
I need to modify a block of code and add a counter regarding how many times it took the user to guess the right number.
I was wondering how it would be properly implemented into my code.
This is what I have so far.
<?php
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$count++; //Declare the variable $count to increment by 1.
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
You have to use PHP Sessions to keep track of the count.
All you have to do is initialize counter to 0 and have it increment when the user guesses a number
<?php
session_start();
if (!isset($_POST["guess"])) {
$_SESSION["count"] = 0; //Initialize count
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
echo $_POST["numtobeguessed"];
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else { // must be equivalent
$_SESSION["count"]++;
$message = "Well done! You guessed the right number in ".$_SESSION["count"]." attempt(s)!";
unset($_SESSION["count"]);
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
This should work for you.
$count = isset($_POST['count']) ? $_POST['count'] : 0; //Use post value if defined. If not set to 1.
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
$count++;
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<input type="hidden" name="count"
value="<?php echo $count; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
on 22.6.2021 i wrote a Guess Number in Range [0 .. aMaxIntValue] sample Web Application using PHP. i think the following code may help you. the code is kept in a Single PHP file. it generates #4 HTML pages ...
the 1st initial page is used to collect application parameters (e.g. the Max Int Number to Guess)
the 2nd page is the Main Play Game Page where the user is asked to Guess the Secret Number or to Reset Game. this page shows the previous user guesses and some tips for the user about the guess
the 3rd page is used to notify the user looses game (that is he has no more tries left)
the 4th page is used to notify the user wins the game (that is the Guess was OK)
the Number of Tries left to the User is computed using the values range [0 .. max]
the Secret Number to Guess is a random generated integer number
this is the PHP + HTML code ...
<?php
session_start();
error_reporting (E_PARSE | E_COMPILE_ERROR);
function ResetGame()
{
unset ( $_SESSION['theMaxNumber'] );
}
function InitGame()
{
$_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);
$_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;
$_SESSION['theUserTriesCount'] = 0;
$_SESSION['thePrevGuessesString'] = '';
$_SESSION['theUserGuess'] = 0;
}
function ComputeNumberOfTriesLeft()
{
return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
}
function IsNoMoreTriesLeft()
{
return ComputeNumberOfTriesLeft() <= 0;
}
$aCanPlayGame = false;
$aUserSubmittedGuess = false;
$aIsNoMoreTriesLeft = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( isset ($_REQUEST['playgame']) ) {
$_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);
// init game ...
InitGame();
$aCanPlayGame = true;
}
elseif ( isset ($_REQUEST['submituserguess']) ) {
$aCanPlayGame = true;
$aUserSubmittedGuess = true;
$_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);
}
elseif ( isset ($_REQUEST['resetgame']) ) {
ResetGame();
}
else {
ResetGame();
}
}
else {
ResetGame();
}
// check a play
$aUserShouldTryLower = false;
$aUserShouldTryHigher = false;
$aUserWins = false;
$aUserLooses = false;
if ($aCanPlayGame) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ( ! $aIsNoMoreTriesLeft ) {
// user have tries left
if ($aUserSubmittedGuess) {
// check user guess ...
$aUserGuess = intval($_SESSION['theUserGuess']);
if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryLower = true;
}
elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryHigher = true;
}
else {
$aUserWins = true;
// also reset game
ResetGame();
}
// add the current guess to the prev guesses string
$_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';
// increase the user tries count
++ $_SESSION['theUserTriesCount'];
// check tries count
if ( ! $aUserWins ) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ($aIsNoMoreTriesLeft) {
// this was the last try
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
}
}
else {
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
?>
<?php if ($aUserLooses): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Sorry, you loose the game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aUserWins): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Congrats, you Win the Game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aCanPlayGame): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
<p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
<p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
<p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
<form method="post">
<label for="theUserGuess">Enter your Guess: </label>
<input type="text" id="theUserGuess" name="theUserGuess">
<input type="submit" name="submituserguess" value="Guess">
<input type="submit" name="resetgame" value="reset game">
</form>
<p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
<p>
<?php
if ($aUserShouldTryLower) {
echo 'you should try a lower < guess';
}
elseif ($aUserShouldTryHigher) {
echo 'you should try a higher > guess';
}
else {
echo 'no guess';
}
?>
</p>
</body>
</html>
<?php else: ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Guess a Number from (0) to ... </p>
<form method="post">
<input id="theMaxNumber" name="theMaxNumber">
<input type="submit" name="playgame" value="play game">
</form>
</body>
</html>
<?php endif; ?>
that's all folks ...