Is there a difference if a parameter of a POST-form is placed in the query string:
<form action="mysite.com/index.php?myparam=myvalue">
...more inputs here
</form>
and placing it as a hidden input?
<form action="mysite.com/index.php">
<input type="hidden" value="myvalue">
...more inputs here
</form>
I'm using Joomla, but it's totally unrelated actually. I see that there's a bit of "here and there" in their tutorials, but does it actually matter? What are the implications if I use either one?
NOTE: I forgot to place action=post in the forms which has changed the question totally. however, with the arrival of interesting answers which answered more than just my question, I decided to leave them as is.
Yes, there is a difference, technically and conceptually. The way that difference affects you depends on the application server that handles the request (well, and on your preferences, of course).
Technical difference:
In most application servers, the source of a parameter (URL or FORM) determines where they end up. In PHP, url parameters go in the $_GET and form fields in the $_POST superglobals, respectively. If you don't care about the technical difference, there is a $_REQUEST superglobal for your convenience.
Conceptional difference:
It is most logical to make a difference between two types of request parameters:
Such that are required to render a page, i.e. they don't change anything in the database if you send the request again.
Such that change the database, i.e. are destructive (they are the reason why browsers ask if you are okay with posting a page again if you hit refresh).
The former ones are called idempotent and should be transferred via GET. A good example would be a search string or a record ID. No matter how often your hit refresh, the database stays untouched.
The other kind of parameter is data that should be stored in the DB. It would be destructive in the sense that it actually changes database contents. These parameters should be transferred via POST.
By the way, this is also a good way to decide if your form should be method="GET" or method="POST": Whenever form input is idempotent on the database, use a GET form. For example a user search form should be GET, a user preferences form should be POST.
Now you could argue that in your case the record ID is idempotent, but the other bits of information in your form are not. In this case I find it most idiomatic to use
<form action="mysite.com/index.php?id=1234" method="POST">
<!-- ...more inputs here -->
</form>
since a GET mysite.com/index.php?id=1234 would request that very record.
There is no need to do it that way, though - of course you can post the ID as a hidden input.
Two things you should be aware of, though:
In this case the HTTP server logs would not show evidence of which record the user posted to (if you care for that).
This kind of separation only works for POST forms. GET forms ignore the parameters in action attribute, you must specify all of them in as hidden input fields.
for the POST form there is no difference.
for the GET form the entirely new query string would be composed of the form fields, eliminating all existing values - so, never use query string for the GET forms, use hidden fields instead.
There IS a difference because the GET parameters passed to the action attribute are dismissed. You should use hidden fields.
If you specify the method attribute in your form and set its value to "POST", then you will have to parse both the GET and POST parameters.
I used the following file to test (name it "testget.php"):
<!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" xml:lang="en" lang="en">
<head>
<title>Test GET</title>
</head>
<body>
<p>
<?php
if( ! empty( $_GET ) )
{
print_r( $_GET );
}
if( ! empty( $_POST ) )
{
print_r( $_POST );
}
?>
</p>
<p>No method attribute</p>
<form action="testget.php?foo=bar">
<input type="hidden" name="bar" value="foo" />
<input type="submit" value="Submit" />
</form>
<p>method="get"</p>
<form action="testget.php?foo=bar" method="get">
<input type="hidden" name="bar" value="foo" />
<input type="submit" value="Submit" />
</form>
<p>method="post"</p>
<form action="testget.php?foo=bar" method="post">
<input type="hidden" name="bar" value="foo" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Output:
No method attribute:Array ( [bar] => foo )
method="get":Array ( [bar] => foo )
method="post": Array ( [foo] => bar ) Array ( [bar] => foo )
Related
I want to make an HTML (or php maybe?) page that constructs a new HTML page based on input parameters the user gives to a drop-down box. I just don't know how you handle the input.
Here's my HTML:
<html>
<body>
<input type="number" min="1">
</body>
</html>
Yes I know it's not the full HTML page, but I just want to focus on the <input> tag. I know you probably have to set it equal to a PHP variable maybe?
I want it to generate a different HTML page that looks like this:
<html>
<body>
<p>You have chosen: $input </p>
</body>
</html>
I might be asking this all wrong, but I hope it makes sense what I'm looking for. I need to know how to handle the user input. I couldn't find a thread that discusses this. Do I need to generate a new HTML file? Or just override the current one and maybe have a reset button? I'm so confused.
In the simple case, you'll have two pages: your form and your result page. You can send data from the form page to the results page with one of two methods: GET or POST.
GET means that the data you're sending gets put in the page URL. This is useful because then you can link to a specific version of the results page, but potentially dangerous because you don't want to put sensitive data in the URL bar.
POST means that the data is sent with the HTTP request in the background. This is preferable for something like a password.
The GET and POST data can be read by nearly any server-side language and used to generate HTML on-the-fly. The example below uses PHP.
The form page doesn't necessarily need any server-side code, just basic HTML. Here's a simple example:
<!DOCTYPE html>
<html>
<form method="GET" action="my_result.php">
<input type="text" name="my_value">
<input type="submit">
</form>
</html>
Your second page (the results page) should bear the name that you specified in the form's action attribute. This is the page which will need server-side code. So here is an example my_result.php:
<!DOCTYPE html>
<html>
<p><?php echo $_GET['my_value']; ?></p>
</html>
Obviously, my_value can and should be replaced by whatever you want to call your data, as long as the name attribute of the input element matches the key in the PHP.
This example uses the GET method. You can use POST by changing the method attribute of the form and using $_POST instead of $_GET (if you are using PHP).
If you use $_REQUEST rather than $_GET or $_POST, it finds a value that was passed via either GET or POST. This is usually less safe than explicitly stating how your value was passed.
Addendum: Some servers are configured to disallow you from directly using the values of php superglobals such as $_GET, $_POST, and $_REQUEST for security purposes. That is because you really should always sanitize user input before using it in an application. The type of sanitization required depends on the type of input and how it is being used, and is well outside of the scope of this question. For this purpose, php provides the filter_input function.
The sanitization filter is an optional parameter for the filter_input function, so if you really want to use the data unfiltered, you can simply omit it (but know that this is dangerous). In this case, you can replace all instances of $_GET['my_value'] in the above code with filter_input(INPUT_GET, 'my_value').
This is not a tutorial, but I guide you to some important points:
You can get user input with html by using form element. read more about form and methods of form (GET and POST).
Then, how can you print user input when submitted by user? php supports both (GET and POST) using $_GET and $_POST with input name as key.
Dealing with user-input needs extra care because of security. user might submit malicious content that later attacks you or another user.
Try like below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
if ($_POST) {
echo "<h3>You have selected ".$_POST['number']."</h3>";
} else {
echo '
<form method="post" action="">
<select name="number" id="number">
<option value="1" >1</option>
<option value="2" >2</option>
<option value="3" >3</option>
</select>
<input type="submit" value="submit">
</form>
';
}
?>
</body>
</html>
To handle a user input you have to use forms
<form action="action_page.php">
<input type="number" min="1 name="my-number">
<input type="submit" value="Submit">
</form>
After user set number and press submit button, you will get the value in action_page.php in $_REQUEST['my-number']
I'm facing problem in inserting HTML label to database and found no way to do so. My code is as under
<html>
<body>
<form name = "myForm" >
<label name = 'q1'>Question 01: what Jorge do according to the story</label>
</form>
<?php
require "connection.php";
$qst = $_POST['q1'];
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
?>
any help will be appreciated please.
You have a slew of problems here. First let's talk about the things that are actually preventing this from working.
First, you need to set the method property of the <form> element to POST to have the form perform a POST action upon submittal instead of the default GET action.
<form name="myForm" method="post">
Note, that it is usually considered good form to also specify the action property of the form, though in this case the default behavior of posting to the currnet URI just happens to work for you.
Second, you need to actually create an input field in the form. This is where the data that is posted is input:
<label for="q1">Question 01: what Jorge do according to the story?</label>
<input type="text" name="q1" />
Third, You need a submit button to actually make the form POST:
<input name="submit" type="submit" value="submit" />
Now, let's talk about the stuff that should be fixed that doesn't actually prevent this from working, but just represents good programming practice.
First, you should not be using mysql_* functions. They are deprecated. I would suggest mysqli or PDO as widely used alternatives.
Second, you have a significant vulnerability to SQL injection. You should NEVER use user input data without validating and sanitizing it. This means you should probably check to see if a value was even POSTed (not an empty string) before trying to do the insert and then you need to escape the value before using it in SQL, or better yet, learn how to use parametrized prepared statements which prevents the need for input escaping.
Third, I would recommend getting in the habit of putting your code logic at the beginning of your script (before HTML) output. In your case this means moving the logic where you read in the PST content and perform the database insert before the HTML. WHy? Because this allow you to do things like conditionally print out error messages if the user did not provide input or to otherwise change the page in response to the POST. This also help build a good habit in that, when you start doing more complex things in PHP, you might need to do things like redirect users from one page to another, or totally separate out the logic form the display into separate files. This is not possible with code stuck at the end of the HTML output.
$_POST variables do not correspond to label elements, they correspond to input elements. The key to your post array is the name of your input element.
<input type="text" name="mytext" />
After post will be $_POST['mytext']
However, you're vulnerable to SQL Injection. You should not be using mysql_query() but rather PDO or Mysqli with prepared statements, but if you insist on using it, escape it first with mysql_real_escape_string()
$qst = mysql_real_escape_string($_POST['q1']);
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
Fred made a good point in the comments though. This bit of code is going to execute the first time you load the page before the form is submitted and throw an error (or warning) because $_POST['q1'] doesn't exist yet. You'll want to make sure it does exist before doing things with it.
if(!empty($_POST['q1'])){
$qst = mysql_real_escape_string($_POST['q1']);
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
}
Further, you need to tell the form where to submit to and what method to use:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for = 'q1'>Question 01: what Jorge do according to the story</label>
<input type='text' name='q1' value='' />
</form>
BTW, label does not have a name attribute, it has a "for" attribute.
Also, <form> elements use "GET" by default and submit to the current page if an action is not set, so it's technically not necessary to even have the action set in this case, but it's good practice.
You need add input field for your form and change form sumbit method. By default it's "GET", so you can't have input value in $_POST.
Or you can get input value from $_GET.
<html>
<body>
<form name = "myForm" method="post">
<label for = 'inp'>Question 01: what Jorge do according to the story</label>
<input type="text" name="q1" id="inp" />
<input type="submit" value="Submit">
</form>
<?php
require "connection.php";
$qst = $_POST['q1'];
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
?>
And also you need to have sumbit input field to submit form or can sumbit it with js or on keyup enter key.
<input type="submit" value="Submit">
What I need is this:
user loads the page (inputs are null)
user gives some input and submits
the inputs have their new values
user navigates back
the inputs have their previous values
My php file looks like this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form id="formTest" name="formTest" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" autocomplete="off">
<select id="selectTest" name="selectTest">
<option value=0 <?php if(isset($_POST['selectTest']) && $_POST['selectTest']==0){echo 'selected=\'selected\'';} ?>>Select an option...</option>
<option value=1 <?php if(isset($_POST['selectTest']) && $_POST['selectTest']==1){echo 'selected=\'selected\'';} ?>>Option 1</option>
<option value=2 <?php if(isset($_POST['selectTest']) && $_POST['selectTest']==2){echo 'selected=\'selected\'';} ?>>Option 2</option>
</select>
<br/>
<input id="inputTest" name="inputTest" type="text" value="<?php if(isset($_POST['inputTest'])){echo htmlentities($_POST['inputTest']);} ?>" />
<br/>
<input type="submit" value="OK" />
</form>
<?php
print_r($_POST);
?>
</body>
</html>
As you can see the form "remember" its data after a submit. The problem occurs at this point when the user hits the browser's Back button. Although the POST array has the values of the previous state, the browser fills the fields with the data of the next state (with the ones after the submit).
Although I could managed this problem in Chrome and Firefox with turning off the autocomplete property of the form, but this had no result in IE8.
Any suggestions would be much appreciated!
It sounds like you want the form always to display the values you echoed in your PHP? A quick-and-dirty fix is to reset the form when the page loads:
<body onload="document.forms[0].reset();">
You might need to update that onload attribute for different page structures or you could do it more elegantly if your actual application used jQuery and you give the form an ID.
I believe there is a way to turn off autocomplete/history per-field in IE also. I'd have to google that. Edit: Okay, I did... looks like you have the form attribute IE is looking for. I don't think this is actually an autocomplete issue so much as the back button is trying to recreate the last state of the page... including changes the user made, specifically filling out fields.
Here's the jQuery approach to resetting the form when the document is ready (include back button)... strangely, jQuery hasn't implemented the reset() method of a form, so the [0] gets you the raw DOM element. Add these lines to your head; substitute a local jquery on your server if available and preferred:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function(){$("#formTest")[0].reset();});
</script>
If you run them through some sort of persistent struct (session scope comes to mind) , you can set that to a conditional on your form. So if it doesn't see the form variable (which is what post is for passing and interrogating form stuff). So the statement would replace the post isset and instead check if the struct 'session' (or some other scope) exists and if so populate. Make sense? I hope this helps.
I was wondering if my code below is even correct, I've been having numerous errors with this, but am not sure if the problem really exists here. The code is below:
The user will click 'Exit Group'.
<p class="logout"><a id="exit" name="logout" href="#">Exit Group</a></p>
The code that should be execute when 'Exit Group' is clicked is below:
if(isset($_GET['logout'])){
//CODE TO BE EXECUTED
}
However, the code I am trying to execute when the user clicks 'Exit Group' is not even being executed. There is nothing wrong with the code within the braces, as numerous people have checked it. But I was wondering if my problem may lie in the code above? Thank you.
If you click the link, nothing happens because the URL only contains the fragment identifier #. Not even a GET request will be issued.
You use this kind of link normally to jump to an element inside the page (e.g. Top to jump to an element with ID top). This is completely handled in the browser.
And if you only put the fragment identifier there, just nothing will happen. This is very often used if the link should execute some JavaScript and should actually not link to something else.
You are testing the $_POST array at the server side. But this array only contains elements, if you initiate a POST request by a form. That means you need to create a form with a submit button, e.g.:
<form action="" method="POST">
<input type="submit" name="logout" value="Exit Group" />
</form>
Here comes the name attribute into play, which will be the key in the $_POST array. But assigning this on a normal link will have no effect.
You could do it also with the link, but with a GET request this way:
<a id="exit" href="?logout=1">Exit Group</a>
<!-- ^-- parameter must be part of the URL, name has no effect -->
and
if(isset($_GET['logout'])){
//CODE TO BE EXECUTED
}
Note that you have to pass a parameter logout it here.
It seems you have mixed up GET and POST requests. If you have a form, the name s of the form elements will be transmitted as parameters to the server. That means given this form:
<form method="POST">
<input type="text" name="foo" value="" />
<input type="text" name="bar" value="" />
<input type="submit" name="send" value="Send" />
</form>
if the user clicks on the submit button, the $_POST array at the server side will have the keys:
$_POST['foo']
$_POST['bar']
$_POST['send']
This does not work with links though. A click on a link will create a normal GET request, and here, the parameters must be part of the URL, appended after a question mark ? and separated by an ampersand &:
Link
will result in
$_GET['foo']
$_GET['bar']
$_GET['andMore']
You probably should read about the HTTP protocol.
a isnt a form control. it needs to be an input or select if it's within a form.
For manual linking, do href="/page?logout"
You're using a regular hyperlink, no form will get posted. you need a submit button of some kind in a form with method="post" to do that. regular links just result in GET requests and nothing will ever be posted that way.
edit: added simple example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Form test</title>
</head>
<body>
<?if ($_SERVER['REQUEST_METHOD'] == 'POST'):?>
<pre><? print_r($_POST)?></pre>
<?endif;?>
<? // $_SERVER['REQUEST_URI'] holds the current URL, so we know that ?>
<? // we'll end up back in this file when the form is submitted. ?>
<form method="post" action="<?= $_SERVER['REQUEST_URI']; ?>">
<input type="text" name="textbox"
value="<?= isset($_POST['textbox'])?$_POST['textbox']:'Type something' ?>" />
<input type="submit" name="submitbutton" value="Submit" />
</form>
</body>
</html>
$_POST will only be filled if you use a form with method=post.
Yes. A POST and a GET are two different things ;)
if(isset($_GET['logout']))
This <a id="exit" name="logout" href="#"> should be <a id="exit" href="?logoff=true#">.
Then logoff will be in the $_GET array.
This seems so simple but I can't remember how I've done it before.
Using PHP I'm posting a form from mysite.com/?x=y and want the resulting page to be mysite.com/?x=y&formx=formy...
Options I've tried don't quite give the desired result:
action - setting action="?x=y" clears the get variables if method="get" in place of those in the form. Prior knowledge of the get variables are also required.
method - although it seems logical to set method="get", this passes the form variables but clears any placed in action. Setting method="post" retains the current get variables but doesn't add the form variables/values.
Hidden field(s) - All get variables/values can be in hidden fields with method="get". This requires prior knowledge of the get variables and a lot of duplication if there are a lot of variables or forms. This so far is the closest solution.
Just set the form's "method" attribute to "get" instead of "post".
Example:
<form action="?x=y" method="get">
<input type="text" name="query" size="20">
<input type="submit" name="submit" value="Go">
</form>
I suppose you could :
either pass those variables as <input type="hidden" name="x" vaue="y" /> in your form.
or, maybe this might work : use "mysite.com/?x=y" as action for your form : with a bit of luck, those parameters will remain when the browser will post your form -- you should try, but it might work.
Of course, if you want those parameters to appear in the URL of the destination page, you'll have to use the GET method for your form.