PHP, pass array through POST - php

Which is the most secure way to send an array through POST?
foreach ($id as $array)
{
<input type="hidden" name="prova[]" value="<?php echo $array; ?>"/>
}
<input type="submit" name="submit"/>
or using implode() to create a single variable, pass the variable and then use explode() to get back the values into a new array?

Edit If you are asking about security, see my addendum at the bottom Edit
PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.
$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);
This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.
Addendum
I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.

http://php.net/manual/en/reserved.variables.post.php
The first comment answers this.
<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>
<?php
var_dump($_POST['person']);
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>
The name tag can work as an array.

You could put it in the session:
session_start();
$_SESSION['array_name'] = $array_name;
Or if you want to send it via a form you can serialize it:
<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />
$passed_array = unserialize($_POST['input_name']);
Note that to work with serialized arrays, you need to use POST as the form's transmission method, as GET has a size limit somewhere around 1024 characters.
I'd use sessions wherever possible.

There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).
XSS
XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:
" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="
This would be written into your form like so:
<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>
The best way to protect against this is to use htmlspecialchars() to secure your input. This encodes characters such as < into <. For example:
<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>
You can read more about XSS here: https://www.owasp.org/index.php/XSS
Form Modification
If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.
I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg with ../index.php or ../db-connect.php).
In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.

Why are you sending it through a post if you already have it on the server (PHP) side?
Why not just save the array to s $_SESSION variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.
It all depends on what you really want to do.

Related

How to use input submit value and GET (link the submit value to another page) in a single click?

I am trying to input submit value and want to pass the value to another page through GET but for that I have to use two Clicks button.
I want the same in a single click. Help required.
Code:-
<form method="post">
<input name="inwardid" type="text" id="inwardid" />
<?php $inwardid = $_POST['inwardid']; ?>
<input type="submit" value="Next" />
</form>
<a href="addbook.php?up=<?php echo $inwardid; ?>"><button>Proceed</button>
You want to send the value the user typed in to the other page. So use this for your <form>:
<form method="POST" action="addbook.php">
<input name="up" type="text" id="up">
<input type="submit" value="Proceed">
</form>
To access the value in addbook.php, use $_POST['up'].
This will send the value the user typed in the input label (type="text") to the addbook.php page, using a $_POST. No need for a $_GET, $_POST will do just fine.
As you deliberately asked for method GET, my solution shows you GET!
You must know there is no security issue when using GET. It depends what you want to do. GET is useful if you want to use a dynamic code in multiple ways depending on some some variables that you do not want to hard-code in your script, or simply do not want to send files or other huge data.
Lets admit a newspaper has a site called breaking_news.php and you want to access the breaking news of November 8, 2016you could use this as :
breaking_news.php?y=2018&m=11&d=08
The fact that one can see your GET vars means nothing. Even by using POST one can see your variables by looking at your code. And one way or the other you must protect against code injection and brute force.
But if your not in the mood to show this vars to your visitor you can use URL rewriting to rewrite the url above in the browser as
RewriteRule ^breaking/(.*)/(.*)/(.*)/news\.html$ breaking_news.php?y=$1&m=$2&d=$3 [NC,L]
so you send your visitor to see the (rewritten)URL
breaking/2018/11/08/news.html
but what the web-server is showing him is:
breaking_news.php?y=2018&m=11&d=08
A reason to use this if for example when you want your dynamic site to be taken into consideration by some searching engine as a static site, and get indexed. But this is again another battle field.
Second, you want to send the variable to "addbook.php", and not to itself.
Your question sounded like you want to send to "another page" not to the same page.
Third, I can see in your code snippet you want to submit the variable "up" and not "inwardid", as you did in your code.
And also I can see you want the "submit" button to be called "Proceed".
Your code would look like this:
<form method="GET" enctype="application/x-www-form-urlencoded" action="addbook.php" target="_blank">
<input name="up" type="text" id="inwardid" />
<input type="submit" value="Proceed" />
</form>
As I said you must protect against injection, and this means for example, that in the "addbook.php",to whom you are sending the variables you must write some code that protects you against this issues. As your question is not in this direction I will not enter this subject.
To avoid problems with special chars you must "url-encode" your variable specially when sending them per POST method. In this case you must use this enctype if your handling text. Because this enc-type is transforming special chars into the corresponding ASCII HEX-Values.
Using GET your safe, because GET cant send in another enc-type. So your variable will automatically be url-encoded and you receive a string that is compliant to RFC 3986 similar by using:
rawurlencode($str)
Lets admit someone smart guy fills in a your input box the following code, in the desire to break your site. (This here is not exactly a dangerous code but it looks like those who are.)
<?php echo "\"?> sample code in c# and c++"; ?>
using enctype="application/x-www-form-urlencoded" this will become something like this:
%3C%3Fphp%20echo%20%22%5C%22%3F%3E%20sample%20code%20in%20c%23%20and%20c%2B%2B%22%3B%20%3F%3E
what makes it safe to be transported in a URL, and after receiving and cleaning it using
strip_tags(rawurldecode($_GET['str']))
it would output something like this, what is a harmless string.
sample code in c# and c++

Get Tag As Value For Imput Type

I am needing a GET value to be placed display in a forum option, however I do not know how to do this, as the get value can not have quotes in it. The xxx is where I want to display the get value.
<input type="text" name="test" value="xxx">
This is really basic stuff. Should not be any problems to find by Google.
<input type="text" name="test" value="<?php echo $_GET['your_parameter']; ?>" />
You should escape the GET parameter before echoing it, unlike the other answer. This will prevent someone from injecting extraneous tags into your code.
<?php
$parameter = (isset($_GET["your_parameter"])) ? htmlspecialchars($_GET["your_parameter"]) : '';
?>
<input type="text" name="test" value="<?= $parameter ?>" />
If you have short tags disabled, you'll need to use <?php echo in place of <?=. Many (most?) PHP developers will argue that you shouldn't use short tags at all. I personally never use them because I don't write my templates in PHP.
As Jimmie Johansson mentioned before this is really basic stuff and easy to search for.
Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.
Source: http://www.php.net/manual/en/tutorial.forms.php
If you transmit data via a FORM to php there are to ways to transmit the data. The first one ist via GET the other way is via POST.
If you choose GET your information will be stored as URL-Parameters
An associative array of variables passed to the current script via the
URL parameters.
Source: http://www.php.net/manual/en/reserved.variables.get.php
Post instead just sends the data to the PHP-Script so you can use this data like GET but you do not have any URL-Parameters here.
An associative array of variables passed to the current script via the
HTTP POST method.
Source: http://www.php.net/manual/en/reserved.variables.post.php
To choose one of this two Methods you have to edit your HTML-Form
Now that we transmitted the data either with GET or POST we can access them in PHP via the global variables
$_GET
and
$_POST
They are Arrays and you can access specific data with a key which represents the name of the input field or other form constructs. In your example the input fields name is "test" so we would access it like this
<?php $_GET["test"]; ?>
You can use
<?php ... ?>
Wherever you want in your HTML-Code as long it's an PHP File. So if you want to output something via PHP just use the and put you statements between them.
<input type="text" name="test" value="<?php echo $_GET['your_parameter']; ?>" />
Documentation
Arrays:
http://php.net/manual/de/language.types.array.php
Forms:
http://www.php.net/manual/en/tutorial.forms.php
http://www.w3schools.com/php/php_forms.asp
PHP and HTML:
http://www.php.net/manual/en/faq.html.php
POST and GET:
http://php.net/manual/de/reserved.variables.post.php
http://php.net/manual/de/reserved.variables.get.php
Further Reading
Further reading
http://en.wikipedia.org/wiki/Separation_of_presentation_and_content
http://wp.tutsplus.com/tutorials/creative-coding/improving-your-work-flow-separate-your-mark-up-from-your-logic/
http://www.w3schools.com/tags/ref_httpmethods.asp
And the important things at the end. For security you should check what was entered into the input field
http://www.w3schools.com/php/php_form_validation.asp
If you have problems to follow my answer feel free to ask me. Check the links!

How can I populate the fields of a PHP form automatically when the field values are in the url?

I have a have in PHP and I have common fields such as 'Name' and 'Surname'.
Now when the user visits the page e.g. http://www.example.com/form.php the form fields 'Name' and 'Surname' are empty.
I would like to now have a link similar to this http://www.example.com/form.php?name=John
so that when the client hits the link the PHP form will now have the name field already filled with 'John' in it.
I know this can be done in HTML but how can I do it in PHP?
Just to let to know I do not own the PHP form - I just want a link from my website to fill the PHP form (which I do not have control over).
Thanks in advance.
Can be done using $_GET
An associative array of variables passed to the current script via the URL parameters.
e.g.:
<? php
if(isset($_GET['name']))
{
$test = $_GET['name'];
}
?>
<html>
<body>
<form>
<input type="text" name="test" value="<?php if(isset($test)){echo "$test";}?>"/>
</form>
</body>
</html>
Note: code isnt tested or anything.. Also, there are possible security risks with getting values from your URL (can be considered user input), so make sure you are aware of that and how to prevent
You could store that value and then when you're about to output the input fields
you just pass along the stored value.
$name = $_GET['name'];
// ... later on
echo '<input type="text" value="'.$name.'"/>';
By using $_GET superglobal
<input name="name" value="<?php echo !empty($_GET['name']) ? $_GET['name'] : '';?>" />
<input name="surname" value="<?php echo !empty($_GET['surname']) ? $_GET['surname'] : '';?>" />
You can use the get method in php to get the name and make use of it
You can retrive this information by the $_GET["name"] function, or $_REQUEST["name"].
Reserver variables
Be carefull with those operations, you might have validation a/o security problem.
Note: if you are not sure that the "name" variable is set or not, you have to use also the
isset function to test it.
You can use the $_GET superglobal, so your input could look like this:
<input type="text" name="name" value="<?php if(isset($_GET['name'])) { echo $_GET['name']; } ?>" />
The $_REQUEST superglobal does a similar thing but I would just use $_GET.
It looks like everyone's answers here assume you are building the form yourself, which doesn't appear to be the case based on your question.
The thing that you want to do may or may not be possible. If the form accepts certain kinds of parameters in certain ways, you may be able to hook in to that functionality and set it up so that when someone clicks a link on your page, that information gets passed to the other page.
One way forms can accept this information is in the form of a "get" request. With this method, values are passed as part of the url, as in your example: http://www.example.com/form.php?name=John. Assuming your page has access to a php variable called $name, you can create a link from your code to build this kind of url like this:
Sign up!
If the page does not accept get parameters in this way (and I have a hard time imagining that they would), you may have to try other techniques to send along the information (assuming that they will even accept it!). The two other ways I imagine you could do this are by passing the value with "post" or creating a cookie for the page. If you tell us what page you are trying to set up this behavior on, we might be able to examine it and give you a better answer.

hidden field in php

For hidden fields, can i use a field of the type
<input type="hidden" name="field_name" value="<?php print $var; ?>"/>
and retrieve it after the GET / POST method as $_GET['field_name'] / $_POST['field_name'] ?
are there any other ways of using hidden fields in php?
You absolutely can, I use this approach a lot w/ both JavaScript and PHP.
Field definition:
<input type="hidden" name="foo" value="<?php echo $var;?>" />
Access w/ PHP:
$_GET['foo'] or $_POST['foo']
Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php
Cheers!
Yes, you can access it through GET and POST (trying this simple task would have made you aware of that).
Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.
Can I use a field of the type ... and retrieve it after the GET / POST method ...
Yes (haven't you tried?)
Are there any other ways of using hidden fields in PHP?
You mean other ways of retrieving the value? No.
Of course you can use hidden fields for what ever you want.
Btw. input fiels have no end tag. So write either just <input ...> or as self-closing tag <input .../>.

Will data order in post form be the same to it in web form?

Assuming there are 5 inputs in web form
<input name='the_same[]' value='different' />
<input name='the_same[]' value='different' />
<input name='the_same[]' value='different' />
<input name='the_same[]' value='different' />
<input name='the_same[]' value='different' />
When server side receive the post data, i use a foreach to accept data, say
$the_same = new array();
foreach($_POST['the_same'] as $data)
$the_same[] = $data;
Will the order of data saved in server side be the same to it in web form? and cross browsers, it could be a criteria all browsers follow.
Well, the W3C recommendation on HTML forms does say:
The control names/values are listed in
the order they appear in the document.
Still, I'd consider it a bit risky to have your app depend critically on that detail.
PHP already handles converting POSTed/GETed variables into arrays when you put [] after the name. Do that instead of getting it wrong yourself.
Better way to do in html:
<input name='the_same[]' value='different' />
Then in server:
$the_same = new array();
foreach($_POST['the_same'] as $data) // or $_GET if you prefer
$the_same[] = $data;
In this way no variable will be overwrite.
if you want to have it in an order, you may use the dynamic variables or simply access the array explicitly
the_same1
the_same2
the_same3
since you know the names anyway, you can access them easily
$the_same = array();
for($i=1; ; $i++){
$tmp =$_REQUEST["the_same".$i]
if( empty($tmp) ){
// no more stuff
break;
}
$the_same[] = $tmp;
}
If you change the name of your input to the_same[] - $_REQUEST['the_same'] will become an array of those values, first to last in element order (all current browsers I believe).
You can also specify a specific order if you need, or even use string keys. For instance, an <input name='the_same[apple][2]'/> would become $_REQUEST['the_same']['apple'][2]
Without using the [] on the input names, PHP will only see the last value. The other values will be 'overwritten' by the later value when the $_REQUEST/$_GET/$_POST arrays are constructed.
An example of using that to your advantage could be with a checkbox, as the HTML checkbox only submits a value when checked, you may want to submit a "not checked" value somtime:
<input type='hidden' name='check' value='not checked' />
<input type='checkbox' name='check' value='checked' />
Most likely yes, but you should not assume this. It depends on your browser how the inputs are being send, and aditionally PHP does not guarantee that a foreach loop iterates in the same order as the elements were added.
It is a bad practise to give your inputs the same name.
You could append an index after each name value (even with javascript if you want), and then read this in PHP to be sure the order is maintained.

Categories