This question already has answers here:
PHP How to send multiple values within the same name
(2 answers)
I am trying to insert multiple input value with same name
(2 answers)
How to get multiple input values with PHP when name attributes are the same?
(1 answer)
store multiple value with same input name in sql
(1 answer)
PHP Get multiple values from GET with same name
(2 answers)
Closed 4 months ago.
simple php code that works well in terminal:
<?php
$a = array();
for($i=0; $i<3; $i++){
$b = readline('time: ');
$c = readline('money: ');
$d = array('time'=>$b, 'money'=>$c);
array_push($a, $d);
}
print_r($a);
this pushes the values of multiple entries into an array, creating an array of arrays. however, readline() does not work in the browser. i know i can use javascript easily enough but am trying to replicate this simple action using only php and html. and i really like the way readline() works. i have tried variations on the following but am left scratching my head:
<form method="POST">
<?php
for($i=0; $i<3; $i++){
?>
<input name = 'time'>
<input name = 'money'>
<?php
}
?>
<input type="submit">
</form>
<?php
print_r($_POST['time']);
was hoping print_r($_POST['input name']) would return an array, but instead only gives the last input entry. is there a straight forward way to do this with php, or do i HAVE to use a client-side script like javascript?
Just add [] to input names:
<form method="POST">
<?php
for($i=0; $i<3; $i++){
?>
<input name = 'time[]'>
<input name = 'money[]'>
<?php
}
?>
<input type="submit">
</form>
<?php
print_r($_POST['time']);
This question already has answers here:
Multiple inputs with same name through POST in php
(5 answers)
Closed 1 year ago.
I have a while loop that displays 4 checkboxes from $choices with value answer_id from database.
<?php while($row=mysqli_fetch_assoc($choices)){ ?>
<input type="checkbox" name="choices[]" value="<?php echo $row['answer_id']; ?>"><?php echo $row['choice']; ?><?php } ?><?php } ?>
<input type="submit" name="submit" value="submit">
I want to send this array of selected choices to another page and store each of its value in different variables.
if(isset($choices)){
$choice1id = $_POST['choices'];
}
if(isset($choices)){
$choice2id = $_POST['choices'];
}
if(isset($choices)){
$choice3id = $_POST['choices'];
}
if(isset($choices)){
$choice4id = $_POST['choices'];
}
If user has selected 2 checkboxes so its value gets on index 0 and 1 in array and these 2 values get stored in variables choice1id and choice2id on another PHP page.
But it says Warning: Undefined variable $choice1id, $choice2id etc.
how do I solve this?
I'm not sure if this is what you wanted. Seems like you want to get $_POST['choices'] and create variables from it? If so, first check if it was posted, then loop through each one. You can create dynamic variables in the loop. This will give you variables like $choice1id $choice2id .. etc
if(isset($_POST['choices'])){
$ctr = 1;
foreach ($_POST['choices'] as $choice) {
$var = "choice" . $ctr . "id";
$$var = $choice;
$ctr++;
}
}
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'] : '')."'>
This question already has answers here:
How to get PHP $_GET array?
(8 answers)
Closed 2 years ago.
I got a challenge in which I have this code in a PHP file:
<?php
include('secretfile.php');
if(isset($_GET['a']) && isset($_GET['b']))
{
$a = $_GET['a'];
$b = $_GET['b'];
if (!empty($a) && !empty($b))
{
if($a===$b)
{
if(isset($_GET['a']) && isset($_GET['b']))
{
$a = $_GET['a'];
$b = $_GET['b'];
if($a!==$b)
{
echo $secretcode;
}
}
}
}
}
I have to print secretcode in webpage with OUT changing the PHP file.
How can I do it?
I tried by giving parameters through URL like this:
http://127.0.0.1:8080/?a=1&b=1&a=22&b=33
But it didn't work. The file is taking the last values directly and no matter what, I couldn't go past the 13th line. I went through a lot of answers but I go no solution.
Is it possible to do it? If yes, how?
To pass multiple values for a or b, you need to use the [] notation like below:
http://127.0.0.1:8080/?a[]=1&b[]=1&a[]=22&b[]=33
That being said, the PHP code in your file seems to be poorly written.
To pass an array on html form you can use [] like
<form method="GET">
<input type="text" name="a[]" />
<input type="text" name="b[]" />
<form/>
I am building a number guessing game and need to create a session variable to hold the randomized target number until the user submits the correct guess. I also need to print the number of attempts after the user submits the correct answer.
I set my session variable and used a hidden field to hold the counter. I don't know if the hidden field works bc when I submit a guess, my code prints out the first if statement of the check() function..ALL THE TIME.
I think it has something to do with the session variable (and of course my code), but I can't figure it out. I've been working on this for two days now and feeling the frustrations. Any help would be amazing. Here's my full code below:
<?php session_start() ?>
<!DOCTYPE HTML>
<html>
<head>
<title>Number Guessing Game</title>
</head>
<body>
<h1>Guess the number</h1>
<p>I'm thinking of a number between 1 and 5. Can you guess what it is?<br>
In less than 3 tries?</p>
<?php
extract($_REQUEST);
error_reporting(E_ALL & ~E_NOTICE);
// check to see if this is start of game
if (filter_has_var(INPUT_POST, "guess")) {
check();
} else {
setTarget();
} //end if
// set targetNum session variable
// increment counter by 1
function setTarget() {
$targetNum = rand(1, 5);
$_SESSION["targetNum"] = $targetNum;
$counter++;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
}
function check() {
global $counter;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess"
value= "$guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
if ($guess == $_SESSION['$targetNum']) {
print "<h3>Awesome. You guessed it in $counter attempt(s)</h3>";
unset($_SESSION["targetNum"]);
$count = 0;
print "<a href='numberGuessingGame.php'>TRY AGAIN</a>";
} else if ($guess > $_SESSION['$targetNum']) {
print "<h3>Too high. Guess again.</h3>";
} else if ($guess < $_SESSION['$targetNum']) {
print "<h3>Too low. Guess again.</h3>";
} else {
print "I don't know what that is...";
}
}
?>
</body>
</html>
You made two basic, but severe errors.
First: DO not set the error level to exclude notices when developing! That way you will never spot typos in variable or array index names. Remove error_reporting(E_ALL & ~E_NOTICE);, or replace it with error_reporting(E_ALL);.
Second: You use extract($_REQUEST); - using that function is asking for trouble. PHP has a long history of security vulnerabilities because of the "register_globals" feature, which introduces global variables just because some key=value pair in the request data was parsed. It took years to remove that feature. You are re-implementing it without any security precaution by using that function, and with no real benefit.
Remove that extract($_REQUEST); function, and use $_REQUEST['varname'] instead of $varname for all variables that come from the remote browser.
Your $guess variable is never set to the POST value (Correction: you're using extract but I'd advise against it). You are also changing the value of your session array key when you add a '$':
$guess = $_POST['guess'];
if ($guess == $_SESSION['targetNum']) {