I'm trying to update the user password in this code. I know it is not reliable since it does not has SQL injection prevention feature, I'm just trying to learn here.
anyway, using $_request variable in my code does not work with the database query, it works when I want to display the variable with echo.
PHP code:
$newPassword=$_POST['newPassword'];
$confirmPassword=$_POST['confirmPassword'];
$userID1=$_REQUEST['ID'];
$code=$_GET['$code'];
echo "<h1>Hello " . $userID1 . "</h1>";
if (isset($_GET['submit']))
{
if($newPassword == $confirmPassword ){
mysql_query("UPDATE facultymember SET password='$newPassword' WHERE ID='$userID1'");
$message = "Your password has been updated.";
}
else
{
$message = "New password does not equal Confirm password";
}
}
HTML form:
<form name="frmChange" action='newpass.php' method="GET" onSubmit="return validatePassword()">
<div style="color:red;" "class="message"><?php if(isset($message)) { echo $message; } ?></div>
Enter a new password
<input type="text" name="newPassword">
Re-enter the new password
<input type="text" name="confirmPassword">
<input name="submit" type="submit" value="Save Changes">
</form>
wrong object to get value , when you are submitting GET request method="GET"
$newPassword=$_POST['newPassword'];
$confirmPassword=$_POST['confirmPassword'];
or
$newPassword=$_GET['newPassword'];
$confirmPassword=$_GET['confirmPassword'];
and no ID param also attached
Related
I'm a novice at mysql having trouble with inserting fields. I have created a login form and a homepage form for users to enter personal details. The login form submitted to mysql database fine, but the personal details form refused to submit; only when I specified the same fields as the first form did the form submit. Obviously, I would like to add new data in the second form, and I would appreciate tips on organizing my database, which consists of a single table profile.It stores info on every user including fields: id,username,password,avatar,location,goal, etc.
Appreciate your help & patience. I will combine the info from the two forms into a user record eventually. Right now, though, I would like to know why no new entry is created or error message displayed even though my error display is turned on.
EDIT:: sorry for not including whole code
loginform.php (works fine)
<?php
require("connect.php");
session_start();
$query = "SELECT * FROM `profile`";
if ($query_run=mysqli_query($cnn,$query))
{
echo "
<h1>Sign up for Runners World</h1>
<form action='' method='post'>
Username: <input type='text' name='username'><br>
Email: <input type='text' name='email'><br>
Password: <input type='text' name='pw'><br>
<input type='submit' name='submit' value='submit'>
</form>
";
}
else {
die("<br>could not connect to table");
}
?>
<?php
if (isset($_POST['submit']))//if you submitted the form
{
$username = $_POST['username'];
$password = $_POST['pw'];
$email = $_POST['email'];
if ($username and $password and $email)
{
$addLogin = "INSERT INTO profile (username,email,password) VALUES ('$username','$email','$password')";
$success = $cnn->query($addLogin);
if ($success)
{
$_SESSION['name']="$username";
echo("<script>location.href = 'homePage.php';</script>");
}
else
{
die("login data failed to reach database");
}
}
else {echo "please fill out all the fields";}
}
else {
$submit=null;
echo 'no form submitted';
}
?>
addDetails.php (not submitting)
<?php
session_start();
error_reporting(E_ALL);
ini_set("display_errors",1);
require("connect.php");
require("login.php");
echo "<h1>Welcome ".$_SESSION['name']."</h1>";
echo "<form action='' method='post'>
Avatar: <input type='text' name='avatar'><br>
Location: <input type='text' name='location'><br>
Descripiton: <input type='text' name='about'><br>
Daily Goal: <input type='text' name='goal'><br>
<input type='submit' value='submit' name='submit'>
</form>
";
$avatar = $_POST['avatar'];
$location = $_POST['location'];
$goal = $_POST['goal'];
$about = $_POST['about'];
if (isset($_POST['submit']))
{
$sql = "INSERT INTO profile (avatar,location,goal) VALUES ('$avatar','$location','$goal')";
if ($cnn->query($sql)===TRUE)
{echo "you have inserted profile fields";}
else
{echo "sqlQuery failed to insert fields";}
}
?>
If you want to add data to a row that already exists, look up the UPDATE command in SQL
You should change the Sql statement in 'addDetails.php' to:
UPDATE profile
SET avatar={$avatar}, location={$location}, goal={$goal}
WHERE id={$id}
By the way you should never ever use this statement in your production, it is not safe, you should keep in mind to prevent Sql injection.
I used this code to create a user registration page in my website. I firstly connected to my database and then did the below codes ----->
<form action="index.php" method="post">
<p id="usr1">Name : </p><input id="input1" placeholder="Username" type="text" name="username" required> </br>
</br>
<p id="usr2">Password : </p><input id="input2" placeholder="Password" type="text" name="pwd" required> </br>
<p id="usr3">Password : </p><input id="input3" placeholder="Re-Type your password" type="text" name="cpwd" required> </br>
</br>
<input id="sub" name="subbox" type="submit">
</form>
<?php
if (isset($_POST['submit_button'])) {
$username= $_POST['username'];
$password=$_POST['pwd'];
$conpwd=$_POST['cpwd'];
}
if ($password == $conpwd) {
$query = "SELECT * FROM login WHERE name='$username' ";
$query_run = mysqli_query($con,$query);
if (mysqli_num_rows($query_run) > 1) {
echo '<script type="text/javascript">alert("This Username Already exists. Please try another username!")</script>';
// the above code will check if the username is already taken or not.
}else {
$query = "insert into login values('$username' , '$password')";
$query_run = mysqli_query($con,$query);
if ($query_run) {
echo '<script type="text/javascript">alert("Registration Successful!")</script>Click Here To Continue';
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header( "Location: homepage.php");
}else {
echo '<script type="text/javascript">alert("Server Error. Please try again after a few minutes!")</script>';
}
}
}else {
echo "Please check and re-type both passwords";
}
?>
But it always return some errors.This is what I see when i try to run the code
Is anything wrong with this code?
To answer your initial question, yes there is something wrong. Your code is vulnerable to SQL injection. You should have a look at: How can I prevent SQL injection in PHP? And password is stored plain in your database, which means no respect for your user. There are some other problems with code style but it's just bonus.
Anyway, the thing that cause you the "alert" problem is that submit_button button does not exists. There is no button with that name. Your if condition is always false. So you have to replace:
if (isset($_POST['submit_button'])) {
With
if (isset($_POST['subbox'])) {
And maybe add a value to your input (not sure it's required, I did not tested):
<input id="sub" name="subbox" type="submit" value="1">
Thanks to #Fred-ii-
I have two pages. Index.php and my Login.php.
I am using dropdown menu form for logging in - when the user presses 'Sign in', the data gets sent to the Login.php. It's all okay when the password/username was correct (they get sent to the dashboard).
But how could I display an error right there, in the form? Currently when the username/password is wrong it sends you to a new blank page. I want the error to appear right there on the form.
My form:
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" class="form-control" name="user_name" placeholder="Username" required>
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" class="form-control" name="user_password" placeholder="Password" required>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-block">Sign in</button>
</div>
My login.php:
error_reporting(E_ALL);
session_start();
$con = mysqli_connect("localhost", "root", "", "battlesql");
if (!$con) {
echo "<div>";
echo "Failed to connect to MySQL: ".mysqli_connect_error();
echo "</div>";
} else {
if (isset($_POST['user_name']) && isset($_POST['user_password'])) {
$username = stripslashes($username);
$username = mysqli_real_escape_string($con, $_POST['user_name']);
$pass = stripslashes($pass);
$pass = mysqli_real_escape_string($con, $_POST['user_password']);
$pass_hashed = hash('whirlpool', $pass);
$select_user = "SELECT * from accounts where name='$username' AND password='$pass_hashed' LIMIT 1";
$query = mysqli_query($con, $select_user);
$row = mysqli_num_rows($query);
if (!$row) {
echo "<div>";
echo "No existing user or wrong password.";
echo "</div>";
} else {
echo "<div>";
echo "You have been logged in.";
echo "</div>";
}
} else {
echo "MySQL error!";
}
}
In your login.php, instead of echoing "No existing user or wrong password", use this:
if(!$row)
{
die(header("location:index.php?loginFailed=true&reason=password"));
}
And in your index.php, you can generate the message as:
<button type="submit" class="btn btn-success btn-block">Sign in</button>
<?php $reasons = array("password" => "Wrong Username or Password", "blank" => "You have left one or more fields blank."); if ($_GET["loginFailed"]) echo $reasons[$_GET["reason"]]; ?>
There are dozens of ways to do this, but I'll provide you with one.
Looking at your PHP code, I'm not exactly sure where your redirect to the "dashboard" is, but say you have some code like this:
<?php
//Fetch stuff from the database
if($fetchedUsername == $username and $fetchedPassword == $password)
{
header("Location:/dashboard");
return;
}
?>
Then, to send them back to the login form, you would just put something in the else statement:
<?php
if(........)
{
//Redirect to dashboard
}
else
{
header("Location:/login");
return;
}
?>
This will send them back to the form. Now you want to show an error, so one way to do this is to set a GET variable, so in the else statement, change the header to:
header("Location:/login/?error=1");
This will let you check for the error code on the login page.
So onto your login page code. You can use isset() and inline-PHP echoes to print out an error directly into the form. Something like this:
<form>
//Form stuff
<?php if(isset($_GET["error"])):?>
<div class="error">Invalid Username or Password</div>
<?php endif; ?>
</form>
That way you can style div.error without worrying about an empty wrapper showing up when $_GET["error"] is not set.
You can also make the code to echo a bit shorter using inline PHP:
<?=(isset($_GET["error"])) ? "Invalid Username or Password" : ""?>
You can achieve what you want using ajax(asynchronous JavaScript and XML). Send login data to login.php from index.php using an ajax call. Read the reply the ajax call returns and show error/success message.
You can use the jquery $.ajax({}); function to implement this model. If you are having trouble in implementing the $.ajax() function then you can read all about it here.
Also, if you haven't already done it, I suggest you to encrypt the password before sending it login.php.
I have made simple php files by using which I can validate username and PASSWORD and then only user can log in. I want users to update account only if they log in to account. Without validating ID and password, they can't update their Name and Surname and all... It's very simple program. Here is the table Structure.
It is just a Demo data. I want users to update their accounts only after logging in. Here is the file by which they can see their information by logging in.
<html>
<head>
<title>
Login
</title>
</head>
<body>
<?php
if(isset($_POST["uname"]) && isset($_POST["pass"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
mysql_connect("localhost","adarsh","Yeah!");
mysql_select_db("aadarsh");
$select = mysql_query("select * from users where username='$uname' AND pass='$pass'");
$data = mysql_fetch_array($select);
if($uname==$data['username'] && $pass==$data['pass'])
{
echo "<center>";
echo "Name: ".$data['username']."<br>";
echo "Last namme: ".$data['lastname']."<br>";
echo "<img src=".$data['image']."><br>";
echo "</center>";
}
else
{
echo "<script>alert('Nope!!!');</script>";
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="uname">
<input type="pass" name="pass">
<input type="submit" name="submit" value="Login!">
</form>
</html>
The code is working fine and They can see their data by entering username and password. If they will enter wrong Username and password, they will just see alert box.
I just want users to update their data after logging in. Without login, they can't update their data.
But i have no idea how to do it. Once I tried by validating username and password and then redirecting to new page where they can update their account using header location but that doesn't work. I didn't get any variables on the other page.
Help me solving this....
Try this
<html>
<head>
<title>
Login
</title>
</head>
<body>
<?php
session_start();
if(isset($_POST["submit"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
if(empty($uname) && empty($pass))
{
echo "<script>alert('Empty');</script>";
}
else
{
mysql_connect("localhost","adarsh","Yeah!","aadarsh");
$select = mysql_query("select * from users where username='$uname' AND pass='$pass'");
$data = mysql_fetch_array($select);
$count = count($data);
if(empty($count) || $count > 1)
{
echo "<script>alert('Invalid Login');</script>";
}
else
{
$image = $data['image'];
$lname = $data['lastname'];
$username = $data['username'];
$_SESSION["lastname"] = $lname;
$_SESSION["username"] = $username;
echo "Name: ".'$username'."<br>";
echo "Last namme:".'$lname'."<br>";
echo "<img src='$image'><br>";
if(isset($_SESSION))
{
redirect('new_page.php');
}
else
{
echo "<script>alert('Something Went Wrong');</script>";
}
}
}
}
?>
<form method="post" action="#">
<input type="text" name="uname">
<input type="pass" name="pass">
<input type="submit" name="submit" value="Login!">
</form>
</body>
</html>
and in new_page.php
<?php
session_start();
if(isset($_SESSION["username"]))
{
//show update form
}
else
{
//redirect to login page
redirect('login.php');
}
Includes
Using Session
Optimize Query
Validate all fields
and take a look at this too
How can I prevent SQL-injection in PHP?
MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
So, after logging in, instead of simply displaying the users details, display a form allowing the user to update their details, something like this (incomplete code just to give you an outline):
if($uname==$data['username'] && $pass==$data['pass'])
{
echo '<form method="" action ="">';
echo '<input value="'.$data['username'].'" />';
echo '<input value="'.$data['lastname'].'" />';
echo '<input type="submit" />';
echo "</form>";
}
If you want to pass variables from one page to another, once the user is logged in, you should use Session variables.
Thanks to all to answer on my question. Finally with the help of you guys, I solved every errors and Program is working fine!
I did this with the help of 2 files... Here are they,
updatedata.php (This file contains only html stuff... .html will also work)
<html>
<head>
<title>
Login
</title>
</head>
<body>
<form method="post" action="updateaccount.php">
Username : <input type="text" name="uname"><br>
Password :<input type="password" name="pass"><br>
New Information:<br><br>
New Name : <input type="text" name="newname"></input>
<input type="submit" name="submit" value="Update!">
</form>
</html>
updateaccount.php (hehe, Don't get confused in file names...)
<?php
$con=mysql_connect("localhost","adarsh","Password");
mysql_select_db("aadarsh",$con);
if(isset($_POST["uname"]) && isset($_POST["pass"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
}
$sql="select * from users where username='$uname' AND pass='$pass'";
$select = mysql_query($sql);
$data = mysql_fetch_array($select);
$username=$_POST["newname"];
if(isset($_POST['submit']))
{
if($uname==$data['username'] && $pass==$data['pass'])
{
$user_id= $data['id'];
if(isset($_POST['newname']))
{
$update = mysql_query("UPDATE users SET username = '$username' WHERE id = $user_id");
if($update)
{
echo "<script>alert('updated!');</script>";
header("location:http://www.example.com");
}
else
{
echo mysql_error();
}
}
}
else
{
echo "<script>alert('Nope!!!');</script>";
}
}
?>
Thanks to all of you again.... :)
Some considerations about your code:
mysql_connect is deprecated, you should use mysqli_connect.
http://php.net/manual/en/book.mysqli.php
You can use empty() instead of isset(). empty() will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable. With !empty you can:
if (!empty($_POST["uname"]) && !empty($_POST["pass"])){
$uname = .........
}
Can't use echo and header("location:http....") in the same loop. If you send to another page, the message will not be displayed.
After a header("location:http....") you must exit(); otherwise, the code will follow the normal flow.
You check if ($update). If you click the submit button, $update always be true, so this check is not necessary.
Hope that helps.
This is my script:
session_start();
include "../inc/conn.php";
if ($_GET['login']=="yes") {
echo 'test2';
$username=$_POST('username');
$password=$_POST('password');
echo $username.' '.$password;
$userq=mysql_query("SELECT * FROM members WHERE username='$username' AND password='$password'") or die(mysql_error());
if (mysql_num_rows($userq)=="1") { $_SESSION['chkuser']="confirmed"; $_SESSION['username']=$user; }
else { echo 'Потребителското име и/или паролата са грешни. Моля опитайте отново.'; }
}
echo $user.' '.$pass;
if ($_SESSION['chkuser'] <> "confirmed") {
echo '<div align="center"><strong>Моля въведете име и парола</strong>:<br/><br/><br/>';
?>
<form name="form1" method="post" action="?login=yes">
Потребител: <input type="text" name="username" />
Парола: <input type="password" name="password" /><br/><br/>
<p><input type="submit" name="Submit" value="Вход" /></p>
</div>
</form>
<?
exit();
}
Test 2 is echoed, but username and password are not sent via POST - scripts breaks after $_POST is used.. Do you guys see where my error is ?
Use [], not () to get data from $_POST array:
$username=$_POST['username'];
$password=$_POST['password'];
Also, I might mention that you should escape user input before using it in mysql query:
$username=mysql_escape_string($_POST['username']);
$password=mysql_escape_string($_POST['password']);
If you don't do this, anyone can insert something like this:
username=admin
password=blabbla' OR '1'='1
and will login as admin without knowing the password :)
Shouldn't this:
$username=$_POST('username');
$password=$_POST('password');
be
$username=$_POST['username'];
$password=$_POST['password'];
?