Adriaan Joubert Adriaan Joubert - 2 months ago 10
HTML Question

PHP session data from form not being passed and/or not printing to screen

I am playing around with using my Raspberry Pi 3 as a web server.

I would like to learn more about processing user input through forms.

I have two files in

/var/www/html
, viz.
form.html
and
form.php
:

form.html
:

<form action="form.php" method="post">
<input type="text" name="varname"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

<?php

session_start();

if (isset($_POST['Submit'])) {
$_SESSION['varname'] = $_POST['varname'];
}
?>


form.php
:

<?php

session_start();

$var_value = htmlspecialchars($_SESSION['varname']);

echo $var_value;

?>


When I click Submit! on
form.html
the browser takes me to
form.php
which displays a blank page.

Naturally, I would like it to print
$var_value
to the screen.

Is there problem in my code, or could it be some other server-side issue?

Answer

Change your form.html extension to form.php,

And you may use the below code to achieve your work.

Form.php // Single page

<?php
session_start(); // Should be in first Line
if (isset($_POST['Submit'])) { 
    $_SESSION['varname'] = $_POST['varname'];
    $var_value = htmlspecialchars($_SESSION['varname']);
    echo $var_value;
    }
?>
<form method="post">
<input type="text" name="varname"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
?>

Otherwise: // Multiple Page

form.php

<form action="some_form.php" method="post">
<input type="text" name="varname"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

some_form.php

<?php
session_start();
if (isset($_POST['Submit'])) { 
    $_SESSION['varname'] = $_POST['varname'];
    $var_value = htmlspecialchars($_SESSION['varname']);
    echo $var_value;
    }
?>
Comments