Passing values form one form into another - a weird case - php

Please have a look to the following code:
<?php
$nomeDominio='';
if (isset($_GET['infoDominio']))
{
$nomeDominio = $_GET['nomeDominio'];
echo "I'm getting ".$nomeDominio;
}
if (isset($_POST['atualizarDominio']))
{
echo "I'm posting ".$nomeDominio;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Case 99</title>
</head>
<body>
<form name="infoDominio" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="get">
<input id="nome_dominio" type="text" name="nomeDominio" value="<?php echo $nomeDominio; ?>"/>
<br />
<button name="infoDominio" type="submit">Obtem informacao</button>
</form>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" name="atualizarDominio" method="post">
<input type="hidden" value="<?php echo $nomeDominio ?>" name="nome-dominio"/>
<br />
<button type="submit" name="atualizarDominio">atualizar domínio</button>
</form>
</body>
</html>
You can copy/paste - it will serve as test case.
Like this, IF we get and then we post:
The value from GET WILL NOT pass into POST.
The thing is:
If we just change the action= property of the second form element to, instead of having the $_SERVER['PHP_SELF'], to have just action="";
you will notice that the value WILL pass.
My question is:
Why?
ADDITIONAL NOTE:
This is not something to solve. Instead, this is something to understand why is it happening this way.
Why, if we change the action on the second form to action="", the value stored in $nomeDominio pass from one conditional into another? The code sample can be used by itself, so you can perfectly test this very easily and see what I'm talking about.

{
$nomeDominio = $_GET['nomeDominio'];
echo "I'm getting ".$nomeDominio;
}
if (isset($_POST['atualizarDominio']))
{
$nomeDominio = $_POST['nomeDominio']; //THIS HERE
echo "I'm posting ".$nomeDominio;
}
you are missing the line with comment THIS HERE
You wanted to pass the _GET['nomeDominio'] from the first form to a hidden field of the second form right? Then when we submit the SECOND form you echo nomeDominio's value again (from the second form's hidden field).
You where missing and assignement in the $_POST: $nomeDominio = $_POST['nomeDominio'];
There you go. If you do not undesrtand I do not know how to say differently.

You are being inconsistent. The top form uses nomeDominio for the element name, where as the bottom form uses nome-dominio. My hunch is that is why one shows up and the other does not, you are accessing the wrong name.
EDIT
Further elaboration:
if (isset($_POST['nomeDominio']))
{
echo "I'm posting ".$_POST['nomeDominio'];
}
Replacing that code, and assuming you chose the nomeDominio for the name, that should work.

If I'm understanding you correctly, you want to be able to propagate the $_GET value even through a POST method. You can do this by appending the query string to the action attribute of the second POST form:
<form action="<?php echo htmlentities($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'] );?>" name="atualizarDominio" method="post">
EDIT: Ok, I think I understand a bit better.
In the first case, (with the second form action as $_SERVER['PHP_SELF']), you are forcing the form to post the data to the page without all the added $_GET data (if you look at the URL, the $_GET data is appended to the file name after the ?), so when you look for $_GET['infoDominio'], it doesn't exist any more, and therefore $nomeDominio is still set to an empty string. When you send the POST form, the $_POST['atualizarDominio'] IS set, and you get the I'm posting message, but with no value set in $nomeDominio.
Now when you change the action of the second form to "", you are telling the browser to send the user to the same page you were just on, which includes all the $_GET data in the URL (check it - you find the ?nomeDominio=whatever&infoDominio= in the address bar still). When you submit the second form after having submitted the first form, all the $_GET data is propagated, and so $_GET['infoDominio'] is set, $nomeDominio is assigned whatever value you put in the first form, and thus shows up in the page after submitting the second form.
The fact that the form name and the submit button name are the same shouldn't affect it.
If I'm still misunderstanding what you're asking, please let me know. Otherwise I hope this helps.

You have done two mistake. First Mistake
if (isset($_POST['atualizarDominio']))
{
$nomeDominio = $_POST['nomeDominio']; ///Here
echo "I'm posting ".$nomeDominio;
}
Second Mistake
<input type = "hidden" value="<?php echo $nomeDominio; ?>" name="nomeDominio"/><br/>
name="nome-dominio" //This is another Mistake
name="nomedominio" //use it

Related

How to save POST data of a form after user submission without using Sessions, JSON, Ajax, Hidden input or another file

First of all I'll be sincere, I'm a student and I've been asked to do a task that seems impossible to me. I don't like asking questions because generally speaking I've always been able to fix my coding issues just by searching and learning, but this is the first time I've ever been on this possition.
I need to create a php file that contains a form with two inputs that the user fills. Once he clicks submit the website will show on top of it the two values. Till here I haven't had an issue, but here's the problem, the next time the user sends another submission, instead of clearing the last 2 values and showing 2 new ones, now there needs to be 4 values showing.
I know this is possible to do through JSON, the use of sessions, Ajax, hidden inputs or using another file (this last one is what I would decide to use if I could), but the teacher says we gotta do it on the same html file without the use of any of the methods listed earlier. He says it can be done through an Array that stores the data, but as I'll show in my example, when I do that the moment the user clicks submit the array values are erased and created from zero. I know the most logical thing to do is asking him, but I've already done that 4 times and he literally refuses to help me, so I really don't know what to do, other than asking here. I should point out that the answer has to be server side, because the subject is "Server-Side Programming".
Thank you for your help and sorry beforehand because I'm sure this will end up being a stupid question that can be easily answered.
For the sake of simplicity I erased everything that has to do with formatting. This is the code:
<?php
if (isset($_POST['activity']) && isset($_POST['time'])){
$agenda = array();
$activity = $_POST['activity'];
$time = $_POST['time'];
$text = $activity." ".$time;
array_push($agenda, $text);
foreach ($agenda as $arrayData){
print implode('", "', $agenda);
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<label for="Activity">Activity</label><br>
<input name= "activity" type="text"><br><br>
<label for="Time">Time</label><br>
<input name= "time" type="time"><br><br>
<input type="submit">
</form>
</body>
</html>
Your question was not very clear to be honest but I might have gotten something going for you.
<?php
$formaction = $_SERVER['PHP_SELF'];
if (isset($_POST['activity']) && isset($_POST['time'])){
$agenda = array();
//if the parameter was passed in the action url
if(isset($_GET['agenda'])) {
$agenda = explode(", ", $_GET['agenda']);
}
//set activity time
$text = $_POST['activity']." ".$_POST['time'];
//push into existing array the new values
array_push($agenda, $text);
//print everything
print implode(", ", $agenda);
//update the form action variable
$formaction = $_SERVER['PHP_SELF'] . "?agenda=" . implode(", ", $agenda);
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $formaction; ?>" method="POST">
<label for="Activity">Activity</label><br>
<input name= "activity" type="text"><br><br>
<label for="Time">Time</label><br>
<input name= "time" type="time"><br><br>
<input type="submit">
</form>
</body>
</html>
SUMMARY
Since you cant save the posted values into SESSION vars or HIDDEN input, the next best thing would be to append the previous results of the posted form into the form's action url.
When the form is posted, we verify if the query string agenda exists, if it does we explode it into an array called $agenda. We then concatenate the $_POST['activity'] and $_POST['time'] values and push it to the $agenda array. We then PRINT the array $agenda and update the $formaction variable to contain the new values that were added to the array.
In the HTML section we then set the <form action="" to be <form action="<?php echo $formaction; ?>

Get input from HTML form in PHP

I'm learning MySQL and PHP and got a problem with the input of the form. So I wrote a small test code, but it still cannot work. My PHP version is 5.6.
The code:
<html>
<body>
<form action ="2.php" method ="post">
Name: <input type="text" name="username" />
<input type ="submit" value="ok" />
</form>
</body>
</html>
and
<html>
<?php
if(isset($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>
The output of the project is always error, can't output the input before.
I tried single quote and double quote for username, both can't work.
I also tried to set always_populate_raw_post_data in php.ini to 0, -1, 1, all can't work.
I don't know where the problem is, though it might be very silly.
As what it look it is correct and should run without any problem. Make sure the above code is what you actually have. From my experience most of the form submission can be
you don't have correct name (username)
you might send incorrect http verb (post)
you submit to wrong endpoint (2.php)
From you code above everything look fine. if you still don't have the right result, you better debug it with var_dump, or print_r function with these built-in
$_POST, $_GET, $_REQUEST and check whether they contains you form variable name username
You are using isset as a variable, but it is a function that returns a boolean.
Change $user=isset($_POST['username']); to $user=$_POST['username'];
Another thing is that in both case you will end up in the IF condition even if there is no value added to the field so you can do something like this too:
<html>
<?php
if(isset($_POST['username']) && !empty($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>

Doing an inline if in the action of a form

I need to redirect the user to a site that gets the "Short_proj_name" information. So i did this:
<form action="Main.php?short_proj_name=<?=$_REQUEST['short_proj_name']?>" method="post" name="formProjName" target="_blank" id='frmProjName'>
However, upon searching, i found out that there are several reasons NOT to use $_REQUEST, one of them being security and all that. However, simply doing $_POST['short_proj_name'] or $_GET['short_proj_name'] never returns the information i need.
Basically, how would i go about doing an if statement that checks if the $_GET is empty, and does a $_POST instead? Can i do that in the action method of my form?
EDIT:
Adittionally, is it possible that maybe using both $_POST and $_GET return null, yet using $_REQUEST doesnt? As far as i know, $_REQUEST is both get and post together, but none of them returns any information
It works if i do it as so:
if(!empty($_POST['short_proj_name']))
{
$projName = $_POST['short_proj_name'];
}
elseif (!empty($_GET['short_proj_name']))
{
$projName = $_GET['short_proj_name'];
}
else
{
$projName = $_REQUEST['short_proj_name'];
}
But i'm not sure if that solves the security problem at all
I think the answer here is to always use _GET.
A form can actually send both _GET and _POST data based on what you use in the "action" attribute of the form. The action part doesn't care what you set the "method" attribute as.
From what you are showing above, the params are all in the "action" part of the form so these are always passed into _GET anyway. If the inputs were inside the form then those would be received via _POST
Here's an example.
In PHP I would receive $_GET['monkey'] = '1' and $_POST['lion'] = 1
<form method='post' action='receive.php?monkey=1'>
<input type='text' name='lion' value='1' />
<input type='submit' />
</form>
There shouldn't really ever be an instance where you need to check if the answer is in _GET or _POST and as mentioned in a comment, it's quite a security risk to use $_REQUEST or check if it's in _GET or _POST.
Most times, you can just push the page request URL back into the form "action" to ensure all the same _GET params are included on the form _POST.
The big mistake most people do is try to move them from _GET into hidden input fields inside a form thinking they need to do that to carry all that data through.
However, this type of function call might help you but I wouldn't approve of it.
function getRequestParam($param){
if(isset($_GET[$param])){return $_GET[$param];}
if(isset($_POST[$param])){return $_POST[$param];}
return "";
}
you can like
<?php
if(!empty($_POST))
{
$projName = $_POST['short_proj_name'];
}
else
{
$projName = $_GET['short_proj_name'];
}
?>
<form action="Main.php?short_proj_name=<?=$projName ?>" method="post" name="formProjName" target="_blank" id='frmProjName'>
but i think it's ugly
Here is a simple code :
<?php
if (isset($_GET) && $_GET['short_proj_name'] != '')
echo $_GET['short_proj_name'];
else if (isset($_POST) && $_POST['short_proj_name'] != '')
echo $_GET['short_proj_name'];
else
echo $_REQUEST['short_proj_name'];
?>
But if you get the value from a post or get, it can be anything so be careful...
If the "short_proj_name" is a file name, a nasty person can get access to other files just by guessing their names...

How to call php function on html form submit - in the same page

Okay so I have an html form in Add.html. When I click submit, I would like the data to be added to my database via php and then return to the same form with "instance added" or "failed blah blah."
The only way I know how is to set the form action to a separate php file and call that - but then the php file renders and I do not return to the same form.
I would like to not have to add a "return to form" button and would prefer to return to the form on submit with a status message.
Any better ways to do this?
A very simple way to do is to do following :
yourpage.php
<?php
if(isset($_POST)){
//data posted , save it to the database
//display message etc
}
?>
<form method="post" action="yourpage.php" >....
You can do a redirect in php, to the html form - and you can set a "flash message" - to show "instance added" by saving "instance added" to the session and showing that value when you redirect to html.
you can use this trick
<?php if (!isset $_POST['Nameofyourinput']){
?>
<form method="post" action="add.html">
// your inputs here along with the rest of html
</form>
<?php
}
else
{
// Update you database and do your things here
//in your request variable you can add the error you want if things didn't go well, for example
$result = mysqli_query($connection, $sql) or die('Instance not added !'.$req.'<br>'.mysql_error());
// and then
echo (" instance added")
};
The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".
Just give nothing to the action attribute. It will refer to your current page.
<form method="post" action="">
Other way to do this are:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Or just add '#'
<from method="post" action="#">
To handle php code. Write your code inside it.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// write your code here.
}
You should change your file extension from .html to .php .
Well you can employ old school AJAX. For instance,let's say we have a form that takes in a number N,and once we click the calculate button we should see the result the of 2^N displayed on the same page without the page being refreshed and the previous contents remaining in the same place. Here's the code
<html>
<head>
<title> Simple Math Example</title>
<script type="text/javascript">
var request = new XMLHttpRequest();
function createAjaxObject(){
request.onreadystatechange = applyChange;
request.open("POST","calculate.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("N="+document.getElementById('N').value);
}
function applyChange(){
if(request.status == 200 && request.readyState == 4){
document.getElementById('resultSpace').innerHTML = request.responseText;
}
}
</script>
</head>
<body>
<fieldset>
<legend>Enter N to get the value of 2<sup>N</sup> ::: </legend>
<input type="text" name = "N" id = "N">
<br>
<input type="button" value = "Calculate" onclick="createAjaxObject()">
</fieldset>
<div id="resultSpace">
</div>
</body>
The file calculate.php is the same file with the above code. When the calculate button is clicked, it calls a function createAjaxObject which takes in a value N and sends the value to the same file via the POST method. Once the calculation is done, a response will be sent. And if the response is successful, it will be sent to a function called applyChange which will render it to the same page via JavaScript.

Passing variables from HTML to PHP using form submission

I'm having a problem with the following piece of code. My desire is to have the heading Search results appear when the form is submitted using the 'Search' button, and I'm trying to implement this using the hidden input called searching. The idea is that when the form is submitted, this value is set to 'yes', and that will reveal the heading, but that is not what is happening here. Can anyone please tell me where I've gone wrong?
<html>
<head>
<title>Search</title>
</head>
<body>
<h1>Search</h1>
<form name = "search" action = "<?=$PHP_SELF?>" method = "get">
Search for <input type = "text" name = "find" />
<input type = "hidden" name = "searching" value = "yes" />
<input type = "submit" name = "search" value = "Search" />
</form>
<?php
if ($searching == "yes")
{
echo "<h2>Search results</h2>";
}
?>
</body>
</html>
#chris, you dont have to use a hidden field. you just can check if the form was submitted like this:
if(isset($_GET['search'])) echo 'foo';
#Boris, why should it be more secure to store the global into another var? I would agree if you check the global against a regex or whatever before.
Felix
You need to access the superglobal $_GET:
if($_GET["searching"]=="yes"){
//echo here
}
Unless you're using an old version of PHP, or a really unsecure configure, you're likely not using global variables.
Therefore, you need to first retrieve your $searching variable from the magic $_GET variable.
$searching = $_GET['searching'];

Categories