Why isn't my PHP POST request going through? - php

I'm trying to build a system that will give a user a random question, then send the user's answer and the correct answer to the next page via POST, without ever showing the user what the correct answer is. When FileB.php loads, var_dump($_POST); reads
array(1) {
["response"]=>
string(32) "Whatever the user's response was"
}
Why doesn't what I have below work? Why isn't the ans post request going through?
FileA.php
<?PHP
function post($data) // from http://stackoverflow.com/questions/5647461/how-do-i-send-a-post-request-with-php
{
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n"
, 'method' => 'POST'
, 'content' => http_build_query($data)
),
);
$context = stream_context_create($options);
}
post(array("ans" => "Correct Answer"));
?>
<HTML>
<HEAD>
<TITLE>Form</TITLE>
</HEAD>
<BODY>
<FORM METHOD="post" ACTION="FileB.php">
<LABEL>What is the correct answer? <INPUT TYPE="text" NAME="response"/></LABEL>
</FORM>
FileB.php
<HTML>
<HEAD>
<TITLE>Results</TITLE>
</HEAD>
<BODY>
<?PHP
if ($_POST["ans"] == $_POST["response"])
{
echo "You are correct!";
}
else
{
echo "You're wrong!";
}
?>
</BODY>
</HTML>

After you got Strat's suggestion working, an improvement might be to store the correct answer in a session variable instead of revealing it in the HTML source. You don't need a hidden field then. Example:
FileA.php
session_start();
$_SESSION['answer'] = "....";
FileB.php
session_start();
if ($_POST['response'] == $_SESSION['answer'])
{
echo "You're right.";
}
...

Why don't you have a submit button or something like "JavaScript+Ajax" to capture user input ? If this isn't your issue, please specify what exactly doesn't work with your script ? Do you get "You're wrong" even when the response is correct or you don't get any output at all ? It could also be because you call post() before taking input.

Try something like this:
FileA.php
<HTML>
<HEAD>
<TITLE>Form</TITLE>
</HEAD>
<BODY>
<FORM METHOD="post" ACTION="FileB.php">
<LABEL>What is the correct answer? <INPUT TYPE="text" NAME="response"/></LABEL>
<INPUT TYPE="hidden" NAME="answer" VALUE="Correct Answer" />
</FORM>
</BODY>
</HTML>
FileB.php
<HTML>
<HEAD>
<TITLE>Results</TITLE>
</HEAD>
<BODY>
<?PHP
if ($_POST["answer"] == $_POST["response"]){
echo "You are correct!";
}else{
echo "You're wrong!";
}
?>
</BODY>
</HTML>
Obviously change the VALUE of the answer input to whatever your answer should be. Not the best solution if you need to hide the answer 100%, but probably the easiest to get it working.

From what I understand from your question is that you would have like to pass two variables: random question and its answer to FileA.php, but you also want your answer to be hidden. Then, you use POST to send the answer to FileB.php.
You can do as what #Strat has suggested, by having a hidden field. For example:
<?php
$random_question = '.....';
$random_answer = '.....';
?>
<?php echo $random_question; ?>
<form action='fileB.php' methid='POST'>
<input type='text' name='response' />
<input type='hidden' name='ans' value='<?php echo $random_answer; ?>' />
</form>
The downside is that hidden field only prevent broswer from displaying the answer, but they can easily inspect the element and get the correct answer. You can prevent it by
<input type='hidden' name='ans' value='<?php echo md5($random_answer); ?>' />
and
if ($_POST["ans"] == md5($_POST["response"]))
The solution that I suggest is not the best. There is probably a better way to do it if you provide more context such as whether there is database behind the script that random the question.

Related

How to fill PHP form with data from URL?

I have a short sample php code above:
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Check for perfect palindrome</title>
</head>
<body>
<h1>Check for perfect palindrome</h1>
<form method="post">
<label for="stringInput">String:</label><input type="text" id="stringInput" name="stringInput"><br/>
<br/><input type="submit" name="submit" value="Check"/>
</form>
</body>
<?php
if(isset($_POST['stringInput']))
{
$string = $_POST['stringInput'];
if ($string =="")
{
echo "Please fill the form";
} else if ($string == strrev($string))
{
echo "You entered: <b>'$string'</b> is a perfect palindrome.";
} else
{
echo "You entered: <b>'$string'</b> is NOT a perfect palindrome.";
}
}
?>
</HTML>
Imagine that the code is saved under file sample.php and located at localhost/sample.php.
I want to fill the form and trigger the submit button through this link:
localhost/sample.php?stringInput=abc&submit=Check
How can I do that? Thanks for help.
I need to use POST method because the actual form has many inputs not just one and I want to know how it will work with POST. And using PHP only if possible. (Javascript, jQuery are not the first choices). Cheers.
This is a good example to demonstrate what I need.
http://image.online-convert.com/convert-to-jpg?external_url=jhjhj&width=333
I tried GET method and the form doesn't display value.
If you want to include the parameters in the URL you cannot use POST
From wikipedia:
the POST request method requests that a web server accept the data enclosed in the body of the request message
Whereas in a GET request (from w3schools):
the query string is sent in the URL of a GET request
Try this:
You can assign your post values to variables & echo them in your input.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Check for perfect palindrome</title>
</head>
<body>
<?php
$string = "";
if(isset($_POST['stringInput']))
{
$string = $_POST['stringInput'];
if ($string =="")
{
echo "Please fill the form";
} else if ($string == strrev($string) )
{
echo "You entered: <b>'$string'</b> is a perfect palindrome.";
} else
{
echo "You entered: <b>'$string'</b> is NOT a perfect palindrome.";
}
}
?>
<h1>Check for perfect palindrome</h1>
<form method="post">
<label for="stringInput">String:</label><input type="text" id="stringInput" name="stringInput" value="<?php echo $_REQUEST['stringInput'];?>"><br/>
<br/><input type="submit" name="submit" value="Check" />
</form>
</body>
</HTML>
You are using the wrong http method instead of POST you should use GET
"Note that the query string (name/value pairs) is sent in the URL of a
GET request"
Check more about these two methods here: POST vs GET

Variables not setting after posting from html form

I am practicing sending data from a form and echoing that data in a different php script. However, my input is not being posted to the php script that i am pointing my form to.
Hub.php
<!Doctype html>
<html>
<head>
<title>Hub</title>
</head>
<body>
<form action = "test.php" method = "post">
<input type ="radio" value ="assignment_2" name ="choice" >Assignment 2</br>
<input type ="submit" >
</form>
</body>
</html>
test.php
<!Doctype html>
<html>
<body>
<?php
echo $_POST["choice"];
?>
</body>
</html>
After I click the submit button, I am redirected to the test.php page, but it says "Undefined index: choice". I have looked at all the other posts regarding this matter, but none of the answers seem to work for me. Can someone please let me know what i am doing wrong? I am new to php and working with form data so any help will be appreciated.
Thank You.
Okay, so after trying various things suggested by #Alfredo EM, the get method is working and gives me the following output when i run var_dump($_GET);
array(2) { ["choice"]=> string(12) "assignment_2" ["textfield"]=> string(7) "my text" }
The post method is still not working.
I do remember I have saw this issue before, have a look this if you are testing the scripts on your localhost. Hope this can help you.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/207255485-No-POST-values-caught
Radio buttons don't send Post data if they aren't checked, so you'll get an Undefined index error if you try to access it. You can use this code to test if it is checked or not:
if(isset($_POST["choice"])){
echo $_POST["choice"];
} else{
echo "Not checked";
}
You should verify radio button checked before submitting.
HTML:
<form method="post" action="test.php">
<input type="radio" name="choice" value="assignment_2"/>Assignment 2</br>
<input type="submit" name="submit" value="submit"/>
</form>
PHP:
if (isset($_POST['submit'])) {
if (isset($_POST['choice'])) {
$choice = $_POST['choice'];
echo $choice;
} else {
echo 'No Data selected';
}
}

How to keep value after post request?

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>

PHP Pass variable up the page

I came across someone asking the question,
How can I pass a variable up the page (on the same page?).
I had a think about it but couldn't think of how to do it myself, so I was wondering if it is even possible?
So what he was trying to do was change the value of $a at the top of the page at the same time as the bottom value of $a.
Is it possible? If so how?
Thanks in advanced.
<?php
echo("Begining " . $a);
?>
<html>
<head>
<title>Test Variables</title>
</head>
<body>
<form>
<form action="<?=$PHP_SELF?>" method="POST">
<input type="TEXT" name="testf" size="10">
<input type="submit" name = "submit" value = "submit"></form><?php
if ("submit" == $submit) {
$a = $testf;
echo( "Bottom " . $a);
}
?>
</body></html>
Edit:
After seeing answers, maybe it can be done with jquery, ajax or javascript?
No, you'll need to move the if statement to the top, and any variables you calculate that need to be in the if statement also to the top.
Something like:
<?php
if ("submit" == $submit) {
$a = $testf;
}
echo("Begining " . $a);
?>
<html>
<head>
<title>Test Variables</title>
</head>
<body>
<form>
<form action="<?=$PHP_SELF?>" method="POST">
<input type="TEXT" name="testf" size="10">
<input type="submit" name = "submit" value = "submit"></form><?php
echo( "Bottom " . $a);
?>
</body></html>
It's considered a good practice to have all the logic before you start outputting the HTML anyways. Your HTML should ideally have as less logic as possible.
More info: https://stackoverflow.com/a/95027/320615 and https://stackoverflow.com/a/1088791/320615
You can probably bend over backwards to make that work somehow.
But the real answer is to handle all your business logic before you start outputting any HTML. You need to decide at the beginning of your code whether the current request is a form submission or not and set variables and HTML templates accordingly. Never mix business logic into the middle of your HTML templates.
You have to use the $_POST['testf'] and $_POST['submit'] variable.
And also check if it exists with isset : php manual isset
<?php
echo("Begining " . $a);
?>
<html>
<head>
<title>Test Variables</title>
</head>
<body>
<form>
<form action="<?=$PHP_SELF?>" method="POST">
<input type="TEXT" name="testf" size="10">
<input type="submit" name = "submit" value = "submit"></form><?php
if ("submit" == $submit) {
$a = $_POST['testf'];
echo( "Bottom " . $a);
}
?>
</body></html>
You can't do it in PHP, but you can't change HTML once it's fully loaded using javascript (and jquery to make it easier).
EDIT : ok I read your code a bit quickly the first time :
I don't understand the echo before the <html> tag, doesn't seem right. Also you want to give the value of a POST var to $a, so just :
if(isset($_POST['testf'])) {
echo $_POST['testf'];
}

PHP if-statement using $_POST variable doesn't seem to work. Why?

On one PHP server I have two files. One file (the name is "first.php") contains this code:
<html>
<head>
<title>First Page</title>
</head>
<body>
Please enter your password and age:
<form action="pass.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The other file ("pass.php") contains this code:
<html>
<head>
<title>Secon Page</title>
</head>
<body>
<?php
if ($fname=="Jack")
echo "You are Jack!";
else
echo "You are not Jack!";
?>
</body>
</html>
As far as I understand, if a user enters "Jack" in the first page, than the second page should be displayed with "You are Jack!" line, but it doesn't happen. Why is it so?
On your second page, instead of checking for $fname, check for $_POST['fname'] instead. I think that is all you are missing.
You probably don't have register_globals set. This is depreciated and will be removed in 6.x. So for good programming you should instead of $fname try $_POST['fname'] on your second page.
pass.php needs to look like this
<html>
<head>
<title>Secon Page</title>
</head>
<body>
<?php
if ($_POST['fname'] =="Jack")
echo "You are Jack!";
else
echo "You are not Jack!";
?>
</body>
</html>
It might help to set the post values as variables and work with that. Something like this:
foreach($_POST as $key => $value)
{
$$key = $value;
}
Then whatever is posted will be available rather than using $_POST['xxxxx'] in your logic.

Categories