How to fill PHP form with data from URL? - php

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

Related

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';
}
}

Why isn't my PHP POST request going through?

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.

PHP form - on submit stay on same page

I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)

PHP - Dont go to next page if input is wrong

I'm working with a .html and a .php. In the default.html the user must enter some info and when the button is clicked the html does a post to the default2.php.
In default2.php the data is checked and if it's correct it redirects the user to another page. The problem I'm having is when the data entered is wrong.
I'm having two issues here:
When the data is wrong I'm redirecting the user to the default.html, because if I don't do that, it will stay in default2.php and default2.php has nothing important for the user to see. I don't know if this is the best way to do this.
When the data entered is wrong, I want an echo message to the user in default.html. But I don't know how to trigger this from default2.php.
How can I solve these two issues?
Thanks...
default.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>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP4</title>
<style type="text/css">
body {
background-color: #CCC;
}
</style>
</head>
<body>
<p> </p>
<form id="form1" name="form1" method="post" action="default2.php">
<p>
<label for="textfield1">User Name</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="textfield2">Password</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="submit" name="button1" id="button1" value="Submit" />
<br />
<br />
<label id="label1">
</label></p>
<p> </p>
</form>
<p> </p>
</body>
</html>
default2.php:
<?php
require 'connection.php';
if (isset($_POST['button1'])) {
$username_v = $_POST['username'];
$password_v = $_POST['password'];
// Then you can prepare a statement and execute it.
$stmt = $dbh->prepare("CALL login(?, ?)");
$stmt->bindParam(1, $username_v, PDO::PARAM_STR);
$stmt->bindParam(2, $password_v, PDO::PARAM_STR);
// call the stored procedure
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
}
else
{
header("Location: default.html");
}
}
?>
Just add some parameter to
header("Location: default.html?test=failed");
And in html use Javascript to display something sensible when variable test is set to failed. You can find a tutorial how to get value of url parameter with javascript here.
Hope that helps.
Other than that you can use PHP in your default.html and perhaps even AJAX request to do validation without leaving the page and highlighting validation errors.
Personally, I don't like to expose states like "error" and "invalid" to the user using a query string. In this situation, I would merge the two files in one single PHP file, with the PHP code at the top and the HTML code at the bottom.
The if statement in the PHP code would be:
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
exit;
}
else
{
$error = true;
}
And down in the HTML where you want to display the message:
<?php
if( isset( $error ) && $error )
echo 'You have entered the wrong data!';
?>
Ofcourse, in the form element, you would have to remove action="default2.php".
If you prefer separating the logic and the markup, you could change default.html to for example template.php and include it at the end of your controller php file.
I just don't like the idea of an extra page without any content that only acts as a redirector.
If you made default.html a PHP file, you could pass a variable via the URL, this would then allow you check if this variable has been passed using $_GET[]and show the user a message.
So for example, if you forwarded the user to
default.php?error=1
On the default page, you could have a segment of code such as
if (isset($_GET['error'])) {
echo "Show user a message here";
}

how to pass POST variable by links to own pages?

Hi i wannna get variable $_POST by link to self pages. Example :
<?PHP
$var = 'PIG';
echo "<a href='test.php?var=$var'>link</a>";
if (isset($_POST['var']))
{
echo $_POST['var']);
}
?>
it links to own pages. (test.php)
It not works, who can help me please. Thanks
A link cannot POST data, only GET.
In contrast to the GET request method where only a URL and headers are
sent to the server, POST requests also include a message body. This
allows for arbitrary length data of any type to be sent to the server.
Basically, a POST requires two requests, 1) the server receives the "normal" request, with an extra header value indicating that more data needs to be sent. At that point, the server sends an acknowledge and 2) the client sends the POST body. This behavior cannot be achieved only with a link.
However, there are solutions to this and I have seen some technique, among others, outputting a form with an autosubmit, something like
<form name="frm" method="post" action="http://your.domain.com/path/to/page.php?param1=1&param2=2">
<input type="hidden" name="foo" value="bar" />
</form>
<script type="text/javascript">
document.forms["frm"].submit();
</script>
which would result into calling page.php with these arguments
$_GET = array('param1' => '1', 'param2' => '2');
$_POST = array('foo' => 'bar');
Note that this is a simple "redirect" method, but you can create <a> elements to actually trigger some hidden form like that instead of using the standard link. (untested code)
A simple link
<script type="text/javascript">
function dopost(url, params) {
var pe = '';
for (var param : params) {
pe += '<input type="hidden" name="'+param+'" value="'+params[param]+'" />';
}
var frmName = "frm" + new Date().getTime();
var form = '<form name="'+frmName+'" method="post" action="'+url'">'+pe+'</form>';
var wrapper = document.createElement("div");
wrapper.innerHTML = form;
document.body.appendChild(wrapper);
document.forms[frmName].submit();
}
</script>
This is probably what you need, actually.
Items in the query string are available via $_GET, not $_POST, since they are not actually POSTed. If you want to POST then you must either use a form with a method of post, or you must perform a XHR as POST.
Unfortunately, you really can't do that. If you need to use an anchor to submit a value, then you will need to access the variables through $_GET or $_REQUEST.
If it has to be a $_POST (if you are set in that design decision, because $_GET actually makes a lot more sense there), you can use a form and the style the submit button to make it look very much like a link. Put this code in a text editor and check it out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
.button {border:none;background-color:#FFFFFF}
.button:hover{ color:blue; }
</style>
</head>
<body>
<form action="test.php">
<input type="hidden" name="var" value="<?php echo $val; ?>" />
This kinda looks like a link:
<input type="submit" value="link" class="button" />
</form>
</body>
</html>
If you have multiple links and you don't want to rewrite all of them, just add one fake form like this:
<form id="fakeForm" method="post">
<input type="hidden" name="post_key" value="post_value" />
</form>
and set up proper jquery:
$('a').click(function(event){
event.preventDefault();
$('#fakeForm').attr('action',$(this).attr('href')).submit();
});
In this case, when you click on any link, the landing page receives the post_value variable.
Note that if the link is clicked with other than left click (or js is disabled), the link works properly, but the value isn't passed!
This code below demonstrates T30's idea works.
My rationale for passing via $_POST is to prevent certain variables from being exposed in the url which is accomplished here. However, they would still be exposed via "view source".
<?php
/*
This demonstrates how to set $_POST from a link in .php without ajax based on the idea from http://stackoverflow.com/a/27621672/1827488. The rationale for doing so is to prevent certain variables ('userid') from being exposed in the url via $_GET. However, there does not seem to be a way to avoid those variables being exposed by 'view source'.
*/
echo "<!DOCTYPE html><html lang='en'><head><title>Test Data Link</title></head><body>";
// only one hidden form
echo "<form class='hiddenForm' method='post'>
<input class='hiddenFormUserid' type='hidden' name='userid'/>
</form>";
// as many links as you need
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=101>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=101>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=102>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=102>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=103>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=103>Followers</a></p>";
echo "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>";
echo "<script type='text/javascript'>
console.log('jq');
$('.hiddenFormLink').click(function(e){
console.log('data-userid=' + $(this).attr('data-userid') + ', value=' + $('.hiddenFormUserid').val());
e.preventDefault();
$('.hiddenFormUserid')
.val($(this).attr('data-userid'));
$('.hiddenForm')
.attr('action',$(this).attr('href'))
.submit();
});
</script>";
if (isset($_GET["following"]) || isset($_GET["followers"])) {
if (isset($_GET["following"])) {
echo "followed by ";
} else {
echo "followers of ";
}
if (isset($_POST["userid"])) {
echo $_POST["userid"]."<br>";
} else {
echo "no post<br>";
}
} else {
echo "no get<br>";
}
echo "</body></html>";
$_POST["userid"] = "";
?>

Categories