how to add input to a variable? - php

I have this form
<form action="process.php" method="post">
Team Name: <input type="text" name="teamname" />
<input type="submit" />
</form>
and this is my php code
$teamname = $_POST['teamname'];
$namelist = "Lakers";
so let's say two people have submitted their team names as Spurs and Rangers
so how do I make the namelist like this and grow as more people submit their team names..
$namelist = "Lakers, Spurs, Rangers";
I have done it in array_push with arrays, but technically i can't call them.

you need to save the names to file/database.
variable save in the memory of the machine and deleted after the scripts done.
$names = array(); // empty array
$names[] = $_POST['teamname']; // add the $_POST['teamname'] to the array
var_dump($names); // prints the names array.
// now the script done, and all the data in the variables will flush from the memory.

You can use array to solve this issue
<?php
$teamname = $_POST['teamname'];
$namelist = $array("Lakers");
array_push($namelist,$teamname);
print_r($namelist);
?>

using database is a simple solution.
but if you still not like to use database in this situation, you can save the variables as a session or cookie variable. it will remain after page refresh.

Related

Store _POST into variable to use with Page Data [duplicate]

I'm making a php script that stores 3 arrays: $images, $urls, $titles based on the input data of the form within the php file.
I want to print the values of these arrays in the first part of the page and then to pre-fill the form's input fields with the value of the arrays. Also when a user modifies an input field and clicks on "Save" the page should reload with the modfied version.
My problem is that on each call of the php file in a browser the value of the variables gets deleted. Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?
<?php
//save the arrays with the form data
$images = array($_POST["i0"],$_POST["i1"],$_POST["i2"],$_POST["i3"]);
$urls = array($_POST["u0"],$_POST["u1"],$_POST["u2"],$_POST["u3"]);
$titles = array($_POST["t0"],$_POST["t1"],$_POST["t2"],$_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Store the variables in a PHP session.
session_start();
$_SESSION['images'] = $images;
Then on next (or any other) page, you can retrieve the values as:
session_start();
$images = $_SESSION['images'];
Changing the scope of the variables to a larger scope, might do the trick. Also, check if you have a post request before updating the values.
<?php
if(sizeof($_POST) >0)
{
//UPDATE VALUES
}
?>
If you want a permanent storage of state, between different pages, you should use sessions, by putting session_start(); in the start of your script. After this, every variable $_SESSION[$x] will be persisted, and will be available to your scripts.
However, in this particular case, answering your question: "Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?", it is easier to just use the $_POST variable if it exists already:
<?php
if(!$_POST){
$_POST = array();
foreach(array("i0","i1","i2","i3") as $i) $_POST[$i]="";
foreach(array("u0","u1","u2","u3") as $i) $_POST[$i]="";
foreach(array("t0","t1","t2","t3") as $i) $_POST[$i]="";
}
foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
//save the arrays with the form data
$images = array($_POST["i0"], $_POST["i1"], $_POST["i2"], $_POST["i3"]);
$urls = array($_POST["u0"], $_POST["u1"], $_POST["u2"], $_POST["u3"]);
$titles = array($_POST["t0"], $_POST["t1"], $_POST["t2"], $_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Note: this line foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
should be enough to protect you from basic XSS attacks.
Note also that in general, it is best to follow the pattern of reloading pages with GET after POST, which makes you less susceptible to form resubmitions, in which case using sessions for storage is the better solution.
What brought me here was somewhat different kind of beast. I had problem with subsequent post request from AXIS IP camera and needed to preserve last file name across requests. In case that someone stumble here looking for some way to cache variables and SESSION is not an option maybe should look at Alternative PHP Cache:
Note: Unlike many other mechanisms in PHP, variables stored using
apc_store() will persist between requests (until the value is removed
from the cache).
http://php.net/manual/en/book.apc.php
Use sessions: http://php.net/manual/en/function.session-start.php
You can use sessions to store values and write rules to refill form fields after validations on data submit. Also function isset() is very helpful to avoid "not defined" errors.
The solution you are looking for is the session. Use $_SESSION to store value of Your variables. For example, at the end of script:
$_SESSION['images'] = $images;
and in form's input:
<input name='i".$x."' type='text' value='".(isset($_SESSION['images']) ?
$_SESSION['images'] : '')."'>

no values in my string from an imploded post array? PHP

Started learning PHP today so forgive me for being a noob. I have a simple HTML form where the user inputs 4 strings and then submits.
HTML form
<html>
<head>
<title>EMS</title>
</head>
<body>
<h1>EMS - Add New Employees</h1>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<table>
<tr><td>Enter a NAME:</td><td> <input type="text" name="name"></td></tr>
<tr><td>Enter a PPSN:</td><td> <input type="text" name="ppsn"></td></tr>
<tr><td>Enter a PIN :</td><td> <input type="text" name="pin"></td></tr>
<tr><td>Enter a DOB:</td><td> <input type="text" name="dob"></td></tr>
<tr><td></td><td><input type="submit" value="Add New Employee" name="data_submitted"></td></tr>
</table>
</form>
</html>
I want to implode the 4 elements in the $_POST["data submitted"] array to a string.
PHP
<?php
if (isset($_POST['data_submitted'])){
$employee = implode(",",$_POST['data_submitted']);
echo "employee = ".$employee;
}
?>
Why is it that when I run the project, Input the 4 strings into the form and submit that there is nothing contained within the employee string when its outputed? There is however a value in the employee string when I just implode the $_POST array like so without 'data_submitted'.
$employee = implode(",",$_POST);
The output of the $employee string is now - employee = will,03044,0303,27/5/6,Add New Employee
It contains the name,pps,pin,dob and this ADD New Employee value?
How do I just get the $employee string to contain just the name,pps,pin and dob from the $POST_[data_submitted] array?
If you wish to implode the submitted data, then you need to refer to the specific items, as follows:
<?php
$clean = [];
if (isset($_POST['data_submitted'])){
// one way to deal with possibly tainted data
$clean['name'] = htmlentities($_POST['name']);
$clean['ppsn'] = htmlentities($_POST['ppsn']);
$clean['pin'] = htmlentities($_POST['pin']);
$clean['dob'] = htmlentites($_POST['dob']);
$employee = implode(",",$clean);
echo "employee = $employee";
}
Never use submitted data without first checking to make sure that it is safe to do so. You need to validate it. Since the OP doesn't specify what kind of data the named inputs "ppsn", "pin", "dob" pertain to, this example does a minimum of validation. Each input might require more or something different.
Whether you're new or familiar with PHP, it is a good idea to frequently read the online Manual.
First, you need to know that php will treat value in the format: value="value here" as string.
So, calling implode(",",$_POST['data_submitted']); will return Add New Employee as declared here: <input type="submit" value="Add New Employee" name="data_submitted">.
From your question:
How do I just get the $employee string to contain just the name, pps, pin and dob from the $_POST[data_submitted] array?
Solution
1. Unset the <code>$_POST['data_submitted']</code> index in the $_POST super global variable
2. Implode it
// Unset the $_POST['data_submitted'] index
$post_data = unset( $_POST['data_submitted'] );
// Format the post data now
$format_post_data = implode( ",", $post_data );
// Escape and display the formatted data
echo htmlentities( $format_post_data, ENT_QUOTES );

Array and loop PHP

I'm really new new to php. I consider myself alright at Java, but wanted to get more into web stuff. I like HTML and CSS well enough, but I'm having a lot of trouble with php.
I'm writing a really basic php code. I want it to get info from a user (via form) and add it to an array in php (POST). I then would like to store the array as a session variable and write a for loop that prints out each index in an HTML list.
ISSUES:
1. I don't have a good handle on SESSION, so not sure how to store the array as a session variable.
2. I'm not sure how to reference a specific index of an array in php. I've sorta done it in a java way here, but that needs to change.
--CODE--
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
<?php
$stack = array("");
array_push($stack, $_POST[name]);
for(i < $stack.length){
print_r($stack[i]);
}
?>
To access session variables is easy:
First, you need to call the method session_start() (Make sure, you call it, before sending any HTTP header).
After calling the session_start() method, you will have access to the $_SESSION associative array. You will be able to append anything to this array.
The syntax of the for loop in PHP is as follows:
foreach (array_expression as $value)
statement
or
foreach (array_expression as $key => $value)
statement
I hope that it helps.
First let's see the lines of code in PHP you have written:
I.
$stack = array("");
This creates an array called $stack with a single element of "". $stack[0] will have the value of "". You can name the elements of an associated array, like this:
$stack = array("name" => "value");
In this case $stack["name"] will be "value".
II.
array_push($stack, $_POST[name]);
This is incorrect, since name is not a variable, nor a string. You probably meant:
array_push($stack, $_POST["name"]);
this would have written $_POST["name"] at the end of your array having "", so $stack[1] would have been whatever the value of $_POST["name"]; was.
III.
for(i < $stack.length){
This is incorrect syntax. You have meant
for($i = 0; $i < count($stack); $i++){
Note how $ is put in front of all variables and how similar this for cycle is to a Java for.
IV.
print_r($stack[i]);
Incorrect, you need the the cash ($), otherwise your variables will not cooperate.
print_r($stack[$i]);
You, however, do not check whether this is a POST request or a GET. When the user loads the page, it will be a GET request and when he submits the form, it will be a POST request. The first (GET) request will not have $_POST members ($_POST will be empty), as the form was not submitted yet. And if you check whether it is a POST request, you need to check whether "name" is present in $_POST:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //it is a post
if (isset($_POST["name"])) { //name is found inside $_POST
echo "Name is " . $_POST["name"];
}
}
?>
Question1:
$_SESSION is an array, like $stack. You can do something like this:
$_SESSION["name"] = $_POST["name"];
This will create a new element of $_SESSION with the index of "name", however, before such an assignment, you need to make sure the session was started.
Question2:
You reference it by the name of the index, just like in Java, however, in PHP you can have textual indexes as well if you want, while in Java you can only use integers.
Just to quickly update the code you have, to make it somewhat workable:
Html code
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
Php code
<?php
$stack = array("");
if(isset($_POST['name'])){
array_push($stack, $_POST['name']);
for($i=0; $i < count($stack); $i++){
echo($stack[$i]);
}
}
?>
Assuming this is all in welcome.php.

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

how to store variable values over multiple page loads

I'm making a php script that stores 3 arrays: $images, $urls, $titles based on the input data of the form within the php file.
I want to print the values of these arrays in the first part of the page and then to pre-fill the form's input fields with the value of the arrays. Also when a user modifies an input field and clicks on "Save" the page should reload with the modfied version.
My problem is that on each call of the php file in a browser the value of the variables gets deleted. Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?
<?php
//save the arrays with the form data
$images = array($_POST["i0"],$_POST["i1"],$_POST["i2"],$_POST["i3"]);
$urls = array($_POST["u0"],$_POST["u1"],$_POST["u2"],$_POST["u3"]);
$titles = array($_POST["t0"],$_POST["t1"],$_POST["t2"],$_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Store the variables in a PHP session.
session_start();
$_SESSION['images'] = $images;
Then on next (or any other) page, you can retrieve the values as:
session_start();
$images = $_SESSION['images'];
Changing the scope of the variables to a larger scope, might do the trick. Also, check if you have a post request before updating the values.
<?php
if(sizeof($_POST) >0)
{
//UPDATE VALUES
}
?>
If you want a permanent storage of state, between different pages, you should use sessions, by putting session_start(); in the start of your script. After this, every variable $_SESSION[$x] will be persisted, and will be available to your scripts.
However, in this particular case, answering your question: "Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?", it is easier to just use the $_POST variable if it exists already:
<?php
if(!$_POST){
$_POST = array();
foreach(array("i0","i1","i2","i3") as $i) $_POST[$i]="";
foreach(array("u0","u1","u2","u3") as $i) $_POST[$i]="";
foreach(array("t0","t1","t2","t3") as $i) $_POST[$i]="";
}
foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
//save the arrays with the form data
$images = array($_POST["i0"], $_POST["i1"], $_POST["i2"], $_POST["i3"]);
$urls = array($_POST["u0"], $_POST["u1"], $_POST["u2"], $_POST["u3"]);
$titles = array($_POST["t0"], $_POST["t1"], $_POST["t2"], $_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Note: this line foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
should be enough to protect you from basic XSS attacks.
Note also that in general, it is best to follow the pattern of reloading pages with GET after POST, which makes you less susceptible to form resubmitions, in which case using sessions for storage is the better solution.
What brought me here was somewhat different kind of beast. I had problem with subsequent post request from AXIS IP camera and needed to preserve last file name across requests. In case that someone stumble here looking for some way to cache variables and SESSION is not an option maybe should look at Alternative PHP Cache:
Note: Unlike many other mechanisms in PHP, variables stored using
apc_store() will persist between requests (until the value is removed
from the cache).
http://php.net/manual/en/book.apc.php
Use sessions: http://php.net/manual/en/function.session-start.php
You can use sessions to store values and write rules to refill form fields after validations on data submit. Also function isset() is very helpful to avoid "not defined" errors.
The solution you are looking for is the session. Use $_SESSION to store value of Your variables. For example, at the end of script:
$_SESSION['images'] = $images;
and in form's input:
<input name='i".$x."' type='text' value='".(isset($_SESSION['images']) ?
$_SESSION['images'] : '')."'>

Categories