how to pass an array in GET in PHP? - 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.

Related

handle html input elements with numeric id javascript

i have html form
<form name="updatefrm" id="updatefrm" action="" method="post">
<input type="hidden" name="98" id="98" value="" />
<input type="hidden" name="99" id="99" value="" />
<input type="hidden" name="100" id="100" value="" />
<input type="hidden" name="101" id="101" value="" />
<input type="hidden" name="102" id="102" value="" />
<input type="hidden" name="updateqty" id="updateqty" value="1" />
</form>
now i want to assign value to this elements
i m using following javascript code for element with id 98
document.updatefrm."98".value = elements[0].value;
but its giving me error in console.
can any one help me with this ?
You should use document.formname to access forms as not all browsers support this(actually I'm not sure if any does). use document.forms.formname instead. Also to access a numeric property of an object use bracket notation instead of dot notation.
document.forms['updatefrm']['98'].value = elements[0].value;
Why can't I have a numeric value as the ID of an element?
// Change your numeric id.
var myValue=document.getElementById('your_changed_id').value;
alert(myValue)
Go for simplicity..Instead of writing this complex code.why not try a simple code which does the same thing
document.getElementById('your_changed_id').value
You can also use getElementById to set the value. Beside this also check Javascript Naming Convention
document.getElementById('98').value = "YOUR VALUE";
You should not give numbers as ID include any kind of character..
Try like this:
document.forms["updatefrm"]["s98"].value = elements[0].value;
Fiddle

Dynamically add to array in 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.

How to pass array of data from Joomla view form and get the array of data in Joomla Controller

In view/default.php:
<form action="<?php echo JRoute::_('index.php?option=com_scheduler&view=report');?>" method="post" name="rform">
<input type="submit" class="button" value="Generate Report" />
<input type="hidden" name="task" value="report.generate" />
<input type="hidden" name="data" value="<?php echo $this->epsiode; ?>" />
</form>
Where $this->episode is an array of data.
In controllers/report.php:
function generate(){
$items = JRequest::getVar('data',array(), 'post', 'array');
print_r($items);
}
The output is
Array ( [0] => Array )
Please suggest me how to get the array data. I'm using Joomla version 2.5.x.
Not clear what the hidden field data contains, but if you are just echoing an array, the final result does not surprise me.
I suggest one of the options (multiple solutions possible).
Serializing the array
<input type="hidden" name="data" value="<?php echo serialize(htmlentities($this->epsiode)); ?>" />
On the controller, make sure you unserialize the data.
JSON format
Similar idea to the one above, just use the JSON format to store the array. Check json_encode and json_decode
Try this
<?php
$content = $this->epsiode;
for($i=0;$i<sizeof($content);$i++) { ?>
<input type="hidden" name="data[]" value="<?php echo $content[$i] ; ?>" />
<?php } ?>
Use $requestData = JRequest::get('post'); (post, get or data accordingly) in any controller you are using. That should provide you with all the data sent over from the form you are using. Make sure this is the controller that your form posts to. Joomla has some strange behaviour with redirecting from tasks to views, which might give the impression you are losing data somewhere along the way.
Using Joomla 3.1.1

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

Using a Form With Variables as Part of a Function

Could the form below be part of a function? I am wondering if it might not be able to be part of a function since it has variables.
Thanks in advance,
John
echo '<form action="http://www...com/sandbox/comments/comments2.php" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<input type="hidden" value="'.$submission.'" name="submission">
<input type="hidden" value="'.$url.'" name="url">
<input type="hidden" value="'.$submittor.'" name="submittor">
<input type="hidden" value="'.$submissiondate.'" name="submissiondate">
<input type="hidden" value="'.$countcomments.'" name="countcomments">
<input type="hidden" value="'.$dispurl.'" name="dispurl">
<label class="addacomment" for="title">Add a comment:</label>
<textarea class="commentsubfield" name="comment" type="comment" id="comment" maxlength="1000"></textarea>
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
You can use that code in a function provided that:
You pass those parameters ($submissionid, $submission etc) to the function
or
You make them global (you shouldn't do this without strong reason)
There's three basic choices for passing form arguments into a function:
massive argument list
stuff the values into an array and passing that in
global variables
Generally only #2 will keep your hair from getting yanked out (by yourself or other people). The basic setup would go something like:
function show_form($args) {
echo <<<EOL
<form action="yada yada">
<input type="..." name="field1" values="{$args['field1']}" />
<input type="..." name="field2" values="{$args['field2']}" />
etc...
</form>
EOL;
}
$form_args = array(
'field1' => $field1,
'field2' => $field2,
etc...
)
show_form($form_args);
Note that I'm using a HEREDOC to generate the form text. It's far easier to deal with than building a string with concatenation. It saves you from having to worry about escaping quotes.
If this form deals with potentially hostile users, you'll want to pass all the values through htmlspecialchars() beforehand, to prevent some HTML injection attacks. You can do that within the form building function, or while you're building the argument array.
comment followup:
In this example, you're building array called "form_args" to store all the field data of your form. I'm just calling them "field1", "field2" etc... You pass those $form_args array as a parmeter to the show_form() function. Within the function, it accesses that data via its own private little "$args" copy of the array.
Within the form, the notation {$args['field1']} simply means "Look in the $args array for an entry whose key is 'field1', and insert its matching value into the HTML being generated here. The braces ({}) aren't strictly necessary in this case, but could be considered good practice to use anyways. There's more details in the PHP online manual's Arrays entry

Categories