I have a simple account creation script that is not working. I know that there are no connection errors because the login works fine. Also, I turned on error-reporting (made it -1) but it shows no errors
This is my code in snippets, thanks
HTML
<form method="post">
<input type="text" name="newUsername" placeholder="Username"/>
<input type="password" name="newPassword" placeholder="Password"/>
<input type="submit" name="signUp" value="Sign Up!"/>
</form>
Then PHP:
if($_POST['signUp']) {
$username = $_POST['newUsername'];
$pass = $_POST['newPassword'];
$signedUp = SignUp($Username,$pass);
echo $signUpCode[$signedUp]; // See the SignUp function in prefunc.php
} elseif($_POST['LogIn']) {
$username = $_POST['Username'];
$password = $_POST['Password'];
$loggedIn = LogIn($username,$password);
echo $logInCode[$loggedIn];
}
$signUpCode = Array(
"-3"=>"Logged in already - can't sign up!",
"-2"=>"Username already exists!",
"-1"=>"Failed to sign up - please try again!",
"1"=>"Signed up, and logged in successfully!"
);
function SignUp($Username,$Password) {
$Username = preg_replace("/[^a-zA-Z0-9]/","",$Username);
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(getCurrentId()){
return -3;
}
if(!mysql_num_rows($u)) {
mysql_query("INSERT INTO Users SET Username='$Username',Password=''$Password") or die(mysql_error());
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(mysql_num_rows($u)) {
LogIn($Username,$Password);
return 1;
} else {
return -1;
}
}
return -2;
}
Are you sure you re executing the insert query?
also the query sintax is wrong, try this: insert into user ( username,password) values ('admin','1234').
finally you must fix security issue, your code is affected by sql injection
Related
I have been working on a website on a localhost and have just tried to upload it to a free webserver so I can get some testers, for some reason my code is being reported as malware and is being blocked by my antivirus, this means I can't see anything when visiting it apart from the ERR_CONNECTION_RESET. Have you guys got any ideas as to why this code is being detected as malware?
LOGIN.php
<?php
include('classes/db.php');
if (db::maintenance()) {
die('This site is currently going under maintenance, please check back again shortly.');
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (db::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
if (password_verify($password, db::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])) {
echo "Logged in!";
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
$user_id = db::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
db::query('INSERT INTO login_tokens VALUES (NULL, :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$user_id));
setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie('SNID_', '1', time() + 60 + 60 * 24 * 3, '/', NULL, NULL, TRUE);
header('Location: index.php');
} else {
echo "Incorrect password";
}
} else {
echo "User not registered!";
}
}
?>
<h1>Login to your account</h1>
<form action="login.php" method="post">
<input type="text" name="username" value="" placeholder="Username"><p />
<input type="password" name="password" value="" placeholder="Password"><p />
<input type="submit" name="submit" placeholder="Login"><p />
</form>
DB.php
(I have changed the connection to false data, and changed it to the correct data when uploading it to the host.)
<?php
class db {
private static function connect () {
$conn = new PDO('mysql:host=localhost;dbname=users;,charset=utf8', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
public static function query ($sql, $params = array()) {
$statement = self::connect()->prepare($sql);
$statement->execute($params);
if (explode(' ', $sql)[0] == 'SELECT') {
$result = $statement->fetchAll();
return $result;
}
}
public static function notify ($userid) {
$notifications = db::query('SELECT forum_members.forum_id, notifications.user_id, notifications.post_id, notifications.forum_id, notifications.post_body, notifications.creation, notifications.type FROM forum_members, notifications WHERE (notifications.forum_id=forum_members.forum_id OR notifications.forum_id=0) AND notifications.user_id=forum_members.user_id ORDER BY notifications.post_id DESC');
return $notifications;
}
public static function maintenance () {
return false;
}
}
?>
Which type of address do you use to enter the website? PHP source doesn't display to browsers, so PHP isn't the problem.
If you enter in with a hostname (Ex. .....2cc.brad....net) Then it'll automatically get detected as a "malware" for beginner safety, if ur accessing it from localhost/127.0.0.1 it should be fine, but if ur accessing it from a host that's marked as malware, than yep.
This question already has an answer here:
Get results from from MySQL using PDO
(1 answer)
Closed 7 years ago.
I'm totally new to PDO so I apologize if I made a simple mistake here. Also if this has been answered before. I searched but couldn't find. My problem is that when I print the sessions it prints out 'Array ( [user_id] => 1 )' but the username and password I entered is for user_id 2. I have tried this with a differant username and password and it still gives an id value of 1. So I echoed out $user_id before the session is created and it is 1. But I can't figure out where it is getting this 1 from? Because there is no id of 1 in the database. Can anyone shed some light on this?
Here is the code from my login file:
<?php
require 'core.inc.php';
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
$stmt = $db->prepare("SELECT password FROM users WHERE username = ?");
$stmt->bindParam(1, $username);
$hash = $stmt->execute();
$password_verified = password_verify($password, $hash);
if ($password_verified = true) {
$stmt_id = $db->prepare("SELECT id FROM users WHERE username = ?");
$stmt_id->bindParam(1, $username);
$user_id = $stmt_id->execute();
echo $user_id;
$id_num_rows = $stmt_id->rowCount();
if ($id_num_rows == 0) {
echo 'You have entered a wrong password';
}else if($id_num_rows == 1){
$_SESSION['user_id'] = $user_id;
print_r($_SESSION);
}
} else {
echo("Please enter a username and password.");
}
}
}
?>
<!DOCTYPE html>
<header>
</header>
<body>
<form action ="<?php echo $current_file;?>" method="post">
<div class='field'>
<label for="username">Username: </label><input type='text'
name='username'/><br>
</div>
<div class='field'>
<label for ="password">Password: </label><input type='password'
name='password'/>
</div>
<div class='field'>
<label for='remember'>
<input type='checkbox' name="remember" id="remember"/> Remember me
</label>
</div>
<input type='submit' value='Log in'/>
</form>
</body>
</html>
<And here is the code from core.inc.php
<?php
session_start();
require 'connect.inc.php';
ob_start();
$current_file = $_SERVER['SCRIPT_NAME'];
#$http_referer = $_SERVER['HTTP_REFERER'];
function loggedin(){
if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
return true;
}else{
return false;
}
}
?>
<Core.inc.php uses connect.inc.php which is added below:
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=goal;charset=utf8','root','');
var_dump($db);
echo 'connected';
}
catch(Exception $e){
echo 'Error 1 has occured';
}
?>
$stmt_id->execute();
Returns true on succes, or false on failure, you need to use the result of the query (and not the status of the execution):
$stmt_id->fetchAll()
Also you have an error here, you need to use comparison and not assignment:
if ($password_verified = true)
The line
if ($password_verified = true) {
is very incorrect because you're basically just assigning true to $password_verified. You should just be doing a if($password_verified) though, I am not sure if it will solve your problem.
You are also not parsing the results as you should be using fetchAll() and then going through the results to see if the user exists.
$stmt_id->execute() will return bool, in your case it's true and later converted to int.
See http://php.net/manual/en/pdostatement.execute.php
You need to fetch the data in order to retrieve the user_id.
the registration form is connected to the database via db.php but I am having trouble in submitting the login details.
<html>
<head>
<?php
include('db.php');
$username = #$_POST['username'];
$password = #$_POST['password'];
$submit = #$_POST['submit'];
the main problem is after the submit button is clicked by an existing user it should give the message but there's problem in the if statement, because on the wamp server its showing only the else message i.e. Error.
if ($submit)
{
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
if (mysql_num_rows($result)) {
$check_rows = mysql_fetch_array($result);
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
echo "<center>";
echo "You are now Logged In. ";
echo "</center>";
}
else {
echo "<center>";
echo "No User found. ";
echo "</center>";
}
}
else echo "Error";
?>
</head>
<body>
<form method="post">
Username : <input name="username" placeholder="Enter Username" type="text"><br></br>
Password : <input name="password" placeholder="Enter Password" type="password"><br>
<input type="submit" value="Submit">
</body>
</html>
You want get $_POST with name submit, but do not send it to the form
Try change
<input type="submit" value="Submit">
to
<input type="submit" name="submit" value="Submit">
Firstly this is old style of php/mysql. So look at PDO on php.net seeing as you are setting out on new project it really wont be hard to make the change now rather than later.
Now onto your issue. if you intend on carrying on with your old method try this.
$sql = "SELECT * FROM user WHERE username=' . $username . ' AND password=' . $password . '";
// check the query with the die & mysql_error functions
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_num_rows($query);
// checking here equal to 1 In a live case, for testing you could use >= but not much point.
if ($result == 1) {
// Checking needs to be Assoc Now you can use the field names,
// otherwise $check_rows[0], $check_rows[1] etc etc
$check_rows = mysql_fetch_assoc($query); // oops we all make mistakes, query not result, sorry.
// This is bad but for example il let this by,
// please dont access user supplied data without
// validating/sanitising it.
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
} else {
// do not logged in here
}
The same in PDO
$sql=" Your query here ";
$pdo->query($sql);
$pdo->execute();
$result = $pdo->fetch();
if ($result = 1) {
// do login stuff
} else {
// no login
}
Remember though that you need to set up PDO and it may not be available on your server by default (older php/mysql versions) but your host should be happy enough to set them up.
Coding, as I've been learning, is about little details, and I'm missing something because I have the following code:
public function login() {
if ($_POST) {
$logdb = new PDO('mysql:host=localhost;dbname=kiko', 'kiko', 'pass');
$logdb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $logdb->prepare("SELECT * FROM usreg WHERE email=:email AND password=:pass");
$stmt->bindParam(":email", $_POST['email']);
$stmt->bindParam(":pass", $_POST['password']);
$stmt->execute();
$loged = $stmt->fetch();
$atributes = $stmt->fetch(PDO::FETCH_ASSOC);
if ($loged) {
session_start();
$_SESSION["loggedIn"] = true;
$_SESSION["id"] = $atributes->id;
$_SESSION["email"] = $_POST['email'];
$_SESSION["group"] = $atributes->group;
$_SESSION["firstname"] = $atributes->firstname;
$_SESSION["lastname"] = $atributes->lastname;
$_SESSION["phone"] = $atributes->phone;
$_SESSION["mobile"] = $atributes->mobile;
$_SESSION["adress"] = $atributes->adress;
$_SESSION["city"] = $atributes->city;
$_SESSION["country"] = $atributes->country;
} else {
echo 'wrong login try again';
}
} else {
echo '<form name="login" action="" method="POST">
Email: <br />
<input type="text" name="email"/><br />
Password: <br />
<input type="password" name="password"/><br />
<button type="submit">Login</button>
Register</form>';
}
}
and everything works well except the part where I'm registering globals. What I'm trying to do is set the global session the details from the fetch array atributes, I tried with:
$atributes = $stmt->fetch(PDO::FETCH_OBJ);
but the result is the same, and I changed the email from array to POST and it works because when I do:
echo $_SESSION['email'];
It works, but the fetch is not passing the details to the other session globals. What should I put in there to sucess what I'm trying to do can you guys help me? Do I need another kind of prepared statement? Is it missing results because I'm making the WHERE clause?
Why are you fetching twice? Once for $loged and another for $atributes
I assume the username/password combination will be unique, so you'll only get one result from your SQL query. That means when you call fetch again, you'll get nothing.
Perhaps you want:
//$loged = $stmt->fetch();
$atributes = $stmt->fetch(PDO::FETCH_OBJ);
if ($atributes) {
session_start();
$_SESSION["loggedIn"] = true;
$_SESSION["id"] = $atributes->id;
Also, make sure you use password_verify when dealing with passwords!
I am just starting to learn php and sql so please go easy on me, i know i'm going to be wrong in certain places. I am trying to allow a user to login and be able to change their password. I have made an attempt of a script which i believe should work, but i guess i'm doing something wrong as it will just link to the php function page and not change the password at all. Here's my script:
HTML form:
<form method="POST" action="includes/changepassword.php">
<p><input type="password" name="oldpasswd" id="oldpasswd" maxlength="30" placeholder="Old Password"></p>
<p><input type="password" name="newpsswd1" id="newpsswd1" maxlength="30" placeholder="New Password"></p>
<p><input type="password" name="newpsswd2" id="newpsswd2"maxlength="30" placeholder="Confirm Password"></p>
<input type="submit" name="submit" id="submit" value="change password">
changepassword.php file:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
function changepassword ($oldpasswd, $newpasswd1, $newpasswd2) {
/*
* RETURNS
* 0 - if password changed
* 1 - if new passwords are not equal
* 2 - if user authentification problems
*/
$oldpasswd = ($_POST['oldpasswd']);
$newpasswd1 = ($_POST['newpasswd1']);
$newpasswd1 = ($_POST['newpasswd2']);
if ($newpasswd1 != $newpasswd2) {
return 1;
}
//check user logged in changes OWN passwd
$sql = "SELECT password FROM ptb_users WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql)or die('User not found: ' . mysql_error());
if (md5($oldpasswd)==$result) {
//Encrypt $emailpassword in MD5 format for the database
$md5_np=md5($newpasswd1);
// Make a safe query
$query = sprintf("UPDATE `ptb_users` SET `password` = '%s'
WHERE `id` = ".$_SESSION['user_id'],
mysql_real_escape_string($md5_np));
mysql_query($query)or die('Could not update password: ' . mysql_error());
return 0;
} else {
return 2;
}
}
?>
What have I done wrong?
it will just link to the php function page and not change the password at all
You told the HTML form to do exactly that: <form method="POST" action="includes/changepassword.php">. But on the other hand, you never call your function.
You need to call the function in order to process the change password. Add this to the bottom of your file just before the ?>
echo changepassword($_POST['oldpasswd'], $_POST['newpasswd1'], $_POST['newpasswd2']);
You can also remove the $_POST assignments within the function as you're passing those in as parameters.
As poke mentioned you will need to call the function in order to update the password.
I think I found another problem in the following code:
//check user logged in changes OWN passwd
$sql = "SELECT password FROM ptb_users WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql)or die('User not found: ' . mysql_error());
if (md5($oldpasswd)==$result) {
You are directly using the result of the mysql_query() function which actually returns as a resource and not a value.
You will need to update your code to this:
//check user logged in changes OWN passwd
$sql = "SELECT password FROM ptb_users WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql)or die('User not found: ' . mysql_error());
$row=mysql_fetch_assoc($result);
if (md5($oldpasswd)==$row['password']) {
See this function- mysql_fetch_assoc().
Look for a tutorial about form handling, after a bit of searching if stumbled over this form tutorial, it looks easy to understand. You will see, that most forms call themself.
formchangepassword.html
<form action="formchangepassword.html" method="post">
At the begin of the form there is usually some code, that decides if the form was called with post (after pressing a button), or if it was called with get. In this code you can call the function you wrote in your CHANGEPASSWORD.PHP file. This file is just a library, it contains functions, you can call this function but they do not run themselfes, they have to be called.
<?php
require_once("CHANGEPASSWORD.PHP");
if(count($_POST) > 0)
{
// button was clicked, do what is necessary
changepassword(...);
...
}
?>
<form action="formchangepassword.html" method="post">
...
</form>
The name of your form fields doesn't match what's listed in changepassword.php . You are missing an "a" in what should be "newpasswd1" and "newpasswd2" -- name=newpsswd1 should be newpasswd1 and so on.
Also you have "newpasswd1" listed twice
$oldpasswd = ($_POST['oldpasswd']);
$newpasswd**1** = ($_POST['newpasswd1']);
$newpasswd**1** = ($_POST['newpasswd2']);
...I think you probably meant this...
$oldpasswd = ($_POST['oldpasswd']);
$newpasswd**1** = ($_POST['newpasswd1']);
$newpasswd**2** = ($_POST['newpasswd2']);
I also incorporated the changes suggested by Pastor Bones and Abhishek Bhatia and it works fine now. (Also I a close form tag to the HTML)
Here's what the whole thing should look (as modified for my site):
HTML FORM
<form method="POST" action="changepassword.php">
<p><input type="password" name="oldpasswd" id="oldpasswd" maxlength="30" placeholder="Old Password"></p>
<p><input type="password" name="newpasswd1" id="newpasswd1" maxlength="30" placeholder="New Password"></p>
<p><input type="password" name="newpasswd2" id="newpasswd2"maxlength="30" placeholder="Confirm Password"></p>
<input type="submit" name="submit" id="submit" value="change password">
</form>
changepassword.php
function changepassword ($oldpasswd, $newpasswd1, $newpasswd2)
{
$oldpasswd = ($_POST['oldpasswd']);
$newpasswd1 = ($_POST['newpasswd1']);
$newpasswd2 = ($_POST['newpasswd2']);
if ($newpasswd1 != $newpasswd2)
{
return 1;
}
$sql = "SELECT Password FROM users WHERE UserID = ".$_SESSION['UserId'];
$result = mysql_query($sql)or die('User not found: ' . mysql_error());
$row=mysql_fetch_assoc($result);
if (md5($oldpasswd)==$row['Password'])
{
$md5_np=md5($newpasswd1);
$query = sprintf("UPDATE `users` SET `Password` = '%s' WHERE `UserID` ".$_SESSION['UserId'],mysql_real_escape_string($md5_np));
mysql_query($query)or die('Could not update password: ' . mysql_error());
return 0;
}
else
{
return 2;
}
}
echo changepassword($_POST['oldpasswd'], $_POST['newpasswd1'], $_POST['newpasswd2']);