Home > other >  how to use $_POST to change some contents forever
how to use $_POST to change some contents forever

Time:04-18

I am trying to populate data from a website to another wensite: a.html:

<form action="b.php" method="post">
<textarea id="myProjects" name="mp"></textarea>
<input id="submit" type="submit" value="Submit" />
</form>

in b.php:

<?php $content=$_POST['mp'];
echo "you entered ".$content;
?>

This works in a very strange way, when I click submit button, I am directed to the b.php page, and I can see what I entered. But if I reload this page, not refresh, my contents disappear, and throwWarning: Undefined array key "mp" It looks like data received from $_POST is "temporarily" stored. I am new to PHP, so I am not sure how can I figure it out.

CodePudding user response:

You can use the PHP SESSION feature to keep the data persistent:

in b.php:

<?php
   // Start the session
   session_start();

   // save the input var as a SESSION property
   if (isset($_POST['mp'])) {
      $_SESSION['content'] = $_POST['mp'];
   }

   // display the property
   echo "you entered " . $_SESSION['content'];

CodePudding user response:

Generally speaking, what you want to do is to store the value of $_POST['mp'] into the $_SESSION variable so that it persists from one page request to the next.

However doing it by manipulating these variables directly is generally bad practice. Unless you sanitize the user input you are open to a myriad of scripting attacks. Although there is some learning involved, you are much better off using an established PHP framework (for example Laravel), which has a full set of validation functions, and manages the process of starting the session for you. A good framework will also help you in many other ways.

  • Related