PHP POST data not displaying - php

Im having some Trouble getting a simple PHP Login form to pass and check Login Data against a Database. For some reason the Data will not pass across from the Html Form to the PHP handler. Both are separate files but the code is as follows:
<html>
<head>
<title>Login</title>
</head>
<body>
<h1> Welcome please Login: </h1>
<form action="LoginCreate.php" method="post">
Username: <input type=“name” name=“username” id="username"><br/>
Password: <input type="password” name=“password” id="password"><br/>
<input type="submit" value="Login"> <input type="submit" value="Create Account">
</form>
Then for the PHP fike: (please note I have not yet added code for checking against the database.)
<?
$db=sqlite_open("database.db");
$username = sqlite_escape_string($_POST["username"]);
$password = sqlite_escape_string($_POST["password"]);
if(isset($_POST['Create Account'])){
sqlite_query($db,"INSERT INTO username (name) VALUES ('$username')");
sqlite_query($db,"INSERT INTO password (password) VALUES ('$password')");
echo "<p> Account Created. <p>";
}
else if(isset($_POST['Login'])){
echo "<p> Login Successful. <p>";
}
sqlite_close($db);
?>
What should be causing the Data not to be Posting correctly, have I got the syntax wrong somewhere? I'm using MicroApache and getting no Errors popup in Chrome.

You need to add the name="action" attribute to your submit buttons and check
if(isset($_POST['action'])) {
if ($_POST['action'] == 'Create Account') {
} elseif ($_POST['action'] == 'Login') {
}
}

Related

Hash a password in PHP before it goes to database, getting error

I had been researching a while and even got a hold of my hosting company for help but I have run into a problem with my PHP code and my database through my website. While the code that I have does hash the password that I enter, when I attempt to use the regular word password it comes up as incorrect. But if I copy and paste the hashed password, it works.
<?php
/* NEW.PHP
Allows user to create a new entry in the database
*/
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($email, $pass, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New User</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '') {
echo '<div style="padding:4px; border:1px soluser_id red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>Update User Info <br><br><br><br><br>Email: *</strong>
<input type="text" name="email" value="<?php echo $email; ?>" /><br/>
<strong>Password: *</strong> <input type="password" name="pass" value="<?php echo $pass; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit"> <br><br>Back to home?</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
// get form data, making sure it is valuser_id
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$pass = mysql_real_escape_string(htmlspecialchars($_POST['pass']));
// check to make sure both fields are entered
if ($email == '' || $pass == '') {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($email, $pass, $error);
} else {
// save the data to the database
mysql_query("INSERT users SET email='$email', pass=MD5('$pass')")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the form hasn't been submitted, display the form
renderForm('','','');
}
?>
As you can see it does hash it when I enter it into the database, but when I try to use the password the way it was originally spelled, it tells me it's the wrong one.
I would do the MD5 hashing on the PHP side. Print it before it goes into the database and try to compare it with the input given on the login form.
Also the htmlspecialchars is not needed in this case. Since your escaping is fine. If it would contain weird chars, it would match them against the database.
Also make sure your encoding type is set on both pages and make sure they're the same.
Without seeing your SELECT query in the login form I'd ask if you're MD5 hashing it when you select it as well?
mysql_query("SELECT * FROM users WHERE email='$email' AND pass=MD5('$pass')")
or die(mysql_error());
However, I agree that you shouldn't be using MD5 for password hashing. Check out http://php.net/manual/en/function.password-hash.php

Message that database is updated after redirecting

I'm new to PHP. I want to display a message that the database is updated after each time I redirect it after entering the data.
$sql = "INSERT INTO incoming (recipt, userid, username, money)
VALUES ('$recipt', '$userid', '$username', '$money')";
if ($conn->query($sql) === TRUE) {
echo "<script>window.open('incoming2.php','_self')</script>";
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
2 methods
1-you can redirect to any page adding message in get variable and check at that page if that variable is set then display it as message
//redirect to index.php with msg as
header('location:index.php?msg=2 records updated');
//at index page where you want to display message
if(isset($_GET['msg']) && !empty($_GET['msg'])){
echo '<p class="myMsg">'.$_GET['msg'].'</p>'
}
2- second method is to save the message to session variable and access it at page but you will have to unset that variable as below
//sending message assuming session_start() is written at to of all pages
$_SESSION['msg']="2 records updated or what ever your message is";
//where you want to display message
if(isset($_SESSION['msg']) && !empty($_SESSION['msg'])){
echo '<p class="myMsg">'.$_SESSION['msg'].'</p>'
unset($_SESSION['msg']);
}
Pass the message to your url:
echo "<script>window.open('incoming2.php?message=New+record+created+successfully','_self')</script>";
Then you can get the message in incoming2.php:
echo urldecode($_GET['message']);
Be careful: sanatize your input!
Use header("Location: incoming2.php"); instead of echoing JS.
Also, check your SQL statement for SQL injection vulnerabilities.
If you are posting the data on the same page you could do the following:
<?php
if(isset($_REQUEST["submit"])){
// mySQL code here
// return either success or failed
$confirmation="success";
}
?>
<html>
<head>
<title>Feedback</title>
</head>
<body>
<div>
<?php
if(isset($confirmation)){
echo $confirmation;
}
?>
</div>
<form method="post" action="">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" Value="Submit">
</form>
</body>
</html>
If you are sending the data to a separate page:
On the receiving page:
<?php
// mySQL code here
// return either success or failed
//redirect to index.php with confirmation as true or false
header('location:index.php?confirmation=success');
?>
and on the page that you Sent the data from:
<html>
<head>
<title>Feedback</title>
</head>
<body>
<div>
<?php
//at index page where you want to display message
if(isset($_GET['confirmation']) && !empty($_GET['confirmation'])){
echo $_GET['confirmation'];
}
?>
</div>
<form method="post" action="uploaddata.php">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" Value="Submit">
</form>
</body>
</html>
You can then use CSS3 animations to fade the message in and out for a better user experience :-)

PHP submission not working with either $_POST or $_REQUEST

I have been trying to get the PHP code to submit an email to a mysqlDB, but for some reason it is not working:
This is the form code in the HTML
<form class="header-signup" action="registration.php" method="post">
<input name="email" class="input-side" type="email" placeholder="Sign up now">
<input type="submit" value="Go" class="btn-side">
<p class="hs-disclaimer">No spam, ever. That's a pinky promise.</p>
</form>
For the PHP, I did the following (DB connection infos set to xxxxx):
<?php //start php tag
//include connect.php page for database connection
$hostname="xxxxxx";
$username="xxxxxx";
$password="xxxxxx";
$dbname="xxxxxx";
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
//Include('connect.php');
//if submit is not blanked i.e. it is clicked.
If(isset($_POST['submit'])!='')
{
If($_POST['email']=='')
{
Echo "please fill the empty field.";
}
Else
{
$sql="INSERT INTO MailingList (MAIL) VALUES('".$_POST['email']."')";
$res=mysql_query($sql);
If($res)
{
Echo "Record successfully inserted";
}
Else
{
Echo "There is some problem in inserting record";
}
}
}
?>
Do you know what might be the problem?
The php file is in the same folder than the webpage.
Thanks for your time
Regards
$_POST['submit']
does not exist, you have to specify the name for the submit button
<input type="submit" name="submit"........>
Please try this
You could also use this conditional for a POST request
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
And check the input with a var_dump($_POST); to see if the value exists in the array.
This is only if you're expecting one form. If you want multiple forms on the page you could make use of naming your submit button in the HTML code
<form class="header-signup" action="registration.php" method="post">
<input type="submit" name="action1" value="Go" class="btn-side">
</form>
You could also use this if you set an name on the submit button
if(isset($_POST['action1']))
{
var_dump("hit");
}

PHP form - on submit stay on same page

I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)

user invalid login

I am creating my own website just to get some experience. I've been working on it for 3 days and am at the point where I can sign up and sign in.
When signing in, if the combination of the username and password is not found in the database, my code displays an error message telling the user that either he didn't sign up yet or he is entering a wrong user email or password.
But, the message is displayed in a new page, instead of the sign in page.
I looked at some tutorials online, but didn't find a good explanation for it. Could someone please give me some advise?
I am using PHP for the database connection.
I just typed a very basic example:
<?php
//login.php
$msg = ''; //to store error messages
//check whether the user is submitting a form
if($_SERVER['REQUEST_METHOD'] == 'POST') //check if form being submitted via HTTP POST
{
//validate the POST variables submitted (ie. username and password)
//check the database for a match
if($matchfound == TRUE) //if found
{
//assign session variables and other user datas
//then redirect to the home page, since the user had successfully logged in
header('Location: index.php');
}
else
{
$msg = 'Error. No match found !'; //assign an error message
include('login_html.php'); //include the html code(ie. to display the login form and other html tags)
}
}
else //if user has not submitted the form, just display the html form
{
include('login_html.php');
}
//END of login.php
?>
login_html.php :
<html>
<body>
<?php if(!empty($msg)) echo $msg; ?> <!-- Display error message if any -->
<form action="login.php" method="post">
<input name = "username" type="text" />
<input name = "password" type="password" />
<input name = "submit" type="submit" value="Submit" />
</form>
</body>
</html>
This is not a complete code. But I just created it for you to understand how this can be done. :)
Good luck
Your opening form tag should look like this: <form action="" method="post">. The empty "action" attribute will cause the page to post back to itself. Just check the $_POST for username and password to determine whether to test for a match or just show the form.
And please be sure to hash your passwords and sanitize your inputs!
you can do it without going to a new page.
<?php session_start(); ?>
<?php
if(isset($_POST) && isset ($_POST["admin_login"])){
$user_data_row = null;
$sql="SELECT * FROM table_name WHERE <table_name.field name>='".mysql_real_escape_string($_POST['email'])."'
and <table_name.field name='".mysql_real_escape_string($_POST['password'])."'
;
$result=mysql_query($sql);
$user_data_row=mysql_fetch_assoc($result);
if(is_array($user_data_row)){
$_SESSION['user_id'] = $user_data_row['id'];
header("Location: <your page name>");
}else{
$_SESSION['message'] = "Valid email and password required";
}
}
?>
<?php if(isset($_SESSION['message'])){
echo "<li>{$message}</li>";
?>
<form action="" method="post" id="customForm">
<label>Email:</label>
<input type="text" id="email" name="email">
<label>Password:</label>
<input type="password" id="password" name="password">
<input type="submit" value="Login" id="send" name="admin_login">
</form>
may be its helps you....
Basically what you need to do, is post the form to the same page.
Once you have that, at the type just check for the $_POST: if($_SERVER['REQUEST_METHOD'] == 'POST')
If it is a post, check the username and password and either show an error or redirect to the signed in page. After this, display the login form.
So, if it's an error, they'll get the error and then the login form. If it's not posted, they'll get just the login form, and if it's a valid login, they'll get redirected to the proper page before the login form is shown.

Categories