-1

I have file index.php with form and I want to process the form with other php file. How can I echo the result to get "Hello name"?

Here's the code:

 <form action="action.php" method="post">
    Name:<input type="text" name="name">
    <button type="submit" name="submit">Submit</button>
</form>
<p>Hello {here goes the name} </p>

And other php file:

<?php
    
    if(isset($_POST['submit'])){
        echo $_POST['name'];
    }
    
    ?>
  • `echo "Hello".$_POST['name'];` – ADyson Apr 20 '21 at 06:29
  • I strongly recommend not to [name a form element `submit`](https://stackoverflow.com/questions/39345107/javascript-submit-is-not-submitting-the-form), but if "other php" is action.php, the code is not showing on the same page as the form - the statement `

    Hello {here goes the name}

    ` will not work on the same page. But also [see if there are errors somewhere](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display)
    – mplungjan Apr 20 '21 at 06:31
  • You could likely benefit from using a session variable – mplungjan Apr 20 '21 at 06:37

1 Answers1

-1

You have to put them in the same file in order for this to work or to use AJAX for form submission and some JS.

 <form action="" method="post">
  Name:<input type="text" name="name">
  <button type="submit" name="submit">Submit</button>
</form>
<?php

if(isset($_POST['submit'])){
  ?>
    <p>Hello <?=$_POST['name']?></p>
 <?php
}
?>
mplungjan
  • 134,906
  • 25
  • 152
  • 209
  • Isn't the use of the `action` attribute of the `form` tag to call another page? – Nigel Ren Apr 20 '21 at 06:34
  • 2
    This is VERY XSS sensitive code – mplungjan Apr 20 '21 at 06:34
  • 2
    @mplungjan, my understanding of this answer was that you can't call another page with form submission you have to use AJAX. – Nigel Ren Apr 20 '21 at 06:37
  • Is not XSS complaint but he asked for the solution for a solution to print that variable from post, you can also use `action=""` but is not a safe solution also – Alexandru Corlan Apr 20 '21 at 06:38
  • 2
    `

    Hello =$_POST['name']?>

    ` is a problem. I can post `name=`
    – mplungjan Apr 20 '21 at 06:44
  • @AlexandruCorlan or you can leave the action attribute out and not even mention it, it will then also post to the same page. – Ivan86 Apr 20 '21 at 07:59
  • You also don't have to put this in the same file for it to work. For example, you submit the form to other.php which uses `header("Location: http://www.example.com/index.php?name=peter");`. This will redirect you back to index.php setting the variable name as `$_GET['name']`. – Ivan86 Apr 20 '21 at 08:00
  • or you can set `$_SESSION['name']` in another file and then use it in index page after redirect... as @mplungjan mentioned in the comments. – Ivan86 Apr 20 '21 at 08:03