I'm using a form to post data and collect it with PHP by using individual cookies after some validation..
it takes too much time to do things with the data which gets extended for more and more forms... I was thinking about improving my code with loops, functions or arrays, offered to create a map array...
share your suggestion on how should I re-write my code for more data and multiple forms which get the data exported to documents..
<?php
if(isset($_POST['send']))
// name
if(strlen($_POST['name']) < 2){
echo "error - name is too short";
}
// other validations with elseif..
else {
setcookie('001',$_POST['name']);
}
// age
if((isset($_POST['age']) && is_numeric($_POST['age']))){
setcookie('002',$_POST['age']);
}
?>
<form method="post">
<input name="name" type="text"/>
<input name="age" type="number"/>
<input type=submit" name="send" value="submit">
</form>
I think should store it as a key val pair in $_SESSION. You can infinitely add more key-val pairs without worrying much. Also it will be secure as the data won't be exposed in cookies.
Related
I'm trying to add a value to $_POST data while it gets submitted to the target page as follows:
post.php
<?php $_POST['field1'] = "Value1";?>
<html>
<head>
</head>
<body>
<form method="post" action="catch.php">
<input name="field2" type="text"/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
catch.php
<?php
foreach ($_POST as $key => $value) {
echo $key . " : ". $value;
echo "<br/>";
}
?>
but I cannot catch 'field1' on the other end. I don't want to use a hidden input field. How can I achieve that?
Thanks!
When you send the form, the $_POST data is reset and assumes only the inputs inside the form and a possible query string you may have appended to form action.
The best way to accomplish what you want is using hidden field but since you dont want it, you can append a query string to your form action:
<form method="post" action="catch.php?field1=Value1">
You're not submitting field1 anywhere. What happens is this:
post.php generates a HTML page (one that doesn't contain any reference to field1)
the user's browser renders the page
on submit, only the elements inside the form are submitted
catch.php receives the elements submitted above.
In other words, you need to get that value into your form:
<form method="post" action="catch.php">
<input name="field2" type="text"/>
<input name="field1" type="hidden" value="<?php echo htmlspecialchars($_POST['field1']) ?>"/>
<input type="submit" value="Submit" />
</form>
There is no other way to get the value into your POST data, if it's not present in the form. What you could do as a workaround is store the data in GET (size limit), session (concurrency issues - what happens when the user has two tabs open, each with different session data?), or cookies (size limit AND concurrency issues).
You can't do it this way. If you want to send the data you're trying to add to the POST there only through the users form, you are forced to also store it somewhere client side (e.g. a hidden field or a cookie). What you're doing right now is setting some value into the POST variable, but it gets overridden by the users form post (or rather the $_POST variable you're using after the form post is another instance).
What you could do instead to keep it serverside is save the value in the variable to the session of the user, then in the form post action server side get the value again (given the fact that you're using sessions). Lastly you could just store it in some table in a database, though I wouldn't do this.
Since $_POST are data sent by post method to script, you can not use it for another request directly. You need to compose and send another post request. The easiest way for you will be to use hidden input field/s.
Or you can choose another approach to make http post request, for example curl methods.
If you don't need data to be given by post method, you can save it in session, for example.
try this:
in post.php
<?php $_SESSION['field1'] = "Value1";?>
<html>
<head>
</head>
<body>
<form method="post" action="catch.php">
<input name="field2" type="text"/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
in catch.php
<?php
if(isset($_SESSION['field1']))
{
$_POST['field1'] = $_SESSION['field1'];
unset($_SESSION['field1']);
}
foreach ($_POST as $key => $value) {
echo $key . " : ". $value;
echo "<br/>";
}
?>
Make sure you have started the session.
Note: you must use hidden elements or query string as other user suggested.
EDIT: Thanks for all the helpful answers, I got it solved.
I can't really seem to find an answer to this question, and it's probably really simple.
I was just creating a page for fun where you can guess a number from 1-10. Person 1 enters a secret number, that person 2 will guess. However, I have had a lot of problems storing the $_POST from the secret number.
TL;DR I can't store the information of secretNumber into guessnumber_guessed.php file. For example look in guessnumber_guessed. First part of the if statement, if the inputNumber equals the secretNumber, it should say correct. Problem is, the variblae is undefined, how to a 'transfer the info'?
Hope you guys get my point, help is really appreciated
Here's the code:
guessnumber_welcome:
<form method="post" action="guessnumber.php">
<input type="text" name="secretNumber" placeholder="Type the secret number">
<input type="submit" name="submit" value="Send">
</form>
guessnumber.php:
<form method="post" action="guessnumber_guessed.php">
<input type="text" name="inputNumber" placeholder="Guess the secret number">
<input type="submit" name="submit" value="Guess!">
</form>
<?php
$secretNumber = $_POST["secretNumber"]
?>
guessnumber_guessed.php:
<form method="post" action="">
<input type="text" name="inputNumber" placeholder="Guess the secret number">
<input type="submit" name="submit" value="Guess!">
</form>
<?php
$inputNumber = $_POST["inputNumber"];
if ($inputNumber == $secretNumber) {
echo "<p id=\"correctAnsw\"> CORRECT! </p>";
}
else if ($inputNumber == 2) {
echo "<p id=\"wrongAnsw\">You're very close. Go up a little!</p>";
}
else if ($inputNumber==4) {
echo "<p id=\"wrongAnsw\">You're very close. Go down a little!</p>";
}
else if ($inputNumber > 10) {
echo "<p id=\"wrongAnsw\">The number is you guessed is too high. Stay within the borders!</p>";
}
else if ($inputNumber < 1) {
echo "<p id=\"wrongAnsw\">The number is you guessed is too low. Stay within the borders!</p>";
}
else {
echo "<p id=\"wrongAnsw\">This is not the number. Try a new one!</p>";
}
?>
The sessions will not help. They're user oriented. If the first person is using the page to enter a number and the second person comes after that, in the same session, on the same browser, you can use the sessions mechanism.
If you're trying to make a multi-user "game" and the two persons are with separate browsers, it means you must:
Pair the two persons somewhat (maybe a room mechanism)
Use some kind of server storage or cache (you can even use memcached for in-memory storage) to match the two persons and their answers.
I faced a similar problem trying to pass beetween two scripts some url strings for a "two-step" uploader.
In my opinion there is two solutions, depends on the level of security you want to have:
In guessnumber.php put the $_POST['secretNumber'] value in an input type="hidden"
<input type="hidden" value="<?php echo $_POST['secretNumber']; ?>">
In this way the value will be passed to the second script via POST and will be available in the $_POST array.
This method, is not safe for sensible datas, because everybody who can access the html source simply through the browser devtool can read or modify it!!
The second, and more safe, solution is to use the php session
In guessnumber.php start the php session and save the value in this way:
if ( !session_id() ) {
session_start();
}
$_SESSION['secretNumber'] = $_POST['secretNumber'];
then in guessnumber_guessed.php recover the session and get the value from there
if ( !session_id() ) {
session_start();
}
$secretNumber = $_SESSION['secretNumber'];
I strongly recommend the second solution.
Hope it helps :)
I want to create a project that save the fill up forms in previous form and insert into database using one button only. For example answer1.php and answer2.php the save button is in the answer2.php i want to fetch data from answer1.php and save to databse same as in answer2.php
this code below insert data in one form only
$query = mysql_query("INSERT into holiday (holiday_no,holiday_name, status,campaign_name,holiday_type, createdBy, holiday_date, createdDate)
VALUES('$holiday_no', '$id','$status','$campaign_name','$hol', 'System','$date','$createdDate')") or die(mysql_error());
echo "Data has been saved with holiday name";
Not quite sure what you're asking for ...but giving it a try ;-) :
You can put the key-value pairs the first script receives into the next form so they get transmitted once again to the second script. E.g. if in the first step something like category=foo and country=bar gets transmitted write out a form that looks like
<form method="POST" action="answer2.php">
<p>
<input type="hidden" name="category" value="foo" />
<input type="text" readonly="readonly" name="country" value="bar" />
<!-- all the other things you want to add to the form -->
<input type="submit" />
</p>
</form>
But keep in mind that a) you need to encode the values properly for html output, otherwise your scripts are vulnerable for injection attacks, see http://docs.php.net/htmlspecialchars
and b) your second script can't "be sure" that the values haven't been altered or even transmitted to the first script at all; if you need that (e.g. for some transaction mechanism) you need something else like e.g. http://docs.php.net/features.sessions
Use hidden fields, a session, or a temporary table.
<?php
if (empty($_REQUEST)) {
echo '<form action="', $_SERVER['PHP_SELF'], '">
</form>';
} elseif (empty($_REQUEST['some_field_from_your_second_form']) {
// Do the second part of your form
} else {
// Do the final submission
// Sanitize the values
// Insert in the database
}
This is a "best practice"/"most efficient" question. I have a large form (20+ fields). Form post into one large MySQL table.
No I can't break up the form and no, I can't break up the table (its being used to hold measurements); used by admin sales reps. Also, I don't want to use Javascript.
I know I can do this:
HTML
<form action="etc.php" method="post">
<input type="text" name="neck" value="">
<input type="text" name="arm" value="">
<input type="text" name="back" value="">
<input type="text" name="chest" value="">
<input type="text" name="legs" value="">
<submit button>
PHP
<?
$_POST['neck'];
$_POST['back'];
$_POST['arm'];
$_POST['chest'];
$_POST['legs'];
$postMeasurements = "INSERT INTO measurements (etc, etc, etc,) VALUES (etc, etc, etc) WHERE etc='etc'; query ($postMeasurements);
?>
But is there a faster way? Instead of having to declare each individual post, simply just run a loop that takes all the data post and inserts into the table. Even if the data has be in the same order of the columns of the table or if the input names have to be the same as the table column names is fine by me; I am just getting tired have to keep writing all these $_POST variables into.
Second question: What is the best way to hold this data in case of an error? As it stands now, I hold everything in $_SESSION (one session variable for each input), then redirect back to the form page if there is an error with an error message. then echo each $_SESSION variables as that inputs value.
Thanks,
if the fields as the exact names as the field names. post can only have the fields and nothing else
//if $_POST has the form then, also this is very unsafe because there is no injection prevention too
$sql = "INSERT INTO table (" . implode(",", array_keys($_POST)) . ")"
. "VALUES ('" . implode("','", array_values($_POST)) . "')";
You can directly use $_POST['foo'] inside your query, and need not declare :) .
holding the data could be in session, or inline cache, if you have huge data, its better to use some cache in server, and onload of the form, it retrieves the data from server based on SESSION_ID
Have the page post to itself.
Then do something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
// validate and insert post data
header("Location: $successUrl");
exit();
}
?>
<form action="etc.php" method="post">
<input type="text" name="neck" value="<?= $_POST["neck"]?>">
<input type="text" name="arm" value="<?= $_POST["arm"] ?>">
....
Let me explain.
Normally when hidden fields are passed from a form to the page specified in the action of the form, those hidden fields can be accessed on the processing page like so:
The Form:
<form action="process.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="hidden" name="loginTime" value="1:23PM" />
<input type="hidden" name="userIp" value="173.23.22.5" />
<input type="submit" name="submit" value="Submit" />
</form>
Processing Page (process.php):
<?php
if isset($_POST['submit']) {
echo $_POST['username'];
echo $_POST['loginTime'];
echo $_POST['userIp'];
}
?>
You see how I had to call the two hidden fields by name and individually. Is there any way I can call all hidden fields that are passed to a page from a form all at once despite what the field names of those are or how many there are?
In other words how do I make PHP do this:
// echo the contents of all hidden
fields here (if there were any)
EDIT
Additional info:
The form is designed in such a way (not the one above of course) that field names will be of the following sort:
product_name_1
product_quantity_1
product_price_1
product_name_2
product_quantity_2
product_price_2
and so incremented so on...
Depending on the user action there can be 3 hidden fields or thousands, there are no limits.
Make an array of valid hidden field names, then iterate through $_POST and if the $_POST field name is in the array of valid field names, echo them.
$valid = array('first_name', 'last_name');
foreach ( $_POST as $key => $value ) {
if ( in_array( $key, $valid ) ) {
echo $_POST[$key];
}
}
PHP does not care whether the field was hidden or not, HTTP doesn't tell PHP how it appeared on the website.
The closest thing I would come up with was saving all names of the hidden fields inside an array and echoing them all in a loop.
You can try the following:
<form action="process.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="hidden" name="group_hidden[loginTime]" value="1:23PM" />
<input type="hidden" name="group_hidden[userIp]" value="173.23.22.5" />
<input type="submit" name="submit" value="Submit" />
</form>
And then print it:
echo htmlspecialchars(print_r($_POST, true));
This might give you a clue about how to solve this.
there's no way to tell the type of the input built-in, so instead you'll need to come up with a way to identify the ones you want yourself. This can be done either by coming up with a special naming scheme, or by storing a list of the names of the hidden fields in another field. I'd recommend the former option, since you don't have the risk of losing data integrity somehow. Look at using array_filter to parse through the array to get the specially-named fields out.
Maybe, assuming that your hidden fields will be in sequence (i.e. 1,2,3 and not 1,2,4) following all of the end users' actions (adding and taking away fields), you could try something along the lines of
$i = 1;
while(isset($_POST["product_name_$i"]))
{
echo $_POST["product_name_$i"];
echo $_POST["product_price_$i"];
$i++;
}
Or something along those lines?