0

I have been trying to create a php script which takes any number from a text form, and puts it into an array. Then I want to loop through the array and output each number.

So far with some searching around on Google, I've come up with this piece of code. Unfortunatly it doesn't work. The strange thing is, I actually got it working at some point, but somehow the code wouldn't function anymore without actually changing anything in the script.

Can anyone help me complete this, I have my version which worked at some point but doesn't anymore.

(I know I should filter input but since this is just an exercise it doesn't really matter.)

<html>
<head>
    <title>13.13</title>

<body>
    <h2> Inputting numbers into array through form</h2>
    <br>
    <br>

    <form>
        <input type="text" name="number" />
        <input type="button" value="submit" name="submit" />
    </form>

<?php
    session_start();    

        if (isset($_REQUEST['submit'])) {
            $number = $_REQUEST['number'];

            if (!isSet($_SESSION['number'])) {
                $_SESSION['number'] = array();
            }
        array_push($_SESSION['number'], $number);

        foreach($_SESSION['number'] as $key => $val) {
            echo $key . ">" . $val;
        }
    }

?>    

</body>
</html>
Fabian Fagerholm
  • 4,099
  • 1
  • 35
  • 45
Dennis VW
  • 2,977
  • 1
  • 15
  • 36

2 Answers2

1

Move session_start() to the top of your code before any HTML output. You can't start a session after headers have already been sent - and they have been sent because HTML output has been sent.

It's just good practice anyway.

Oliver Williams
  • 5,966
  • 7
  • 36
  • 78
0

You need to define a method in your form.

Here' the full code, also, always place session_start at the top of the page.

<?php
    session_start();    

        if (isset($_REQUEST['submit'])) {
            $number = $_REQUEST['number'];

            if (!isSet($_SESSION['number'])) {
                $_SESSION['number'] = array();
            }
        array_push($_SESSION['number'], $number);

       /* foreach($_SESSION['number'] as $key => $val) {
            echo $key . ">" . $val;
        }
        */
        var_dump($_SESSION['number']);
    }

?>    

<html>
<head>
    <title>13.13</title>

<body>
    <h2> Inputting numbers into array through form</h2>
    <br>
    <br>

    <form method="post" action="#">
        <input type="text" name="number" />
        <input type="submit" value="submit" name="submit" />
    </form>



</body>

Output enter image description here

Akshay
  • 2,244
  • 3
  • 15
  • 34
  • 1
    FWIW, it was explained in the comments that `method="post"` was not needed as apparently forms default to `method="get"`. That can be read from `$_REQUEST`. – HPierce Oct 19 '15 at 15:15