Get input from HTML form in PHP - 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>

Related

else Statement not being triggered after if(empty($var))

I've tried searching for a solution to my problem on stackoverflow but can't seem to find one that fits my situation.
<?php
if (empty($userName)){
print <<<HERE
<form>
Please enter your name:
<input type="text" name="userName">
<br>
<input type="submit">
</form>
HERE;
}
else {
print "<h3>Hi there, $userName!</h3>";
} //end
?>
When I enter a value into the form field it is assigned to the variable $userName but the issue occurs when the else statement is not being triggered after that value has been added.
I hope I've been clear enough, looking forward to a possible solution.
Thank You.
this code only works if register_globals is enabled, and register_global was removed since PHP 5.4.0, so this code won't work in PHP 5.4+, nor will it work if register_globals is disabled in PHP.ini (and it has been disabled-by-default since PHP 4.2.0), try
if (empty($_GET['userName'])){
instead. also, seems you're wide open to XSS here, the variable needs to be escaped before being echoed back to the user, or you open your website to xss attacks by hackers.
try
function hhb_tohtml(string $str):string
{
return htmlentities($str, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE | ENT_DISALLOWED, 'UTF-8', true);
}
print "<h3>Hi there, ".hhb_tohtml($_GET['userName'])."!</h3>";
How are you retrieving your value from your variable? I don't see that in your question.
<?php
if(isset($_POST['userName'])) {
$userName = $_POST['userName']; //This will take the userName input and put it into a variable for you to test.
}
if (empty($userName)){
print <<<HERE
<form>
Please enter your name:
<input type="text" name="userName">
<br>
<input type="submit">
</form>
HERE;
}
else {
print "<h3>Hi there, $userName!</h3>";
} //end
?>

Cannot get posted variables to echo in the form

It seems my code is correct, however the posted variables in the form will not echo in the update user settings page in the form. I have echoed the posted ids from the input in the database but I cannot get the variables to show.
I have done this in Codeigniter fine but am trying to do it in pure php with my own framework.
$users = new Users($db); comes from my init.php file that is called at the beginning of the file below.
when I
<?php var_dump($user['first_name'])?>
I get Null
<input type="text" name="first_name" value="<?php if (isset($_POST['first_name']) )
{echo htmlentities(strip_tags($_POST['first_name']));} else { echo
$user['first_name']; }?>">
Hoi Stephen,
Try print_r($_POST["first_name"]); instead of var_dump();
or just for all:
print_r($_POST);
best regards ....
add this at the top of your html page
#extract($_REQUEST);
and put is just to check and after checking remove the below line
print_r($_REQUEST);
hope this help .

use php to change a html elements inner text

I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.

Including form data in another page

When I post my form data:
<form action="layouts.php" method="post">
<input type="text" name="bgcolor">
<input type="submit" value="Submit" align="middle">
</form>
to a php page, "layouts.php", it returns the string, as expected.:
$bgcolor = $_POST['bgcolor'];
echo $bgcolor; //returns "red"
echo gettype($bgcolor); // returns "string"
But when I include "layouts.php" in another page it returns NULL.
<?php
include("php/layouts.php");
echo $bgcolor; //
echo gettype($bgcolor); //returns "NULL"
?>
How do I pass the variable to another page?
You'll have to use a session to have variables float around in between files like that.
It's quite simple to setup. In the beginning of each PHP file, you add this code to begin a session:
session_start();
You can store variables inside of a session like this:
$_SESSION['foo'] = 'bar';
And you can reference them across pages (make sure you run session_start() on all of the pages which will use sessions).
layouts.php
<?php
session_start();
$bgcolor = $_POST['bgcolor'];
$_SESSION['bgcolor'] = $bgcolor;
?>
new.php
<?php
session_start();
echo $_SESSION['bgcolor'];
?>
Give the form two action="" and see what happens. I just tried that on a script of mine and it worked fine.
A more proper way to solve this might exist, but that is an option.

Passing values form one form into another - a weird case

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

Categories