-4

I need some help about how to pass a variable with POST without using sessions.

Currently my code doesn't display value of the variable called $myvariable:

<?php
if(isset($_POST['testbutton'])){
if ($_POST['testbutton'] == 'Testing') {

echo $myvariable;
var_dump($_POST);

}
}

$myvariable = "hello world";

echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">';
echo '<input type="submit" value="Testing" name="testbutton"/>';
echo '</form>';

?>

What should I change in the code to be able to use $variable in POST['testbutton'] part of the code ?

Tass Mark
  • 337
  • 1
  • 2
  • 14

2 Answers2

2

Per my comment:

<?php

$myvariable = "hello world";

if(isset($_POST['testbutton'])){
    if ($_POST['testbutton'] == 'Testing') {

        echo $myvariable;
        var_dump($_POST);

    }
}



echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">';
echo '<input type="submit" value="Testing" name="testbutton"/>';
echo '</form>';

?>

UPDATE

If what you're trying to do is pass a variable from the page to $_POST you'll need to do as jeroen suggested and set a hidden input like this:

  echo '<input type="hidden" value="' . $myvariable .'" name="myvariable"/>';

this will then become $_POST["myvariable"]

WheatBeak
  • 1,036
  • 6
  • 12
2
<?php

// define $mvvariable here and PHP will not bring undefined error
$myvariable = "hello world";

if(isset($_POST['testbutton'])){
if ($_POST['testbutton'] == 'Testing') {

echo $myvariable;
var_dump($_POST);

}
}


echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">';
echo '<input type="submit" value="Testing" name="testbutton"/>';
echo '</form>';

?>
demogorgon
  • 49
  • 1
  • 9