Cannot get username from form (using "post) - php

First of all I apologize for the noobish nature of my question. I have tried to search the internet for a solution, so far with little luck. I therefore turn to the awesome people of StackOverflow, as this usually gets the problems solved quite fast.
I am trying to make a very simple login function for a website. It consists of a HTML-form and a php login script. The problem is that the username (and password) does not seem to get passed from the form to the login script. Starting with the form, it looks like this:
<form name="loginForm" method="post" action="loginScript.php">
<table style="position: absolute; top:55%; left:50%; transform: translate(-50%, -50%)">
<tr>
<td>Brugernavn:</td><td><input name="edUsername" type="text" id="username" autofocus></td>
</tr>
<tr>
<td>Adgangskode:</td><td><input name="edPassword" type="password" id="password"><br></td>
</tr>
<tr>
<td style ="font-size: 10px;">Glemt din adgangskode?</td>
<td style="text-align: right;"><input name="Submit" type="submit" value="Log ind"></td>
</tr>
</table>
</form>
So the information i need in my login script is the username and password data. I try to obtain these with the filter_input() since I read that this was safer than $_POST[]. In the login script it looks like this:
// Get username and password from post form
$ed_user = filter_input(INPUT_POST, 'username');
$ed_pass = filter_input(INPUT_POST, 'password');
echo $ed_user;
The "echo" part is just a temporary line, to check if there is indeed a username retrieved. So far this is not the case. So my question is, what the heck am I doing wrong?

Rewrite as
$ed_user = filter_input(INPUT_POST, 'edUsername');
$ed_pass = filter_input(INPUT_POST, 'edPassword');
Use the name of the field instead of the id.

You've got the names wrong, Check below.
$ed_user = filter_input(INPUT_POST, 'edUsername');
$ed_pass = filter_input(INPUT_POST, 'edPassword');

Your mistake is that you're using input's id attribute instead of the name.
// Get username and password from post form
$ed_user = filter_input(INPUT_POST, 'edUsername');
$ed_pass = filter_input(INPUT_POST, 'edPassword');
echo $ed_user;
Or you could swap the attributes so the PHP code is left as is.
As for the differences between id and name attributes check out another question.

Related

No data submitted from a form

I have created a simple HTML form containing just one field. When I press submit some PHP code that I have written gets called and outputs text that would include submitted data if everything was working. But no submitted text gets printed by the PHP. The form has been created on a Godaddy HTML page and the form is as follows:
<FORM BORDER="1" action="http://www.bestpro.com.au/wordpress/PHB_action.php"
method="post" enctype="application/x-www-form-urlencoded"
eenctype="multipart/form-data" name="PHBForm" accept-charset="ISO-8859-1"
ienctype="text/plain">
<TABLE>
<TR>
<TD>First name:</TD><TD><INPUT type="text" name="firstname" id="firstname"></TD>
<TD></TD><TD></TD>
<TD> </TD><TD> </TD>
</TR>
<TR>
<TD> </TD><TD> </TD>
<TD> </TD><TD></TD>
<TD> </TD><TD><input type="submit" value="Submit"></TD>
</TABLE>
</FORM>
The PHP code output starts as follows:
This is where we end up.
Using `$_POST["firstname"]` which outputs nothing.
Using `htmlspecialchars($_POST["firstname"])` which also outputs nothing.
Question:
The PHP output doesn't include the value that I entered into the field.
Can anyone see what I am doing incorrectly?
I see nothing wrong here, so I can only assume it is something wrong with how you output it on your PHB_action.php page.
You say that you're placing $_POST['firstname'] on your page, but have you actually made sure to echo or print it to the page?
You can do this like so:
echo $firstname = $_POST['firstname']; // notice the echo placed before
or
$firstname = $_POST['firstname'];
print("$firstname");
EDIT:
I've notice you have put your post data inside of single quotation marks when echoing out to your page.
You must concatenate on your data rather than putting them inside of single quotes when echoing, like so:
echo 'Using' . $_POST['firstname']; // notice the dot in between the string and the post data.
Either that, or you have not installed PHP correctly (or at all) onto your server.
Hope this helps
So, this is pretty straight forward and I have written it up and will explain each bit as i go.
The PHP you need for this is:
<?php
if (isset($_POST['send']))
{
$fname = $_POST['firstName'];
if (!empty($fname))
{
echo "hello $fname";
} else {
echo "Please supply your first name.";
}
}
?>
$_POST['send'] is the name of your submit button, this will be the trigger for your PHP to initiate and run through the rest of the code.
$fname = $_POST['firstName']
This is just where I prefer to store the $_POST as a variable in the event you are going to re use it again it saves time writing the entire thing.
if(!empty)
if the username isn't empty (!empty meaning not empty) then perform the echo of $fname. however if it comes back as empty it will echo the else echo "please supply...;
Now for the form.
<form action="" method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td><input type="submit" name="send"></td>
</tr>
</table>
</form>
Just a straight forward form with a blank action on mine (I prefer to keep the PHP within the same file however I normally relay it back to a Class within a different file.
Each form input (First Name / Submit) must have a name="" value otherwise the PHP cannot read it and run with it.
I hope this makes sense and isn't too puzzling :)
Your input field should be inside tag and method should be post. Like:
<html>
<body>
<Form method=post>
<input id=mytextfield name=mytextfield type=text />
<input type=submit value=Submit />
</Form>
</body>
</html>

Only 1st letter of textarea going into database

Thanks to everyone who's given me such great advice over the last several months. I'm almost done with this project and I've learned so much. But I'm kinda stumped using textarea. I've googled and googled and can't find a solution.
This is not a public facing website so I'm not worried about sql injection and my organization uses an older version of PHP so I have to use mysql_query versus mysqli_query.
My problem is I have to echo two things from my database into a form so the user can edit and then update the database with the new inputs. One is a small string of text that I display using input="text". However the other is a longer string that lists a set of instructions so I'm using because it's too much for a text box. However when I run my update query only the first letter of the textarea string gets updated into my database. The textbox string works just fine. Here's my code
getrcs.php
<html>
<form>
<body>
<?php
$q = intval($_GET['q']);
include ('database_connect.php');
$sql= "SELECT * FROM RDS_REFERENCE WHERE ID = '".$q."'";
$query_result=mysql_query($sql);
?>
<table>
<tbody>
<?php
while($row = mysql_fetch_array($query_result)) {
?>
<tr>
<td>
<label>Sub File Series Number/Title</label>
<input type="text" style="width:250px;" required="Required" name="sub_fs_num_tle1[]" value="<?php echo $row['SUB_FS_NUM_TITLE']?>/>
</td>
<td>
<label>Disposition Instructions</label>
<textarea name="disp_instr1" cols="40" rows="30" style="font-family: Arial, Helvetica sans-serif; font-size: 12px;"><?php echo $row['Disposition_Instructions'] ?></textarea>
</td>
</tr>
<?php
}
?>
</tbody>
</form>
</body>
</html>
And update_rcs.php
<?php
include('database_connect.php');
foreach($_POST['id'] as $row => $id)
{
$sub_fs_num_tle1 = $_POST['sub_fs_num_tle1][$row];
$disp_instr1 = $_POST['disp_instr1'][$row];
$rcs_reference_update1 = "UPDATE RDS REFERENCE SET
SUB_FS_NUM_TITLE = '$sub_fs_num_tle1',
Disposition_Instructions = '$disp_instr1'
";
mysql_query($rcs_reference_update1) or die("Could not update".mysql_error());
}
header('Location:rcs_maint.php');
?>
Since your input is name="disp_instr1" the $_POST['disp_instr1'] is a string, not an array. This means that $_POST['disp_instr1'][$row] will output whatever character $row is in that string.
Simple demo:
$test = 'test';
echo $test[0];
Outputs:
t
Live Demo: https://eval.in/541463
To solve the issue use:
$disp_instr1 = $_POST['disp_instr1'];
Also SQL injections aren't the only reason to use parameterized queries. If a single quote needs to go to your db it will fail as is.

AJAX .load() returns NULL

I'm building a website in PHP and I'm trying to implement asynchonous behaviour on some occasions, in this case to load an HTML form into an overlay and making it visible. This works as intended, however I'm now testing everything considering existing data.
So I basically created a variables.php file that sets values to the $_SESSION global and was working from there. Everything was working as expected on index.php, but as soon as I click the overlay I notice the values aren't passing through to populate the form that was added.
I already poked google for a few hours to no avail. I've added echo var_dump($_SESSION); on the index.php file and the values are all there. However on the overlay it returns NULL. I've even include_once("loginForm.php") right in the middle of index.php and that gave me the values. So there's something I'm missing in order to get the values to apply to .load() elements.
Here's some code:
variables.php
//added values to the $_SESSION global for testing purposes
$_SESSION['email'] = 'john#john.com';
$_SESSION['password'] = 'johnny';
$_SESSION['name'] = 'John';
$_SESSION['surname'] = 'Smith';
$_SESSION['country'] = 'UK';
$_SESSION['phoneOption'] = 'Mobile';
$_SESSION['phone'] = '987654321';
header-login.php
//this form accepts an email to check ifExists() and decide what's next
//the input #preLoginEmail assumes the value correctly
<form action="header-login.php" name="preLoginForm" id="preLoginForm" method="post">
<div id="login-part2">
<table id="preLoginTable">
<tr>
<td colspan="2">
<input type="text" id="preLoginEmail" title="Email" name="test-email" tabindex="1" size="10" maxlength="60" placeholder="Email" value="'. $email .'" />
</td>
</tr>
<tr>
<td><a title="forgotten password" href="header-login.php" id="preLoginForgot">forgot password?</a></td>
<td><input type="submit" class="btn1" name="preLoginRegisterButton" id="preLoginRegisterButton" tabindex="1" value="Login / Register" /></td>
</tr>
</table>
</div>
echo var_dump($_SESSION);//works
</form>
onClickEvents.js
//this call retrieves the HTML correctly although the variables dont get assigned to the input's value
$( "#preLoginForm" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
term = $form.find( "input[name='test-email']" ).val(),
url = $form.attr( "action" );
verifiedEmail = validateEmail(term);
if(verifiedEmail){
// Put the results in a div
$('#olContainer').load("../inc/loginForm.php");
overlayOn();
}
else {
$('.session-stat').css({ "background-color": "#A60000" });
}
});
loginForm.php
//when this form is loaded there are no values in the inputs and var_dump($_SESSION) returns NULL
<form id="loginForm" name="loginForm" method="post" action="booking.php">
//some blocks are static and created in plain html
<input name="email" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="<?php echo $email; ?>" />
//others are php variables to make the if/else statement more readable
$countryBlock ='<input name="agentuser" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="'. $country .'" />';
echo var_dump($_SESSION); //NULL
I kinda ran out of ways to figure out what's going wrong, and I just started learning about AJAX this week. If u need anything else just let me know in comments I'll try to be quick to edit. Thanks in advance.
#Fernando - I didn't know which way you decided to go, but if you have to use $_SESSION for this, include:
session_start();
at the beginning of each file you plan to use sessions on, before any content is rendered. Also, be careful to have a means for your users to overwrite their values, ie. with a post, so that once a value gets put in session, there is a way to change it and it doesn't keep overwriting the (new) value. I usually clear out my sessions on Page one of the form. You can do a
unset($_SESSION['test-email']);
...to unset the values. You can use a foreach loop here too.
A great site to compare the speed of loops in PHP is http://www.phpbench.com/ also.
Best of luck!

HTML form acting as get instead of post

I'm pretty new to the whole PHP/HTML deal, and I've run into a problem that I don't know how to fix. It's a pretty simple form that lets you enter data into database. The PHP code is as following:
<?
include("../sqlcontext.php");
$foo = mysql_query("SELECT*FROM users WHERE checksum='".$_COOKIE['userCookie']."'");
if($_COOKIE['userCookie'] == '' || !mysql_num_rows($foo)){
echo 'Du er ikke logget ind :( log ind her';
}
else{
if($_POST['genreKnap']){
$nameGenre = $_POST['nameGenre'];
$textGenre = $_POST['textGenre'];
$succes = mysql_query("INSERT INTO genre VALUES('null','$nameGenre','$textGenre')");
if($succes){
echo 'Yay!';
}else {
echo 'Oh no';
}
}
?>
The form is as following:
<form name="form1" method="post" enctype="text/plain" action="">
<table>
<tr>
<td>Genre navn:</td>
<td><input type="text" name="nameGenre" id="nameGenre" style="width:100%; padding-right: 1px" /></td>
</tr>
<tr>
<td>Genre beskrivelse:</td>
<td><textarea name="textGenre" id="textGenre" style="width:100%; padding-right: 1px"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="genreKnap" id="genreKnap" value="Go!"/></td>
</tr>
</table>
</form>
Whenever I press the submit button, it seems as though it acts as if it was a get method and not a post.
Aha!!!
You are not posting the form correctly.
Set the
action=""
to
action="code.php"
Assuming your php page is called code.php. Just change it to the name/path of the php page and the form will send the data to your php code to process.
When you leave action="" to blank, it posts the data to itself (the same page). It is not acting as GET, it is still acting as POST, but posting to the wrong place. I think you worded the title of the question wrong.
What do you mean it is acting like get instead of post.
Can you not read $_POST variables in your PHP?
remove the 'enctype="text/plain"' in your form code.
enctype="text/plain"
Take that out. It is provided for debugging purposes only and doesn't generate anything that is sane to parse with a machine.
Valid form enctypes:
application/x-www-form-urlencoded: This is the default content type
multipart/form-data
The content type "application/x-www-form-urlencoded" is inefficient
for sending large quantities of binary data or text containing
non-ASCII characters. The content type "multipart/form-data" should be
used for submitting forms that contain files, non-ASCII data, and
binary data.
Source: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3.4
You're all ignoring the primary question and focusing on irrelevent items.
First of all more than anything he's using a short php opener <? not <?php now not every web server accepts short openers first up check that.
Echo out your $_POST vars and see if they're returning the correct items
echo "POSTS BELOW<br />";
echo $_POST['nameGenre']."<br />";
echo $_POST['textGenre']."<br />";
echo "<br />GETS BELOW<br />";
echo $_GET['nameGenre']."<br />";
echo $_GET['textGenre']."<br />";
Put this block of code directly below your php opener see what data it returns.
Also this if($_POST['genreKnap']){ is generally a bad way of doing it as its user input the safest way is a hidden field <input type="hidden" name="action" id="action" value="dopost" /> and change your if clause to if($_POST['action']=="dopost && isset($_POST['action'])){
Also set your form action="" to the actual page name not blank
Give all that a try and if its still not working we'll try something different
If you are send normal data without any files by the form .
Then enctype is not always needed .
But even if you want to include it
The correct way is :
enctype="multipart/form-data"
Also give a url in the action method of the form : <form action='example.php'>
I hope it solves the problem .

PHP $_POST returning null value for unseen reason

My issue is I have a PHP $_POST that returns a null or empty value, and I personally do not see any error with my code (but I know its there) and I can't really step away from it for a few hours since I am on a time schedule. So, I was hoping someone could help me out ;)
Here is what I have, basically:
<table border="0" align="center">
<tr>
<td>
<div id="lvl3">Project Name:</div>
</td>
<td>
<input type="text" name="prjname" maxlength="250">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" name="prjsubmitname">
<input type="button" value="Cancel" onclick="$('#popupoverlay').hide(); $('#prjpopupbox').hide(); $('#prjname').hide(); $('#prjdescription').hide(); $('#prjversion').hide(); $('#prjrelease').hide();">
</td>
</tr>
This is my table for editing a project name- what is important here is the textbox input, I think.
Next I have my PHP:
//Did the user change the Project Name
if (isset($_POST['prjsubmitname']))
{
//Is the input empty
if (!trim($_POST['prjname']))
{
//Input is empty
echo('<script>senderror("Please enter a valid Project Name empty");</script>');
} else {
//Input isnt empty, assign variables
$url = geturlext();
$prjname = mysql_real_escape_string(trim($_POST['prjname']));
//Is input invalid
if (strcasecmp($prjname, "main") == 0 | $prjname == "404")
{
//Input is invalid
echo('<script>senderror("Please enter a valid Project Name invalid");</script>');
} else {
//Input is valid, connect to database
dbconnect();
$checkquery = mysql_query("SELECT * FROM projects WHERE name = '$prjname'") or die(mysql_error());
$check = mysql_num_rows($checkquery);
//Does Project Name already exist
if ($check == 0)
{
//No it does not
$updatequery = mysql_query("UPDATE projects SET name = '$prjname' WHERE name = '$url'") or die(mysql_error());
echo("<script>location.href='index.php?page=" . $prjname . "'</script>");
} else {
//Yes it does
echo('<script>senderror("That Project Name already exists");</script>');
}
}
}
}
This is where I get my issue; No matter what I enter in the textbox, I always get the error message for 'Input is empty'. I have printed the output of $_POST['prjname'] and it is indeed empty.
Now the weird part is, I have this exact same (at least I think) setup for changing the project description, and it works flawlessly. For the sake of comparison- i've included the same parts of the project description editor below.
The table:
<table border="0" align="center">
<tr>
<td>
<div id="lvl3">Project Description:</div>
</td>
<td>
<textarea type="text" name="prjdescription" maxlength="750" style="width:300px; height:100px; resize:none;"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" name="prjsubmitdescription">
<input type="button" value="Cancel" onclick="$('#popupoverlay').hide(); $('#prjpopupbox').hide(); $('#prjname').hide(); $('#prjdescription').hide(); $('#prjversion').hide(); $('#prjrelease').hide();">
</td>
</tr>
And the PHP:
//Did the user change the Project Description
if (isset($_POST['prjsubmitdescription']))
{
//Is the input empty
if (!trim($_POST['prjdescription']))
{
//Input is empty
echo('<script>senderror("Please enter a valid Project Description");</script>');
} else {
//Input isnt empty, do stuff
$url = geturlext();
$prjdescription = mysql_real_escape_string(trim($_POST['prjdescription']));
//Connect and change description
dbconnect();
$updatequery = mysql_query("UPDATE projects SET description = '$prjdescription' WHERE name = '$url'") or die(mysql_error());
echo("<script>location.href='index.php?page=" . $url . "'</script>");
}
}
For clarification, both tables are in the same form tag, and the PHP is right next to eachother.
No errors on Firebug, matter of fact Firebug doesn't give me anything. Other than that, I'm sure it's some really small typo that I am overlooking.
I have found a solution to this issue:
Renaming the variable '$prjname' in the Project Name editing PHP fixes the issue.
It would seem that having a variable ($prjname) with the same name as a $_POST (['prjname']) returns an empty or null string. No idea why.
Thanks to those who tried to help
EDIT: Actually, I get the error again if I only change the variable name ($prjname)- It only fixes when I change the $_POST name... Odd.
Looking at the description of above issue, we can conclude that form elements must be encapsulated within form tag ,then only form data will be posted to server.
So as a solution to your problem, you need to define input elements within form tag.

Categories