This question already has answers here:
Process HTML files like PHP
(5 answers)
Closed 7 years ago.
(First time posting, sorry if formatting is bad :( )
I patched together an html/php page. It works on this live test environment I used phpfiddle.org
Working there it looks like this
When I save the code and upload the file to my server (I've tried two servers, same problem on both), it's broken
I suspect the problem might be with the header, but I have no clue.
This is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$potErr = $stackErr = "";
$pot = $stack = "";
$p = $s = $g1 = $g2 = $b11 = $b12 = $b21 = $b22 = $b23 = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["pot"])) {
$potErr = "Pot size is required";
} else {
$pot = test_input($_POST["pot"]);
if (!preg_match("/^\d+$/",$pot)) {
$potErr = "Only integers allowed (might work with decimals though, I haven't tested it')";
}
}
if (empty($_POST["stack"])) {
$stackErr = "Stacksize is required";
} else {
$stack = test_input($_POST["stack"]);
if (!preg_match("/^\d+$/",$pot)) {
$stackErr = "Only integers allowed";
}
}
$p = $pot;
$s = $stack;
$g1 = pow(($p+2*$s)/$p,1/2);
$g2 = pow(($p+2*$s)/$p,1/3);
$b11 = ($p*$g1-$p)/2;
$b21 = ($p*$g2-$p)/2;
$b12 = $p*$g1*($g1-1)/2;
$b22 = $p*$g2*($g2-1)/2;
$b23 = $p*$g2*$g2*($g2-1)/2;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Geometric Sizing Calculator</h2>
<p>
<i>Shoutout to AlexMartin's pokernerdz.com which is unfortunately offline. A quick geo calc in his honor! - Paul lnternet Otto </i>
</p>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Pot: <input type="text" name="pot" value="<?php echo $pot;?>">
<span class="error">* <?php echo $potErr;?></span>
<br><br>
Stack: <input type="text" name="stack" value="<?php echo $stack;?>">
<span class="error">* <?php echo $stackErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Geo Sizing:</h2>";
echo "<b>2-street sizing plan:</b> <br>";
echo "Bet " . round($b11) . " then bet " . round($b12) .".";
echo "<br><br>";
echo "<b>3-street sizing plan:</b> <br>";
echo "Bet " . round($b21) . " then bet " . round($b22) . " then bet " . round($b23) .".";
?>
</body>
</html>
With the html extension your PHP instance doesn't know to process it, so it doesn't. You can modify your server so html and htm files are processed as PHP as well; or you can just rename the file to .php.
For the latter solution see this thread; Process HTML files like PHP.
Related
I am attempting to display the results without the form being shown at the same time. So, initially when they go to the URL they see the form, and after they fill out the form and the form validation and required fields and URL is valid. Here is what I started with.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$TXTlinknameErr = $TXTurlErr = "";
$TXTlinkname = $TXTurl = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["TXTlinkname"])) {
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = test_input($_POST["TXTlinkname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$TXTlinknameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurl = "";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurlErr = "URL is required";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="TXTlinkname" value="<?php echo $TXTlinkname;?>">
<span class="error">* <?php echo $TXTlinknameErr;?></span>
<br><br>
URL: <input type="text" name="TXTurl" value="<?php echo $TXTurl;?>">
<span class="error"><?php echo $TXTurlErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">' . $TXTlinkname . '</textarea>';
?>
</body>
</html>
Here is what I have tried.
I've tried adding else statements after body and before results. I'd like the results not to show until after form submitted.
Here's what I have so far...
I tried to add the below after the body
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['name']) == "")){
?>
Then I added:
<?php
} else {
//Retrieve show string from form submission.
Just after
// define variables and set to empty values
Finally added:
<?php
} ?>
Before /body
Here is what I tried.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['TXTlinkname'] && $_POST['TXTurl']) == "")){
?>
<?php
// define variables and set to empty values
$TXTlinknameErr = $TXTurlErr = "";
$TXTlinkname = $TXTurl = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["TXTlinkname"])) {
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = HTML_input($_POST["TXTlinkname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$TXTlinknameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurl = "";
} else {
$TXTurl = HTML_input($_POST["TXTurl"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurlErr = "URL is required";
} else {
$TXTurl = HTML_input($_POST["TXTurl"]);
}
}
function HTML_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="TXTlinkname" value="<?php echo $TXTlinkname;?>">
<span class="error">* <?php echo $TXTlinknameErr;?></span>
<br><br>
URL: <input type="text" name="TXTurl" value="<?php echo $TXTurl;?>">
<span class="error"><?php echo $TXTurlErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
} else {
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">' . $TXTlinkname . '</textarea>';
?>
<button onclick="location = location.href">Go Back</button>
<?php
} ?>
</body>
</html>
So, initially when they go to the URL they see the form, and after they fill out the form and the form validation and required fields and URL is valid.
The big issue I see with your code is the if statement. The variables are not defined unless form hasn't been submitted. What I've changed is moved the function to be defined globally along with the variable names, and inverted the if statement. PHP Tags, you don't need them everywhere. One wrapper is good enough.
I'm not sure about what your result is, but for what you asked, I shall provide.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
function HTML_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$TXTlinkname = $TXTurl = "";
$TXTlinknameErr = $TXTurlErr = "";
//If form not submitted, display form.
if (isset($_POST['submit'])){
if (empty($_POST['TXTurl'])) {
$TXTurlErr = "URL is required";
} else {
$TXTurl = HTML_input($_POST['TXTurl']);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST['TXTname'])) {
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = HTML_input($_POST['TXTname']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$TXTlinknameErr = "Only letters and white space allowed";
}
}
}
if (empty($TXTurlErr) && empty($TXTlinknameErr) && isset($_POST['submit'])) {
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">' . $TXTlinkname . '</textarea>';
echo '<button onclick="location = location.href">Go Back</button>';
} else {
echo '<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'">
Name: <input type="text" name="TXTname" value="'.$TXTlinkname.'">
<span class="error">* '. $TXTlinknameErr .'</span>
<br><br>
URL: <input type="text" name="TXTurl" value="'.$TXTurl.'">
<span class="error">'.$TXTurlErr.'</span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>';
}
?>
</body>
</html>
Tested locally on XAMPP
You have to have a variable that tells you if you're going to show the textarea or not...
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$TXTlinknameErr = $TXTurlErr = "";
$TXTlinkname = $TXTurl = "";
$show_textarea = false; //DEFAULT
if (isset($_POST['submit'])) { //The form is sent...
$show_textarea = true; //Then this is DEFAULT!!
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["TXTlinkname"])) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = test_input($_POST["TXTlinkname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTlinknameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["TXTurl"])) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTurl = "";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST["TXTurl"])) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTurlErr = "URL is required";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($show_textarea === false) {
?>
<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="TXTlinkname" value="<?php echo $TXTlinkname;?>">
<span class="error">* <?php echo $TXTlinknameErr;?></span>
<br><br>
URL: <input type="text" name="TXTurl" value="<?php echo $TXTurl;?>">
<span class="error"><?php echo $TXTurlErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
if (isset($_POST['submit'])) { //The form is sent...
if ($show_textarea === true ) { //...AND the form has valid values
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">
' . $TXTlinkname . '
</textarea>';
}
}
?>
</body>
</html>
try this one:
if (!$_POST) || $_POST['TXTlinkname'] == "" && $_POST['TXTurl']) == "")){
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 am trying to check the form on this page and if everything is entered correct I want send the $name, $sport, $beoefenaar and $text to the page http://localhost/051R4-verwerk.php. But the variables aren't being sent to that page.
<!DOCTYPE HTML>
<html>
<head>
<title>Inzendopdracht 051R4</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" type="text/css" media="all" />
</head>
<body>
<a href='viewguestbook.php'>View Guestbook</a>
<?php
// define variables and set to empty values
$nameErr = $sportErr = $beoefenaarErr = $textErr = "";
$name = $sport = $beoefenaar = $text ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = true;
if (empty($_POST["name"])) {
$nameErr = "Name is required";
$valid = false;
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["sport"])) {
$sportErr = "Sport is required";
$valid = false;
} else {
$sport = test_input($_POST["sport"]);
}
if (empty($_POST["text"])) {
$textErr = "Comment is required";
$valid = false;
} else {
$text = test_input($_POST["text"]);
}
if (empty($_POST["beoefenaar"])) {
$beoefenaarErr = "Comment is required";
} else {
$beoefenaar = test_input($_POST["beoefenaar"]);
}
if($valid){
header("location: http://localhost/051R4-verwerk.php");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Laat hier u bericht achter</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Sport: <select name="sport">
<option valeu="">
<option valeu="Tennis">Tennis
<option valeu="Voetbal">Voetbal
<option valeu="Running">Running
<option valeu="Tafeltenis">Tafeltenis
<option valeu="Squash">Squash
<option valeu="Wielrennen">Wielrennen
<option valeu="Boksen">Boksen
</select>
<span class="error">* <?php echo $sportErr;?></span>
<br><br>
Beoefenaar:
<INPUT TYPE="radio" name="beoefenaar" value="0" checked>Nee
<INPUT TYPE="radio" name="beoefenaar" value="1">Ja
<br><br>
<textarea name="text" placeholder="Schrijf hier u bericht*" /></textarea>
<span class="error"> <?php echo $textErr;?></span>
<br><br>
<input type="submit" value="Verstuur"/>
</form>
</body>
</html>
The issue is that you aren't including your second PHP file. You are redirecting to the second PHP file. This means that your are instructing the browser to load up a new page with a new HTTP request. PHP can't store variables between calls, so when this new request comes in all previous variables (and history) are lost. Each page executes completely separate from every other page.
Instead, the simplest way to accomplish what you are trying to accomplish is with sessions. This allows you to store information on a user between script executions. PHP will automatically create cookies for you and manage the session information. You just have to get your data into the session, and then get it back out of the session in your second script. In your first script that could look something like this:
if($valid){
$_SESSION['name'] = $name;
$_SESSION['sport'] = $sport;
/// and more
header("location: http://localhost/051R4-verwerk.php");
}
Then in your receiving script:
$name = isset( $_SESSION['name'] ) ? $_SESSION['name'] : '';
$sport = isset( $_SESSION['sport'] ) ? $_SESSION['sport'] : '';
This will only work if the two scripts are hosted by the same server and on the same domain. There are lots of tutorials out there about using sessions. You will actually still have to validate the data again in your second script, because a user can go directly to it without any information in the session.
Your second option would be to include the second script instead of redirecting to it, in which case your variables will actually be available, but you will also have to adjust the way your first page works. Maybe something like:
if($valid){
include "051R4-verwerk.php";
exit;
}
This is similar to a previous question I asked about matching the selected radio button with the value in the input field.
The code lets a user build a quiz by entering a question and 4 possible answers. You must select one of the answers as the correct one and on a separate PHP page, the answers must be displayed with the correct one in green. Originally this problem was solved, but after I modified the code for validation, the original loop for display would not work.
Here is the output of the code:
I need Albany to print in green since it's the correct answer and was selected with the radio button.
Here is my code for the form:
<?php
session_start();
// Define variables and set to empty values
$questionErr = $answer0Err = $answer1Err = $answer2Err = $answer3Err = "";
$question = $answer0 = $answer1 = $answer2 = $answer3 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = True;
if (empty($_POST['question'])) {
$questionErr = "Please supply a question";
$valid = False;
} else {
$question = test_input($_POST['question']);
$_SESSION['question'] = $_POST['question'];
}
if (empty($_POST['answer0'])) {
$answer0Err = "Please supply a possible answer";
$valid = False;
} else {
$answer0 = test_input($_POST['answer0']);
$_SESSION['answer0'] = $_POST['answer0'];
}
if (empty($_POST['answer1'])) {
$answer1Err = "Please supply a possible answer";
$valid = False;
} else {
$answer1 = test_input($_POST['answer1']);
$_SESSION['answer1'] = $_POST['answer1'];
}
if (empty($_POST['answer2'])) {
$answer2Err = "Please supply a possible answer";
$valid = False;
} else {
$answer2 = test_input($_POST['answer2']);
$_SESSION['answer2'] = $_POST['answer2'];
}
if (empty($_POST['answer3'])) {
$answer3Err = "Please supply a possible answer";
$valid = False;
} else {
$answer3 = test_input($_POST['answer3']);
$_SESSION['answer3'] = $_POST['answer3'];
}
}
// Function to sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// If valid, send to QuestionReview.php to display answers
if ($valid) {
$_SESSION['radio'] = $_POST['radio'];
header('location: QuestionReview.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User-Created Quiz</title>
<style>
.shadow {
-webkit-box-shadow: 3px 3px 5px 6px #ccc; /* Safari 3-4, iOS 4.0.2 - 4.2, Android 2.3+ */
-moz-box-shadow: 3px 3px 5px 6px #ccc; /* Firefox 3.5 - 3.6 */
box-shadow: 3px 3px 5px 6px #ccc; /* Opera 10.5, IE 9, Firefox 4+, Chrome 6+, iOS 5 */
}
.instructions {
color: #696D6E;
}
#form-background {
background-color: #ECEDE8;
}
.error {
color: red;
}
</style>
</head>
<body>
<div style="width:600px">
<fieldset id="form-background" class="shadow">
<h1 class="instructions" style="text-align:center">User-Created Quiz</h1>
<p class="instructions" style="text-align:center">
<strong>Please enter a question of your own,
along with 4 possible answers in the
form below. Be sure to select the
correct answer to your question
before submitting the form.</strong>
</p>
<form style="text-align:center;" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br>
<label class="instructions" for="question" >Enter your question here</label><br>
<input type="text" name="question" size="50" value='<?php echo $question;?>' />
<span class="error">* <br /><?php echo $questionErr; ?></span>
<br><br>
<p class="instructions">
Please provide four answers to your question and select the
correct one.
</p>
<input type="radio" name="radio" value="answer0">
<input type="text" name="answer0" value="<?php echo $answer0; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer0Err; ?></span>
<br><br>
<input type="radio" name="radio" value="answer1">
<input type="text" name="answer1" value="<?php echo $answer1; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer1Err; ?></span>
<br><br>
<input type="radio" name="radio" value="answer2">
<input type="text" name="answer2" value="<?php echo $answer2; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer2Err; ?></span>
<br><br>
<input type="radio" name="radio" value="answer3">
<input type="text" name="answer3" value="<?php echo $answer3; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer3Err; ?></span>
<br><br>
<input type="submit" value="Submit Entry">
</form>
</fieldset>
</div>
</body>
</html>
And here is my code for the result page:
<?php
session_start();
// Pull all variables from SESSION
$question = $_SESSION['question'];
$answer0 = $_SESSION['answer0'];
$answer1 = $_SESSION['answer1'];
$answer2 = $_SESSION['answer2'];
$answer3 = $_SESSION['answer3'];
$radio = $_SESSION['radio'];
$answerArray = array($answer0, $answer1, $answer2, $answer3);
shuffle($answerArray);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Entry Review</title>
<style>
.instructions {
color: #696D6E;
}
</style>
</head>
<body>
<h1 class="instructions">Entry Review</h1>
<p><em>You entered the following question:</em></p>
<p><strong><?php echo $question; ?></strong></p><br>
<p><em>These are the answers you provided:</em>
<p>
<strong>
<?php
if(isset($_SESSION['radio'])) {
$radio = $_SESSION['radio'];
foreach ($answerArray as $value) {
echo $value . "<br />";
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
?>
</strong>
</p>
</body>
</html>
Get a bit of A4 plain paper, work away from your computer for ten minutes.
Now, establish what you're trying to achieve in blocks, what do you want each part of your skillset/language/operator-syntax (PHP, javascript, CSS, HTML etc.) to do?
You have a list of outputs already displayed on your project and you want to mark a chosen output, as differet from the others.
work backwards from that end result, what will make this change? That's right, CSS, so you can write on your paper, you need a CSS class (or other identifier) for a chosen output, that you can call for that answer.
So how will the CSS know which output to choose? Where is this data held?
This data appears to be in PHP somewhere, (but it's not immediately obvious from your code). So, you need a PHP IF statement to check If the answer that is being displayed to the browser is the answer that the user has chosen then that answer needs to be encased in a CSS class somehow (<div> or <span> ) to effect the dfference in appearance.
And that's it. You should have enough of a structure now to go away and to write out notes on that A4 sheet and then use those notes to break your various issues down into component parts (here, there are parts for difining what behaviour should happen and then parts for making that behaviour happen).
Rewrite your code in 5-10 minutes you'll have it exactly as you want it.
On QuestionReview.php page, get the correct answer like this,
$correct_answer = $_SESSION[$_SESSION['radio']];
So keep your quiz page as it is and after submitting, process your form like this:
QuestionReview.php:
<?php
session_start();
// Pull all variables from SESSION
$question = $_SESSION['question'];
$answer0 = $_SESSION['answer0'];
$answer1 = $_SESSION['answer1'];
$answer2 = $_SESSION['answer2'];
$answer3 = $_SESSION['answer3'];
$correct_answer = $_SESSION[$_SESSION['radio']];
$answerArray = array($answer0, $answer1, $answer2, $answer3);
shuffle($answerArray);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Entry Review</title>
<style>
.instructions {
color: #696D6E;
}
</style>
</head>
<body>
<h1 class="instructions">Entry Review</h1>
<p><em>You entered the following question:</em></p>
<p><strong><?php echo $question; ?></strong></p><br>
<p><em>These are the answers you provided:</em>
<p>
<strong>
<?php
if(isset($_SESSION['radio'])) {
foreach ($answerArray as $value) {
$output = "<span";
if($value == $correct_answer){
$output .= " class='instructions'";
}
$output .= ">" . $value . "</span><br />";
echo $output;
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
?>
</strong>
</p>
</body>
</html>
In each iteration of the foreach loop, check if the current option equals to the correct answer or not. If it is then apply the class instructions to the current option.
Output: (Screenshot)
You are almost there... just make it simple:
If you have:
$question = $_SESSION['question'];
$radio = $_SESSION['radio'];
$answerArray = [$_SESSION['answer0'], $_SESSION['answer1'], $_SESSION['answer2'], $_SESSION['answer3']];
Then you can:
if(isset($_SESSION['radio'])) {
foreach ($answerArray as $value) {
echo $_SESSION['radio'] == $value ? "<span style=\"color:green\">Make $value green.</span><br />" : "<span style=\"color:#666\">Make $value grey or red.</span><br />";
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
Which equals to:
if(isset($_SESSION['radio'])) {
foreach ($answerArray as $value) {
if ($_SESSION['radio'] == $value){
echo "<span style=\"color:green\">Make $value green.</span><br />";
} else {
echo "<span style=\"color:#666\">Make $value grey or red.</span><br />";
}
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
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.