Basic PHP-script doesn't work - php

I'm new to PHP and SQL but I'm trying to create a simple PHP-script that allows a user to login to a website. It doesn't work for some reason and I can't see why. Every time I try to login with the correct username & password, I get the error "Wrong Username or Password". The database-name and table-name are correct.
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect("$db_host", "$db_user", "$db_pass") or die("Unable to connect to MySQL.");
mysql_select_db($db_name)or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = ("SELECT * FROM $tbl_name WHERE username='$user' and password='$pass'");
$result= mysql_query($sql);
$count 0= mysql_num_rows($result);
if($count==1){
// Register $user, $pass send the user to "score.php"
session_register("user");
session_register("pass");
header("location:score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if(!session_is_registered(user)){
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
I hope someone can find my mistake, thanks!

FYI session_register and session_is_registered are deprecated and will be removed from PHP. Also try to change your code to use mysqli or PDO. Plenty of articles explain how to do it. Finally, make sure you escape input from the user ($_POST array) because you never know what the user will send and you don't want to be prone to SQL injections. You really do not want to store passwords in clear text, so using SHA1 or MD5 is best.
Having written the above, your code becomes (you can use the $_SESSION global array directly):
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect($db_host, $db_user, $db_pass) or die("Unable to connect to MySQL.");
mysql_select_db($db_name) or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = "SELECT * FROM $tbl_name "
. "WHERE username = '$user' "
. "AND password = sha1('$pass')";
$result = mysql_query($sql);
// There was an extra 0 here before the equals
$count = mysql_num_rows($result);
if ($count==1)
{
// Register $user, $pass send the user to "score.php"
$_SESSION['user'] = $user;
// You really don't need to store the password unless you use
// it somewhere else
$_SESSION['pass'] = $pass;
header("location: ./score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if (!isset($_SESSION['user']))
{
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>

A couple of things
Change this line to the one with error checking i have put below it
$result= mysql_query($sql);
$result= mysql_query($sql) or die(mysql_error());
chances are there is an sql error and you are not picking it up, so the result will always have 0 rows
Also not sure if this line is a typo or not, there shouldn't be a 0 in there
$count 0= mysql_num_rows($result);

Related

Mysql not connecting to server through php

I have been trying to connect to the mysql server through php code, but was unable to. Please help me solve this problem.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$bool = true;
mysql_connect("localhost", "root","rot_darshan") or die("Cannot connect to server"); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("Select * from users"); //Query the users table
while($row = mysql_fetch_array($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
if($username == $table_users) // checks if there are any matching fields
{
$bool = false; // sets bool to false
Print '<script>alert("Username has been taken!");</script>'; //Prompts the user
Print '<script>window.location.assign("register.php");</script>'; // redirects to register.php
}
}
if($bool) // checks if bool is true
{
mysql_query("INSERT INTO users (username, password,fname,lname,email) VALUES ('$username','$password','$fname','$lname','$email')"); //Inserts the value to table users
Print '<script>alert("Successfully Registered!");</script>'; // Prompts the user
Print '<script>window.location.assign("register.php");</script>'; // redirects to register.php
}
}
?>
Please avoid the native mysql_* functions. These are depricated and will be removed:
http://php.net/manual/en/function.mysql-connect.php
Try to follow (mysqli_*):
https://www.w3schools.com/php/php_mysql_connect.asp
$servername = "localhost";
$username = "root";
$password = "rot_darshan";
$database = "first_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Query example
$result = $conn->query("SELECT * FROM users")
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["username"]);
}
If these don't work, check your database credentials (username, password, database name and/or port)
Check for username,password by externally connecting .also replace localhost with 127.0.0.1 or your lan ip.
Check SELECT User, Host FROM mysql.user;

My code does not write anything on the database

This is my CODE, id do not know where is the mistake but this code does not create any information on the database.
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db($dbhandle);
if(isset($_POST['user']) && isset($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = mysql_query("SELECT * FROM users WHERE Username='$user'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "Username already exists!";
}else{
mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
header("location:begin.html");
}
}
mysql_close();
?>
Forget database name here.
change this:
$selected = mysql_select_db($dbhandle);
With
$selected = mysql_select_db($dbname,$dbhandle);
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db($dbhandle);
In above code you are not passing any database name to use, you should pass a database name instead of connection link to mysql_select_db($dbhandle);
like
$db_selected = mysql_select_db('foo', $link);
For reference
http://php.net/manual/en/function.mysql-select-db.php
Hi first of all Please use mysqli or PDO as mysql is depreciated and completely removed from PHP7.
Now your problem . You are not included database name in your mysql_select_db. It should be
$selected = mysql_select_db($dbhandle , $databasename) or die(mysql_error($dbhandle));
Always remember try to echo error after any query this will solve your problem in many cases

Error while updating the database with multiple php files

am trying to update the databse with the pubupdate.php file with the mentioned file but it is giving error Notice: Undefined index: user in C:\xampp\htdocs\Publication\form.php on line 3
Notice: Undefined index: pass in C:\xampp\htdocs\Publication\form.php on line 4. I don't know how this page is directed to form.php. However form.php has been used to create the account of the user so that user can login into the website. The login is done by the page login.php which is using the data which has been inserted in create.php. I don't know how to solve this problem and howcome pubupdate.php is directing to form.php and how to solve this problem.
I am posting the codes which I have used.
pubupdate.php
<?php
$typereg = $_POST['papertype'];
$ptitlereg = $_POST['ptitle'];
$fauthorreg = $_POST['firstauthor'];
$coauthorreg = $_POST['coauthor'];
$abstractreg = $_POST['abstract'];
$nameconreg = $_POST['namecon'];
$areareg = $_POST['area'];
$datereg = $_POST['date'];
$startpagereg = $_POST['startpage'];
$endpagereg = $_POST['endpage'];
$countryreg = $_POST['country'];
$taken = "false";
$database = "publication";
$password = "";
$username = "root";
$con = mysql_connect('localhost', $username, $password) or die("Unable to connect database");
#mysql_select_db($database, $con) or die("Unable to connect");
mysql_query("INSERT INTO `paper` VALUES('$typereg', '$ptitlereg','$fauthorreg','$coauthorreg','$abstractreg' ,'$nameconreg', '$areareg','$datereg', '$startpagereg', '$endpagereg', '$countryreg' )") or die("Strange Error");
echo "Account Created";
mysql_close($con);
header('Location: home.php');
?>
form.php
<?php
$userreg = $_POST['user'];
$passreg = $_POST['pass'];
$taken = "false";
$database = "publication";
$password = "";
$username = "root";
if($userreg && $passreg){
$con = mysql_connect('localhost', $username, $password) or die("Unalbe to connect database");
#mysql_select_db($database, $con) or die("Unalbe to connect");
mysql_query("INSERT INTO `users` VALUES('', '$userreg', '$passreg')") or die("Strange Error");
echo "Account Created";
mysql_close($con);
header("Location : index.html");
} else {
echo "You need to have both a username and password";
}
?>
create.php
<?php
$userreg = $_POST['user'];
$passreg = $_POST['pass'];
$fnamereg = $_POST['fname'];
$lnamereg = $_POST['lname'];
$desigreg = $_POST['designation'];
$taken = "false";
$database = "publication";
$password = "";
$username = "root";
if($userreg && $passreg){
$con = mysql_connect('localhost', $username, $password) or die("Unable to connect database");
#mysql_select_db($database, $con) or die("Unable to connect");
mysql_query("INSERT INTO `users` VALUES('', '$userreg','$passreg','$fnamereg','$lnamereg' ,'$desigreg')") or die("Strange Error");
echo "Account Created";
mysql_close($con);
header('Location: index.html');
} else {
echo "You need to have both a username and password";
}
?>
In your form where you use to get the inputs i.e., Username and Password.
You should give it a name
Something like
<input type='text' name='user'>
<input type='password' name='pass'>
It is clear that you didn't give the name field in your code.
Note :
In addition you can have your class or id according to your need.
Additional Note :
For Debugging, I would recommend you to deal such errors easily by checking whether the value exists..
You can do it easily by the below code
if (isset($_POST['user']))
{
echo 'Username value is - '.$_POST['user'];
}

Rehashing a password being changed PHP

I am currently having problems with hashing. Heres a bit of background;
The user creates an account, and their password is hashed using password_hash($password, PASSWORD_BCRYPT). Then, when they login, the password is checked via password_verify and if it is correct, they will be logged in.
However, when the user goes to their profile and edit's their details, changing their password, they can never login again. As well as this, if an employee changes the users password, they still cannot login.
I've been trying to look around and solve this but can't find anything, and what is the most wierd thing is that when an employee (lets say the admin account) changes another employees password, they can login fine with their new password? I've done pretty much the same code as the working changing password and rehashing code, but it still does not work.
Sign Up:
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "clientinformation"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
$clienttitle = $_POST["clienttitle"]; /*Retrieves the ClientTitle input from the user.*/
$clientforename = $_POST["clientforename"]; /*Retrieves the ClientForename input from the user.*/
$clientsurname = $_POST["clientsurname"]; /*Retrieves the ClientSurname input from the user.*/
$phonenumber = $_POST["phonenumber"]; /*Retrieves the PhoneNumber input from the user.*/
$clientusername = $_POST["clientusername"]; /*Retrieves the Username input from the user.*/
$clientpassword = $_POST["clientpassword"]; /*Retrieves the ClientPassword input from the user.*/
$emailaddress = $_POST["emailaddress"]; /*Retrieves the EmailAddress input from the user.*/
$billingaddress = $_POST["billingaddress"]; /*Retrieves the BillingAddress input from the user.*/
/*Here, each of the inputs are put through the 'stripslashes' function, which stops a MySQL injection attack.*/
$clienttitle = stripslashes($clienttitle);
$clientforename = stripslashes($clientforename);
$clientsurname = stripslashes($clientsurname);
$phonenumber = stripslashes($phonenumber);
$clientusername = stripslashes($clientusername);
$clientpassword = stripslashes($clientpassword);
$emailaddress = stripslashes($emailaddress);
$billingaddress = stripslashes($billingaddress);
/*The use of mysql_real_escape_string also stops a MySQL injection attack.*/
$clienttitle = mysql_real_escape_string($clienttitle);
$clientforename = mysql_real_escape_string($clientforename);
$clientsurname = mysql_real_escape_string($clientsurname);
$phonenumber = mysql_real_escape_string($phonenumber);
$clientusername = mysql_real_escape_string($clientusername);
$clientpassword = mysql_real_escape_string($clientpassword);
$emailaddress = mysql_real_escape_string($emailaddress);
$billingaddress = mysql_real_escape_string($billingaddress);
$hashedclientpassword = password_hash($clientpassword, PASSWORD_BCRYPT);
$query = "INSERT INTO $tablename (ClientID, ClientTitle, ClientForename, ClientSurname, PhoneNumber, Username, EmailAddress, ClientPassword, BillingAddress, SignUpDate)VALUES(NULL, '$clienttitle', '$clientforename', '$clientsurname', '$phonenumber', '$clientusername', '$emailaddress', '$hashedclientpassword', '$billingaddress', CURRENT_TIMESTAMP)";
$result = mysql_query($query);
if($result){
echo "Successful";
header("location:Index.php");
} else {
echo ("Unsuccessful : " . mysql_error());
}
mysql_close();
?>
Check Login:
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "clientinformation"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
/*This retrieves the data inserted by the user from the previous page. In this case, it is retrieving the username and password the user entered.*/
$userusername = $_POST["Username"];
$userpassword = $_POST["ClientPassword"];
/*Here, these four lines of code are used to stop an MySQL injection attack on the website/database.*/
$userusername = stripslashes($userusername);
$userpassword = stripslashes($userpassword);
$userusername = mysql_real_escape_string($userusername);
$userpassword = mysql_real_escape_string($userpassword);
$sql = "SELECT ClientPassword FROM $tablename WHERE Username = '$userusername'";
$result = mysql_query($sql);
$datarow = mysql_fetch_array($result);
$hasheduserpassword = $datarow['0'];
if (password_verify($userpassword, $hasheduserpassword)) {
session_start();
$_SESSION['Username'] = $userusername;
$_SESSION['ClientPassword'] = $hasheduserpassword;
header("Location:IndexUserLogin.php");
} else {
header("location:WrongPU.php");
}
?>
user editing their details:
<?php
session_start();
if(! $_SESSION['Username']) {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "clientinformation";
mysql_connect("$servername", "$username", "$password") or die("Cannot connect to the database.");
mysql_select_db("$dbname") or die ("Cannot select the database.");
$clientid = $_POST["clientid"];
$clienttitle = $_POST["clienttitle"];
$clientforename = $_POST["clientforename"];
$clientsurname = $_POST["clientsurname"];
$phonenumber = $_POST["phonenumber"];
$clientusername = $_POST["clientusername"];
$emailaddress = $_POST["emailaddress"];
$clientpassword = $_POST["clientpassword"];
$billingaddress = $_POST["billingaddress"];
$clientid = stripslashes($clientid);
$clienttitle = stripslashes($clienttitle);
$clientforename = stripslashes($clientforename);
$clientsurname = stripslashes($clientsurname);
$phonenumber = stripslashes($phonenumber);
$clientusername = stripslashes($clientusername);
$emailaddress = stripslashes($emailaddress);
$clientpassword = stripslashes($clientpassword);
$billingaddress = stripslashes($billingaddress);
$clientid = mysql_real_escape_string($clientid);
$clienttitle = mysql_real_escape_string($clienttitle);
$clientforename = mysql_real_escape_string($clientforename);
$clientsurname = mysql_real_escape_string($clientsurname);
$phonenumber = mysql_real_escape_string($phonenumber);
$clientusername = mysql_real_escape_string($clientusername);
$emailaddress = mysql_real_escape_string($emailaddress);
$clientpassword = mysql_real_escape_string($clientpassword);
$billingaddress = mysql_real_escape_string($billingaddress);
$hashedclientpassword = password_hash($clientpassword, PASSWORD_BCRYPT);
$query = "UPDATE $tablename SET ClientTitle = '$clienttitle', ClientForename = '$clientforename', ClientSurname = '$clientsurname', PhoneNumber = '$phonenumber', Username = '$clientusername', EmailAddress = '$emailaddress', ClientPassword = '$hashedclientpassword', BillingAddress = '$billingaddress' WHERE ClientID = '$clientid'";
$result = mysql_query($query);
if($result) {
echo "Successful update";
header("Location:UserCP.php");
} else {
echo ("ERROR : " . mysql_errno . " " . mysql_error());
}
?>
Edit employees details (works)
<?php
session_start();
if($_SESSION['EmployeeUsername'] !== "Admin") {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "employeelogin";
mysql_connect("$servername", "$username", "$password") or die("Cannot connect to the database.");
mysql_select_db("$dbname") or die ("Cannot select the database.");
$employeeid = $_POST['employeeid'];
$employeeusername = $_POST['employeeusername'];
$employeepassword = $_POST['employeepassword'];
$employeename = $_POST['employeename'];
$employeesurname = $_POST['employeesurname'];
$employeeid = stripslashes($employeeid);
$employeeusername = stripslashes($employeeusername);
$employeepassword = stripslashes($employeepassword);
$employeename = stripslashes($employeename);
$employeesurname = stripslashes($employeesurname);
$employeeid = mysql_real_escape_string($employeeid);
$employeeusername = mysql_real_escape_string($employeeusername);
$employeepassword = mysql_real_escape_string($employeepassword);
$employeename = mysql_real_escape_string($employeename);
$employeesurname = mysql_real_escape_string($employeesurname);
$hashedemployeepassword = password_hash($employeepassword, PASSWORD_BCRYPT);
$query = "UPDATE $tablename SET EmployeeID = '$employeeid', EmployeeUsername = '$employeeusername', EmployeePassword = '$hashedemployeepassword', EmployeeName = '$employeename', EmployeeSurname = '$employeesurname' WHERE EmployeeID = '$employeeid'";
$result = mysql_query($query);
if($result) {
echo "Successful update";
header("Location:EmployeeCP.php");
} else {
echo ("ERROR : " . mysql_errno . " " . mysql_error());
}
?>
Check employees login (work)
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "employeelogin"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
/*This retrieves the data inserted by the user from the previous page. In this case, it is retrieving the username and password the employee entered.*/
$employeeusername = $_POST["EmployeeUsername"];
$employeepassword = $_POST["EmployeePassword"];
/*Here, these four lines of code are used to stop an MySQL injection attack on the website/database.*/
$employeeusername = stripslashes($employeeusername);
$employeepassword = stripslashes($employeepassword);
$employeeusername = mysql_real_escape_string($employeeusername);
$employeepassword = mysql_real_escape_string($employeepassword);
$sql = "SELECT EmployeePassword FROM $tablename WHERE EmployeeUsername = '$employeeusername'";
$result = mysql_query($sql);
$datarow = mysql_fetch_array($result);
$hashedemployeepassword = $datarow['0'];
if (password_verify($employeepassword, $hashedemployeepassword)) {
session_start();
$_SESSION['EmployeeUsername'] = $employeeusername;
$_SESSION['EmployeePassword'] = $hashedemployeepassword;
header("Location:IndexEmployeeLogin.php");
} else {
header("location:WrongPU.php");
}
?>
Cheers for all and any responses
Remove all calls to stripslashes() and mysql_real_escape_string() for password input, the functions password_hash() and password_verify() accept even binary input and are not prone to SQL-injection. I assume this already solves your problem.
Escaping should be done as late as possible and only for the given target system, so the function mysqli_real_escape_string() should only be called to build an SQL query.
Check wheter in both tables (clientinformation and employeelogin), the password-hash field is declared with 60 characters or more.
If this doesn't solve your problem, i would use UTF-8 for all your pages. You can check your pages with this W3C checker, every page should be stored in the UTF-8 file format and define the UTF-8 header.
Test with isset whether a variable exists: if(!isset($_SESSION['Username']))
The password hash should not be stored in the session, but maybe this is only for testing purposes.
Setting the userid is not necessary: "UPDATE $tablename SET EmployeeID = '$employeeid', ... WHERE EmployeeID = '$employeeid'";
And it is a good habit to always call exit after a redirect:
header('Location: Index.php', true, 303);
exit;

Comparing database stringvalue with new stringvalue

Here is what I'm trying to do: When user adds a contact to his list, the number of this contact gets run by with the numbers in the database and it gives feedback if the user is already in the database or not. Right now I always get back "User is in database" even though he isn't. Then again I'm not that well acquainted with php. I changed the code a bit again, now it doesn't work at all, because it doesn't like the part
$number = ($_GET["number"] from $DB_Table);
Full code
<?php
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pw";
$DB_Table = "contacts";
$number = ($_GET["number"] from $DB_Table);
$fnumber = ($_GET["fnumber"]);
if ($number == $fnumber) {
echo "This user is already in database";
} else {
echo "This user isn't in the database";
}
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
mysql_close($con);
?>
I don't actually see you executing the database query. You could do something like this:
<?php
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pw";
$DB_Table = "contacts";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$fnumber = mysql_real_escape_string($_GET["fnumber"]);
$result = mysql_query("SELECT * FROM $DB_Table WHERE Something = '$fnumber'", $con);
if ($result) {
// Check the number of rows in the result set
if (mysql_num_rows($result) > 0) {
echo "This user is already in database";
}
else echo "This user isn't in the database";
}
mysql_close($con);
?>
This is not valid PHP code: $number = ($_GET["number"] from $DB_Table);
$_GET["number"] represents the value of the "number" parameter that you find in the url of your page.
Example: http://example.com/index.php?number=7 so $_GET["number"] is 7.
In your code, $DB_Table is a just a string ("contact") and "from" does not fit there using php syntax.
mysql_select_db($DB_Name,$con) or die(mysql_error());
is valid PHP but you are not doing anything with what you get from the database. I suggest you at least take a look at this tutorial php mysql select

Categories