Page 1 of 1

[HELP]Getting values from mulitple textbox using array

Posted: Wed Jan 26, 2011 8:21 pm
by aicrop
Hey guys I'm trying to get the values from 2 text and put it in 1 array and display it.
I cant figure out whts wrong with my code, any suggestion or ideas will help a lot thanks

Code: Select all

<html>
<head>
</head>
<body>

<?php

$try_array = array($_POST['name[]']);

foreach ($try_array as $try){
echo $try;
}



?>


<form name="fors" method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
Enter text:<input type="text" name="name[1]"> 
Enter text:<input type="text" name="name[2]"><input type="submit" name="submit" value="submit">
</form>
</body>
</html>

Re: [HELP]Getting values from mulitple textbox using array

Posted: Wed Jan 26, 2011 8:55 pm
by Jonah Bron
When PHP receives POST/GET field arrays, it creates sub-arrays inside of the normal $_POST/$_GET indices. So if I were to run print_r() on $_POST in your code, I would get this:
[text]
Array
(
[ text] => Array
(
[1] => value
[2] => value
)

[submit] => submit
)[/text]
value being whatever was in those text boxes. So, we would do what you want like this:

Code: Select all

$try_array = $_POST['name'];

foreach ($try_array as $try){
    echo $try;
}
But note that you'll get an error every time you load that page, because it's trying to get $_POST['name'] when it's not there (if the form hasn't been submitted). So, we need to check for it's existence every time.

Code: Select all

if (isset($_POST['name'])) {
    $try_array = $_POST['name'];
    
    foreach ($try_array as $try){
        echo $try;
    }
}
If you weren't seeing errors before, you really need to open up your php.ini config file and enable them.
But we face another problem: cross-site scripting (XSS). This is a security vulnerability in which a malicious user could insert HTML/Javascript into those text boxes, and your site would run it. This is dangerous because the person then can access cookies and all kinds of bad stuff. But don't panic, PHP has a function called htmlentities() that can eliminate that.

Code: Select all

if (isset($_POST['name'])) {
    $try_array = htmlentities($_POST['name']);
    
    foreach ($try_array as $try){
        echo $try;
    }
}
It will convert stuff like < into <, > into > etc.

Re: [HELP]Getting values from mulitple textbox using array

Posted: Sun Jan 30, 2011 7:20 am
by aicrop
thanks that helps a lot!