Hi i am trying to create a very simple log in function using PHP however, after going through the codes, my form seem to be able to perform the function right only when i enter the right user name and password however, if i dont, it doesnt perform its duties here are my codes that i have simplified :
login.php
<form name="userlogin" action="phpprocess/loginprocess.php" method="POST">
<p>Username : <input type="text" id="username" name="username"></p>
<p>Password : <input type="password" id="password" name="password"></p>
<p><input type="submit" id="loginbtn" value="login" ></p>
</form>
loginproccess.php
include "mysqli.connect.php";
$username = $mysqli->real_escape_string($_REQUEST["username"]);
$password = $mysqli->real_escape_string($_REQUEST["password"]);
echo "$username";
echo "$password";
$sql = "select * from users.userlogin where username ='".$username."' and
password = '".$password."'";
$result = $mysqli->query($sql);
if($result == null){
echo"null";
}
if($mysqli -> errno){
error_log($mysqli -> error);
echo $mysqli -> error;
echo " hello";
exit();
}else{
while( list($index, $user1, $pass1) = $result -> fetch_array()){
if($user1 != null && $pass1 != null){
echo "$index $user1, $pass1";
}
}
}
$mysqli->close();
mysqli.connect.php
$host="localhost";
$user="root";
$password="";
$database="users";
$mysqli = new mysqli($host, $user, $password, $database);
if ($mysqli->errno) {
echo "Unable to connect to the database: <br />".$mysqli->error;
exit();
}
what happens is if i enter the wrong user name and password i need the webpage to echo hello , if i enter it right i need it to echo the right user and pass but when enter wrongly, $result does not seem to be null as null and hello is not being printed out. My error log does not display anything. Hope to hear your advice! Thank you in advance !
You print hello when the query gets an error, but it's not an error if the WHERE conditions don't match any rows. It just returns an empty result set. You should use:
if ($result->num_rows == 0) {
echo "hello";
exit();
}
Also, $result->fetch_array() returns an array with both numbered and named indexes. If your table has 3 columns, this will return an array with 6 elements, but you're only assigning to 3 variables.
Use $result->fetch_row() to get an array with just the numbered elements. Also, you shouldn't use SELECT * if you're relying on the order of elements like this, since that depends on the order that the columns were assigned in the CREATE TABLE statement, and this might change if you update your schema. You should list the specific columns you need in the SELECT list.
Related
Hello i want to change my password which is coming from my database, the very first thing i want to verify the users old password, but my $query is not equal to $opword, what might be the reason ?
I am trying to get the result from past 8 hours but I dont know where I went wrong please do help me thanks in advance.
<?php
session_start();
require_once('../includes/config.php');
if(isset($_POST['submit'])) {
require_once('../includes/config.php');
$opword = $_POST['opword'];
$npword = $_POST['npword'];
$cpword = $_POST['cpword'];
$string = "SELECT password FROM admin WHERE username = '$_SESSION[uname]'";
$query = mysqli_query($dbc,$string);
if($opword == $query) {
echo "yup";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
require_once('includes/menu.php');
?>
<form action="changepassword.php" method="post">
<p><label>Old Password:</label><input type="password" name="opword"></p>
<p><label>New Password:</label><input type="password" name="npword"></p>
<p><label>Confirm Changed Password:</label><input type="password" name="cpword"></p>
<input type="submit" value="Change Password" name="submit">
</form>
</body>
</html>
Because you are try to compare password with result object. You need to fetch password field form your data result
if($opword == $query->password) {// fatch password form result data
Note:- Don't store plain password into database
Read http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/faq.passwords.php
Don't forget to use prepared statements and hash your passwords before store them in database (password_hash).
$session_username = $_SESSION['uname'];
//Take only one username
if ($stmt = $dbc->prepare("SELECT password FROM admin WHERE username = ? LIMIT 1")) {
$stmt->bind_param("s", $session_username);
$stmt->execute();
$stmt->store_result();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row['password'] == $opword) {
echo 'yup';
}
}
After the following statement:
$query = mysqli_query($dbc,$string);
Use this before comparing compare:
$row = mysqli_fetch_array($query);
if($opword == $row[0]) {
echo "yup";
}
By using xdebug or var_dump(), you would find that $query is a PDOStatement, and object which will never equal a word.
You need a function get the data. Here is the documentation for mysqli queries.
Basically
$query = mysqli_query($dbc,$string);
mysqli_query returns a resource not value. So you have to fetch values from it
mysqli_fetch_assoc or mysqli_fetch_array
any of above function can be used. Both function returns array. Then you can use array value to match with other value. Hope it will help you.
This question already has answers here:
How to check username and password matches the database values
(3 answers)
Closed 11 months ago.
I'm trying to check if a users entered username and password matches an entry from the database using PDO, but for some reason cannot seem to get it working.
The database table is called user_info and the rows from which i'm trying to grab the username and password from are username and pass respectively. I'm not entirely sure how to check if the users input information matches a database entry, then make a decision on where to send them based on if it returns true or false.
Also, i've obviously got the prerequisites such as including a file that connects to the database, which i know whose information is correct.
I've had a stab in the dark on the if ($username) etc, but clearly it's incorrect.
HTML
<form method="post">
<label for="username2">Username</label>
<input type="text" name="username">
<label for="password">Password</label>
<input type="text" name="password">
<input type="submit" value="Login" name="login">
</form>
PHP
$username = $_POST['username'];
$password = $_POST['password'];
try {
$result = $db->prepare("SELECT * FROM user_info WHERE username = :user AND pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
if ($username == "test" && $password == "test") {
$_SESSION['username'] = $username;
redirect('/add-property.php');
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect";
}
}
What you can do is look up the user in the database and then return row from the query. After you compare the password that was given by the user to authenticate and the one that the query returned then return them to where they need to go.
To find your bug, add this code instead of the catch in your code:
catch (PDOException $e) {
echo "Could not retrieve data from database ".$e->getMessage;
exit();
}
You can also get your query sting to make sure it is correct like this:
echo $db->queryString;
It seems that ($username == $rows && $password == $rows) is all i needed to change in the code to correctly authenticate the username and password.
So the vote page is at Click here
the Username should go into the text box, and after you vote on both servers, it should send the Username to the database.
<form name="vote" class="short style" method="post" target="_blank">
<input name="username" type="text" size="30" maxlength="30" placeholder="Username"><button id="nextbutton" type="button" onClick="next();">Next</button>
<div style="display: none;" id="button" class="button"><button type="submit" onClick="changeAction('http://www.rune-server.org/toplist.php?do=vote&sid=8289&name=');")>Rune-Server</button><button type="submit" onClick="changeAction('http://www.runelocus.com/toplist/index.php?action=vote&id=30838&id2=');")>RuneLocus</button></div>
</form><br>
im not sure what to add, i think i need to do something with the next button.. but please help! another thing is its a html... should it be php?
but the mysql is working fine and is sending to the client.
its just getting the username to be sent to the database,
heres check vote
if (!$con) {
die("Could not connect to database: " . mysql_error());
}
mysql_select_db("a5999082_oxidepk", $con);
$username = mysql_escape_string($_GET['username']);
if (isset($_GET['username'])) {
$result = mysql_query("SELECT * FROM `votes` where username = '$username'") or die(mysql_error());
$row = mysql_fetch_array($result);
if($row['username'] == $username) {
mysql_query("DELETE FROM `votes` where username = '$username'");
echo "true";
} else {
echo "false";
}
}
mysql_close($con);
and then heres the Call back
<?php
$rspscoding = gethostbyname("http://www.oxidepkz.net63.net");
if($_SERVER['REMOTE_ADDR'] == $rspscoding) {
$con = mysql_connect("mysql1.000webhost.com", "a5999082_oxidepk", "password");
if (!$con) {
die("Could not connect to database: " . mysql_error());
}
mysql_select_db("a5999082_oxidepk", $con);
$username = mysql_escape_string($_GET['username']);
if (isset($_GET['username'])) {
mysql_query("INSERT INTO `votes` (username) VALUES ('$username')") or die(mysql_error());
}
mysql_close($con);
}
?>
also not sure what gethostbyname should be... thanks!
So... several comments
First, you're not sanitizing your data, which leaves you open to SQL injection.
Second, you posted your database credentials in your code example. Anyone reading this can see them and access your database. Editing won't fix that (will still be in history) so I would HIGHLY recommend you change your database credentials. Next time you might want to remove those before posting.
Third, you need to stop using mysql and switch to mysqli
Why shouldn't I use mysql_* functions in PHP?
Fourth, you're using (in a confusing way)
$rspscoding = gethostbyname("http://www.oxidepkz.net63.net");
if($_SERVER['REMOTE_ADDR'] == $rspscoding) { }
That will never succeed because $_SERVER['REMOTE_ADDR'] contains the IP of the user, not the host name (and your user won't be posting from your server either, which is what I assume $rspscoding is). Check out the PHP $_SERVER reference.
I want to show different content if a user is admin(2), or noarmal user(1). Login works fine, but i don't know hot to check if a user have 'usertype' 1 or 2? I want to use PHP $_SESSION.
This is my login form:
<!-- Log in -->
<form method="post" action="authentication.php">
<input type="text" name="userid" placeholder="E-mail" required/>
<input type="password" name="password" placeholder="Password" required/><br>
<button type="submit" name="submit" class="btn">Log in</button>
</form>
This is my authentication.php:
session_start();
if(isset($_POST['userid']) && isset($_POST['password'])){
$userid = $_POST['userid'];
$password = $_POST['password'];
$dbc = mysqli_connect('localhost', 'root', '', 'news');
if(!$dbc){
echo "Cannot connect to database";
exit;
}
$query = "SELECT * FROM users_tbl WHERE email = '$userid' AND password = sha1('$password')";
$result = $dbc->query($query);
if($result->num_rows)
{
$_SESSION['valid_user'] = $userid;
}
$dbc->close();
}
if(isset($_SESSION['valid_user'])){
header("location:prefs.php");
}else{
header("location:login.php");
echo 'Error';
}
This is what i have tried:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('news');
$sql = "SELECT users_tbl.usertype FROM users_tbl";
$result = mysql_query($sql);
$user = mysql_fetch_array($result);
$_SESSION['user'] = $user['user'];
$_SESSION['usertype'] = $user['usertype'];
if($_SESSION['user']['usertype'] == 2)
{?>
<h1>Only admin stuff</h1>
<$? }//Endif user is admin(2) ?>
Maybe instead of doing the query for everytime to check if a user is admin, i could save a $_SESSION['usertype'], and then use this to check if a user is 2, for admin, maybe when a user is loggin in? But i do not know how to do this. I'm quite new at this.
try this
if($_SESSION['usertype'] == 2)
{
//do stuff here
}
if ($_SESSION['usertype']) == 1)
{
//do stuff here
}
edit :
if you dont want write so many stuff and you want just include admin stuff inside this one of users just do this
if ($_SESSION['usertype']) == 1 or $_SESSION['usertype']) == 2)
{
//do stuff here for them both admin and users
if($_SESSION['usertype'] == 2 )
{
//do extra stuff here for only admin
}
}
I realize that this is an old question, however I have spent the last week searching the internet looking for an answer to this question as I have had a similar issue. "echo_Me" had the answer, but I see some incorrect syntax. After toying around with it on a localserver, this is what I did.
if($_SESSION['usertype']) == 1 or $_SESSION['usertype']) ==2)
//> start end < end < < end
{
//do stuff here for them both admin and users
if($_SESSION['usertype'] == 2)
{
//Do other stuff for usertype 2
}
}
You have more End Parenthesis then you do start ones.
I set all of the session variables I need when I run the login script for my website. So if I need a session variable, here is how I would handle it:
if($_SESSION['user']['usertype'] == 1 OR $_SESSION['user']['usertype'] == 2) { ?>
// Do Stuff for normal user and admin
<?php } if($_SESSION['user']['usertype'] == 2) { ?>
// DO Stuff for admin only
<?php } ?>
As you can see, the first if statement only has one set of parenthesis. And really, you can remove some of the php code, and just do regular html/css markup then the if statement for usertype of 2 for stuff for admin.
<!-- HTML Markup for both Admin and Regular Users Goes Here above if statement -->
<?php if($_SESSION['user']['usertype'] == 2 { ?>
// Markup for Admin only
<?php } ?>
Also, I would recommend not having the password set in the session variables. In that code, you may have it not do that, I am just unfamiliar with mysqli as I use PDO.
You can save your user type with session variable
Once logged in you need to check with db with the user type for 1 or 2 and store that variable with session variable like $_SESSION['user_type'].
So based on that you can track.
Try to add a column with user type to that table.
Check the value of that column while fetching data from the table. If the value is admin, show the text otherwise not.
I'm a beginner in the programming field..
My concept is just to move,to the home page from the login page after doing the checking of user id and password. i have a database table with fields 'user_id' & 'password'. so i want to get the datas from the table to array and then want to compare it with the values entered by the user...How is it possible in the most easiest way?
I always use
$query = "...";
$sql = mysql_query($query);
while($row = mysql_fetch_assoc($sql)) {
$user_id = $row['user_id'];
// ...
}
I think that should work better as you get an associative array, so you can work with the field names.
Note that if you're selecting SUM(*), you have to put $row['SUM(*)'] or give it a name via SQL.
Although you've shown little research and your question is quite broad, I'll show you an example that might give you some clues.
$username = mysql_real_escape_string($_POST['username']); //escaping the string, will use it in a query
$password = $_POST['password'];
$result = mysql_query("SELECT password FROM users WHERE username = '$username'");
if (mysql_num_rows($result) == 1) { // Expecting one result
$userdata = mysql_fetch_array($result);
if ($password == $userdata['password']) {
// USER IS AUTHORISED
} else {
// USER IS NOT AUTHORISED
}
}
This is a simple example.
Things to consider:
Although I did that in the example above to simplify things, do not store password as plaintext in the database - store a MD5 hash instead. You can generate a hash by using md5("string to hash"). If you need help with that start another question.
After you have authorised the user you can "remember" that by using PHP sessions. Again, if you need help with that ask another question.
$username="username";
$password="password";
//Specify MySQL database to connect to
$database="database";
//Create connection and select the appropriate database
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
//Get the username and password from posted form
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
//Build the query to look for users that exist with that username/password combination
//Here I'm using the users table within my database
$query = "SELECT * FROM users where username=\"$username\" and password = \"$password\" ";
//Retrieve the results of the query, and also aquire the number of records returned
$result = mysql_query($query);
$num = mysql_numrows($result);
//Check to see how many records are returned
if ($num>0)
{
//User login was successful
echo 'success login';
} else {
//Login was unsuccessful
echo 'user name not found';
}
Try this
//HTML
<form method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="login" value="login"/>
</form>
//PHP
if(isset($_POST['login']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$query = "select username,password from tableName
where username='$username' and password='$password'";
$sql = mysql_query($query);
if(mysql_num_rows($sql) == 1)
{
// Login success save username in session redirect to homepage
header("location:homepage.php");
exit();
}
else
{
// Display error message
}
}