Dynamically add to array in PHP? - php

I am trying to take input from a form, add it to an array, and print_r that array to the screen.
My problem is that the input from the form only replaces the first (and only) element in the array.
<form action="" method="POST">
<input type="text" name="text" />
<input type="submit" name="sub"/>
</form>
<?php
$a = array();
if( isset($_REQUEST['text']) && !empty($_REQUEST['text'])){
array_push($a, $_REQUEST['text']);
print_r($a);
}
?>
One theory of mine is that $a keeps getting re-assigned on the first line of PHP code ($a = array();), but I'm not sure how to fix it. I have looked around, but can't find an answer.

You are correct. The array does get reinitialized each time the form is posted. What you'll want to do is have your array as a more persistent data source.
You might consider using a session and the $_SESSION variable.
session_start();
if (!is_array($_SESSION['a'])){
$_SESSION['a'] = array();
}
$_SESSION['a'][] = $_REQUEST['text'];
You might also consider writing this data to a small text file that you could then read at the start of the script.
Another option would be to write the data to a $_COOKIE.

You are mixing client and server execution...
If you want an array of text you should use something like this:
<form action="" method="POST">
<input type="text" name="text[]" />
<input type="text" name="text[]" />
<input type="text" name="text[]" />
<input type="submit" name="sub"/>
</form>
If you want more entry of text being added you should inject more input with javascript

You are not replacing anything, what you're doing is adding the value of $_REQUEST['text'] to the array, which was empty before.

Related

Php send post vars in form

if i put this : NO WORKS
<?php
if($_POST['send']=="ok")
{
print $_POST['opt']['nombre']
}
?>
<form action="" method="post" style="margin:0px;">
<input type="text" name="opt['nombre']" value="Hello" />
<input type="hidden" name="send" value="ok">
</form>
If i Put this : WORKS
<?php
if($_POST['send']=="ok")
{
print $_POST['opt']['nombre']
}
?>
<form action="" method="post" style="margin:0px;">
<input type="text" name="opt[nombre]" value="Hello" />
<input type="hidden" name="send" value="ok">
</form>
Why Happend this , the only change it´s in input file this opt['nombre'] by opt[nombre]
I don´t understand why happend this, it´s possible fix this problem because i want put opt['nombre'], and i think it´s the right
When works the result i get it´s "Hello" but only change this symbol inside tags as [''] by []
DIFFERENCES WORKS AND NO WORKS WHEN SEND POST FORM :
SEND FORM AND DON´T GET HELLO
<input type="text" name="opt['nombre']" value="Hello" />
SEND FORM AND GET HELLO
<input type="text" name="opt[nombre]" value="Hello" />
DIFFERENCE PUT INSIDE [] QUOTES AS 2 OR DON´T PUT, THANK´S
var_dump($_POST) and take a look at the keys. You'll see the difference. The single quotes in the HTML name attribute become part of the string key in the PHP array when you do it the first way. You'd have to access it with the single quotes as part of the string to get it.
print $_POST['opt']["'nombre'"];
Or better yet, just do it the second way, so your PHP code won't have to use a silly key like that. :-)

PHP Read and Write field values without a postback

I want to create a hidden field in my HTML page, all good, just a simple <input> field. Then, I'm trying to read the value of that input field as the page loads the first time, so the closest I've gotten to that is using a $_GET statement. I'm simply trying to echo out the value so that I can see that it's working like such:
<input type="hidden" name="selection" value="fixtures">
<?php
echo $_GET['selection']
and that just gives me nothing, if I try:
echo "<h1>$_GET['selection']</h1>
then I get 0.
Question is - what <form> parameters you have? Did you submit form? Simples example for it will be:
//form.php
<form method="GET" action="next.php">
<input type="hidden" name"selection" value="fixtures" />
<input type="submit" name="submit_btn" value="Send" />
</form>
//next.php
echo '<h1>'.$_GET['selection'].'</h1>';
You can achieve same thing with:
Link

How to POST an associative array in PHP

I have the following form:
<form action="options.php" method="post">
<input type="text" name="deptid" id="deptid" />
<input type="text" name="deptname" id="deptname" />
<input type="submit" name="submit" id="submit" value="save" />
</form>
EDIT
Is it possible to pass the two values into one associative array BEFORE submission ?
I would like to pass it in this form:
array('deptid'=>'deptname')
I need this because I avoid to modify the script of the destination php file(options.php)
Thanks.
Here is a method using pure HTML that get's you nearly exactly where you want to be, and only uses HTML:
<form action="options.php" method="post">
<input type="text" name="options[deptid]" id="deptid" />
<input type="text" name="options[deptname]" id="deptname" />
<input type="submit" name="submit" id="submit" value="save" />
</form>
Which would give you in PHP:
$post_options = array(
'options' => array(
'deptid '=> '[that input element value]',
'deptname' => '[that input element value]'
)
);
Which you can then (including sanitizing) access such as this:
$post_options = array('options');
if (is_numeric($post_options['deptid'] && $post_options['deptid'] > 0) {
// Do whatever
}
if (is_string($post_options['deptname'] && strlen($post_options['deptname'] > 2)) {
// Do whatever
}
EDIT
Or... You want to reference the deptid in the input name attribute and use it to modify the row for a department name? Which seems to indicate something like this:
<?php
$deptid = 1;
$deptname = 'Department of Silly Walks';
?><input type="hidden" name="options[<?=$deptid?>]" value="<?=$deptname?>">
Which outputs:
<input type="hidden" name="options[1]" value="Department of Silly Walks">
http://codepad.org/DtgoZGe7
The problem with this is that the $deptid value becomes a value that's not actually directly named or referenced. I think this is potentially problematic to implement due to this abstraction of the value from the server to the client and back, so I would recommend what I have at the top instead. It's not much of a difference in practice, but it's more or less self-documenting.
Note, if you wanted to serialize a list of departments, it's a little trickier. You might, for instance, try this:
<input type="text" name="options[][deptid]" id="deptid" />
<input type="text" name="options[][deptname]" id="deptname" />
Which would add an indexed value for every input. However... They were would not be directly associated. So you would get, instead, two zero-indexed arrays for each key.
What I would suggest in this case is to use Javascript to add each new department's input elements, so you can give each a number like:
<input type="text" name="options[0][deptid]" id="deptid" />
<input type="text" name="options[0][deptname]" id="deptname" />
<br/>
<input type="text" name="options[1][deptid]" id="deptid" />
<input type="text" name="options[1][deptname]" id="deptname" />
<br/>
<input type="text" name="options[2][deptid]" id="deptid" />
<input type="text" name="options[2][deptname]" id="deptname" />
<br/>
<input type="text" name="options[3][deptid]" id="deptid" />
<input type="text" name="options[3][deptname]" id="deptname" />
Or do the old-school POSTBACK method and use PHP to count $POST['options'] and "manually" add a new "row" of inputs with the same index. It's a common trap, so you just have to think about it if this is what you're after at some point.
$_POST is already an associative array and I recommend you not to complicate things beyond that because $_POST already holds the data came from your form.
$myassoc = $_POST;
print_r($myassoc);
and the associative array that you will receive is organized and named same in the name attribute of the input elements in your form (including textarea)
Other Insights
As I see your code you want to put the deptname data to deptid as it reaches the PHP server-side code. well the thing you can do with is is just assign it to the key deptid
$_POST['deptid'] = $_POST['deptname'];
$myassoc = $_POST;
print_r($myassoc);
<form method="post">
<input type="text" name="formdata['deptid']" />
<input type="text" name="formdata['deptname']" />
<input type="submit" />
</form>
<?php
if(isset($_POST['formdata']))
{
$deptid = $_POST['formdata']['deptid'];
$deptname = $_POST['formdata']['deptname'];
}
?>
Build a JS object with the appropriate structure, convert it to JSON with JSON.stringify(), POST it, and then do json_decode($_POST['data'],true).
You'll have an exact copy from JS object, to PHP associate array. Drop the second parameter of true to get a PHP object.
$_POST is already an associative array.
You can rebuild an array of the form you need from this by just assigning $_POST to a variable
$myarray = $_POST;
Now $myarray is what you require. Do var_dump($myvar);.
Why would you want to do that?
But, you CAN send "arrays" through forms like this:
<form method="post">
<input type="text" name="textboxes[]" />
<input type="text" name="textboxes[]" />
<input type="submit" />
</form>
<?php
if(isset($_POST['textboxes']))
var_dump($_POST['textboxes']);
?>
$deptid = $_POST['deptid'];
$array = array($$deptid => $_POST['deptname']);
print_r($array);

reading two form elements with same name

<form action="test.php" method="post">
Name: <input type="text" name="fname" />
<input type="hidden" name="fname" value="test" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
How can I read the values of both the fields named fname?
On my action file(test.php) under $_POST, I am getting only hidden field value.
Is there any PHP setting through which I can read both values?
I believe you want to name the fields as:
Name: <input type="text" name="fname[]" />
<input type="hidden" name="fname[]" value="test" />
to make PHP understand them as an Array.
In case someone wants to do this and doesn't want to change the name of the form elements, or can't, there is still one way it can be done - you can parse the $_SERVER['QUERY_STRING'] or http_get_request_body() value directly.
It would be something like
$vals=explode('&',http_get_request_body());
$mypost=Array();
foreach ($vals as $val) {
list($key,$v)=explode('=',$val,2);
$v=urldecode($v);
$key=urldecode($key);
if ($mypost[$key]) $mypost[$key][]=$v;
else $mypost[$key]=Array($v);
}
This way $mypost ends up containing everything posted as an array of things that had that name (if there was just one thing with a given name, it will be an array with only one element, accessed with $mypost['element_name'][0]).
For doing the same with query strings, replace http_get_request_body() with $_SERVER['QUERY_STRING']
If you want to pass two form inputs with the same name, you need to make them an array. For example:
<input type="text" name="fname[]" />
<input type="hidden" name="fname[]" value="test" />
You can then access it using the following:
$_POST['fname'][0]
$_POST['fname'][1]
You might want to rethink whether you really need to use the same name though.
Solutions are
1) Try using different name for textbox and hidden value
2) Use an array as mentioned above for field name
3) Its not possible as the values will be overwritten if the names are same

how to pass an array in GET in PHP?

$idArray = array(1,2,3,4);
can I write this line in HTML?
<form method='POST' action='{$_SERVER['PHP_SELF']}?arr={$idArray}'>
or should I write:
<form method='POST' action='{$_SERVER['PHP_SELF']}?arr[]={$idArray}'>
how will it be passed?
how should I handle it in the called page?
thanks !!
If you want to pass an array as parameter, you would have to add a parameter for each element. Your query string would become:
?arr[]=1&arr[]=2&arr[]=3&arr[]=4
As others have written, you can also serialize and unserialize the array.
But do you really have to send the data to the client again? It looks like you just need a way to persist the data between requests.
In this case, it is better imo to use sessions(docs). This is also more secure as otherwise the client could modify the data.
Use serialize and unserialize PHP function.
This function giving you storable (string) version of array type.
For more infomation about usage read
http://php.net/manual/en/function.serialize.php
and http://www.php.net/manual/en/function.unserialize.php
You could use serialize and & serialize along side with urlencode
e.g.
On Sending you can send them like these:
<?php
$array1 = Array(["key1"]=>"value1",["key2"]=>"value2");
$array2 = Array(["key1"]=>"value1",["key2"]=>"value2");
$data1="textdata";
$urlPortion= '&array1='.urlencode(serialize($array1)).
'&array2='.urlencode(serialize($array2)).
'&data1='.urlencode(serialize($data1));
//Full URL:
$fullUrl='http://localhost/?somevariable=somevalue'.$urlPortion
?>
On Receiving you can access them as:
<?php
$destArray1=unserialize($_GET['array1']);
$destArray2=unserialize($_GET['array2']);
$destData1=unserialize($_GET['data1']);
?>
And Voila, you can attach that url on ajax request or normal browser page.
Another option (even nice looking, I'd say):
<form method='POST'>
<input type="hidden" name="idArray[]" value="1" />
<input type="hidden" name="idArray[]" value="2" />
<input type="hidden" name="idArray[]" value="3" />
<input type="hidden" name="idArray[]" value="4" />
</form>
But of course it gets sent as POST. I wouldn'r recommend sending it with serialize since the output of that function can get pretty big and the length or URL is limited.
with GET:
<form method='GET'>
<input type="hidden" name="idArray[]" value="1" />
<input type="hidden" name="idArray[]" value="2" />
<input type="hidden" name="idArray[]" value="3" />
<input type="hidden" name="idArray[]" value="4" />
</form>
Just use explode() and pass it's value. You can get the array back by using implode().
Note: Choose the delimiter according to the type of content that does not exist in your array. For eg. If you are sure that there won't be any commas ( , ) in your array, then pick comma as delimiter.
Use parse_str function
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;
http://snipplr.com/view/4444/passing-an-array-through-get-request/
$str=serialize($idArray);
<form method='POST' action='{$_SERVER['PHP_SELF']}?arr=$str'>
To get the data in the receiving page you will first have to:
<?PHP
$idArray = unserialize($_GET["arr"]);
?>
In the particular case you mentioned, I would implode the array to a string and then explode it when you post the form.
$str = rawurlencode(implode(",",$idArray));
<form method='POST' action='{$_SERVER['PHP_SELF']}?arr={$str}'>
and then on the post processing:
$idArray = explode(",",rawurldecode($_POST['arr']));
serialize() your array first and pass that through. Then call unserialize() on it. http://ie.php.net/serialize
A session is a much safer and cleaner way to do this. Start your session with:
session_start();
Then add your serialized array as a session variable like this:
$_SESSION["venue"] = serialize($venue);
The simply call up the session variable when you need it.
Felix's answer answers the question beautifully, but lacks the examples in my opinion.
This answer is prompted by the comment on Felix's answer.
can you specify keys using this method? – Qwerty Apr 27 '14 at 0:05
First off, to illustrate Felix's answer:
<input type="hidden" name="array[]" value="val1" />
<input type="hidden" name="array[]" value="val2" />
<input type="hidden" name="array[]" value="val3" />
When the request is sent to the server it will be of the type Array.
Following is an example with keys. This will give you an array with two keys, two values each.
<input type="hidden" name="array['first']" value="val1" />
<input type="hidden" name="array['first']" value="val2" />
<input type="hidden" name="array['second']" value="val3" />
<input type="hidden" name="array['second']" value="val4" />
Finally here's an example with VueJS, which is what I was using as of this writing, which led me to this question.
<input v-for="(value, key) in data" type="hidden" :name="'array[' + key + ']'" :value="value">
I hope this will be helpful to any passersby.
Another option is to json_encode then base64_encode then urlencode then you can pass that into a get request.
$idArray = [1,2,3,4];
$urlArray = urlencode(base64_encode(json_encode($idArray)));
$fullURL = 'https://myserver/mypath/myscript.php?arr=' . $urlArray;
On receiving you can get back to the original array by urldecode then base64_decode then json_decode.
$idArray = json_decode(base64_decode(urldecode($_GET["arr"])));
As other have mentioned you can use serialize and unserialize but it is considered to be more secure to use json_encode and json_decode instead. Also as of PHP7 unserialize has a second parameter, for more info see https://github.com/kalessil/phpinspectionsea/blob/master/docs/security.md#exploiting-unserialize
You may not need to use the base64_encode and base64_decode but I recommend it. It will cost you some processing resources but will result in a shorter URL saving you network resources. Keep in mind that if your working with large arrays you may excede the limits of the allowed length of get requests for your server.

Categories