Array and loop PHP - 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.

Related

How to save POST data of a form after user submission without using Sessions, JSON, Ajax, Hidden input or another file

First of all I'll be sincere, I'm a student and I've been asked to do a task that seems impossible to me. I don't like asking questions because generally speaking I've always been able to fix my coding issues just by searching and learning, but this is the first time I've ever been on this possition.
I need to create a php file that contains a form with two inputs that the user fills. Once he clicks submit the website will show on top of it the two values. Till here I haven't had an issue, but here's the problem, the next time the user sends another submission, instead of clearing the last 2 values and showing 2 new ones, now there needs to be 4 values showing.
I know this is possible to do through JSON, the use of sessions, Ajax, hidden inputs or using another file (this last one is what I would decide to use if I could), but the teacher says we gotta do it on the same html file without the use of any of the methods listed earlier. He says it can be done through an Array that stores the data, but as I'll show in my example, when I do that the moment the user clicks submit the array values are erased and created from zero. I know the most logical thing to do is asking him, but I've already done that 4 times and he literally refuses to help me, so I really don't know what to do, other than asking here. I should point out that the answer has to be server side, because the subject is "Server-Side Programming".
Thank you for your help and sorry beforehand because I'm sure this will end up being a stupid question that can be easily answered.
For the sake of simplicity I erased everything that has to do with formatting. This is the code:
<?php
if (isset($_POST['activity']) && isset($_POST['time'])){
$agenda = array();
$activity = $_POST['activity'];
$time = $_POST['time'];
$text = $activity." ".$time;
array_push($agenda, $text);
foreach ($agenda as $arrayData){
print implode('", "', $agenda);
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<label for="Activity">Activity</label><br>
<input name= "activity" type="text"><br><br>
<label for="Time">Time</label><br>
<input name= "time" type="time"><br><br>
<input type="submit">
</form>
</body>
</html>
Your question was not very clear to be honest but I might have gotten something going for you.
<?php
$formaction = $_SERVER['PHP_SELF'];
if (isset($_POST['activity']) && isset($_POST['time'])){
$agenda = array();
//if the parameter was passed in the action url
if(isset($_GET['agenda'])) {
$agenda = explode(", ", $_GET['agenda']);
}
//set activity time
$text = $_POST['activity']." ".$_POST['time'];
//push into existing array the new values
array_push($agenda, $text);
//print everything
print implode(", ", $agenda);
//update the form action variable
$formaction = $_SERVER['PHP_SELF'] . "?agenda=" . implode(", ", $agenda);
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $formaction; ?>" method="POST">
<label for="Activity">Activity</label><br>
<input name= "activity" type="text"><br><br>
<label for="Time">Time</label><br>
<input name= "time" type="time"><br><br>
<input type="submit">
</form>
</body>
</html>
SUMMARY
Since you cant save the posted values into SESSION vars or HIDDEN input, the next best thing would be to append the previous results of the posted form into the form's action url.
When the form is posted, we verify if the query string agenda exists, if it does we explode it into an array called $agenda. We then concatenate the $_POST['activity'] and $_POST['time'] values and push it to the $agenda array. We then PRINT the array $agenda and update the $formaction variable to contain the new values that were added to the array.
In the HTML section we then set the <form action="" to be <form action="<?php echo $formaction; ?>

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'] : '')."'>

how to add input to a variable?

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.

How to add element to array without rewriting previous? - PHP

I'm trying to add elements to an array after typing their name, but for some reason when I do
<?php
session_start();
$u = array("billy\n", "tyson\n", "sanders\n");
serialize($u);
file_put_contents('pass.txt', $u);
if (isset($_POST['set'])) {
unserialize($u);
array_push($u, $_POST['check']);
file_put_contents('pass.txt', $u);
}
?>
<form action="index.php" method="post">
<input type="text" name="check"/><br>
<input type="submit" name="set" value="Add person"/><br>
<?php echo print_r($u); ?>
</form>
It puts it in the array, but when I do it again, it rewrites the previous written element. Does someone know how to fix this?
You always start with the same array, which means no matter what you do you're going to only be able to add one person. I /think/ you're trying to add each person to the file, which can be accomplished by modifying the code to resemble something like this:
session_start();
$contents = file_get_contents('pass.txt');
if (isset($_POST['set'])) {
$u = unserialize($contents);
array_push($u, $_POST['check'] . "\n");
$u = serialize($u);
file_put_contents('pass.txt', $u);
}
Notice also that you can't use [un]serialize() on its own, it must be used in the setting of a variable.
**Note: Personally, I'd just go the easy route and do $u[] = $_POST['check'], as using array_push() to push one element seems a bit... overkill.

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