Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass POST variable by links to own pages?

Hi i wannna get variable $_POST by link to self pages. Example :

<?PHP
$var = 'PIG';
echo "<a href='test.php?var=$var'>link</a>";

if (isset($_POST['var']))
{
echo $_POST['var']);
}


?>

it links to own pages. (test.php) It not works, who can help me please. Thanks

like image 590
Bijak Antusias Sufi Avatar asked Jul 31 '11 01:07

Bijak Antusias Sufi


1 Answers

A link cannot POST data, only GET.

In contrast to the GET request method where only a URL and headers are sent to the server, POST requests also include a message body. This allows for arbitrary length data of any type to be sent to the server.

Basically, a POST requires two requests, 1) the server receives the "normal" request, with an extra header value indicating that more data needs to be sent. At that point, the server sends an acknowledge and 2) the client sends the POST body. This behavior cannot be achieved only with a link.

However, there are solutions to this and I have seen some technique, among others, outputting a form with an autosubmit, something like

<form name="frm" method="post" action="http://your.domain.com/path/to/page.php?param1=1&param2=2">
<input type="hidden" name="foo" value="bar" />
</form>
<script type="text/javascript">
    document.forms["frm"].submit();
</script>

which would result into calling page.php with these arguments

$_GET = array('param1' => '1', 'param2' => '2');
$_POST = array('foo' => 'bar');

Note that this is a simple "redirect" method, but you can create <a> elements to actually trigger some hidden form like that instead of using the standard link. (untested code)

<a href="http://your.domain.com/path/to/page.php?param1=1&param2=2" onclick="return dopost(this.href, {foo:'bar'});">A simple link</a>
<script type="text/javascript">
   function dopost(url, params) {
       var pe = '';
       for (var param : params) {
           pe += '<input type="hidden" name="'+param+'" value="'+params[param]+'" />';
       }
       var frmName = "frm" + new Date().getTime();
       var form = '<form name="'+frmName+'" method="post" action="'+url'">'+pe+'</form>';
       var wrapper = document.createElement("div");
       wrapper.innerHTML = form;
       document.body.appendChild(wrapper);
       document.forms[frmName].submit();
   }
</script>

This is probably what you need, actually.

like image 198
Yanick Rochon Avatar answered Sep 28 '22 09:09

Yanick Rochon