What password and username do I use for mysql_connect()? - php

Okay so as you will probably be able to tell but, I am pretty new to MySQL and PHP and I have ran into a problem.. In my connect.php, which connects to the server, I don't know if my password and username along with the port are right. Now the reason it says port 8080 is because one of my other web development programs was using port 80 so I went in to the Apache files and changed to port, so now when I log into phpMyAdmin I have to type localhost:8080. I don't know if that has to do with mysql_connect, also I checked on phpMyAdmin and it says my username is root and my password is empty. Does the empty password mess with MySQL_connect()? Thanks, here's the code:
connect.php:
<?php
//This file allows me to easily connect to my database
mysql_connect("localhost:8080", "root", "");//connects to database, params are ("servername", "username", "password");
mysql_select_db("membersystem");//selects the table from db
?>
login.php:
<?php
error_reporting (E_ALL ^ E_NOTICE);//saves us from getting undefined index error
session_start();//makes it a sesion based system
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
</head>
<body>
<!--the action='./login.php' tells the page where its gonna send the info, and the method='post' makes it so it dosent show the users personal info -->
<?php
$form = "<form action='./login.php' method='post'>
<table>
<tr>
<td>Username</td>
<td><input type='text' name='user'/></td>
</tr>
<tr>
<td>Password</td>
<td><input type='password' name='password'/></td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='loginbtn' value='Login'/></td>
</tr>
</table>
</form>";
if($_POST['loginbtn']){//if loginbtn pressed
$user = $_POST['user'];//gets the username from text field from the form above
$password = $_POST['password'];//gets the password from text field from the form above
if($user){//checks if the username field from the form has been filled out
if($password){//checks if the password field from the form has been filled out
require("connect.php");//connects to db through connect.php
$password = md5(md5("gshgrYY665f".$password."gr76TH967G"));//encrypts the password
//echo "$password"; echos the hash for password (5f8b1a8d8f2471a2c7c17e0058873447 )
$query = mysql_query("SELECT * FROM users WHERE username='$user' ");//checks if the username is found in database
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);//gets the query associated with the php
$dbid = $row['id'];//gets the id from db
$dbuser = $row['username'];//gets the username from db
$dbpass = $row['password'];//gets the password from db
$dbactive= $row['active'];//gets the active value from db
if($password == $dbpass){
if($dbactive == 1){
//sets session info
$_SESSION['userid'] = $dbid;
$_SESSION['username'] = $dbuser;
echo "you have been logged in as <b>$dbuser</b>. <a href='./member.php'>Click here</a> to go to member page";
}
else
echo "You must activate your account to login. $form";
}
else
echo "You didnt enter the right pass. $form";
}
else
echo "The username you entered was not found. $form";
mysql_close();//closes connection
}
else
echo "You must enter your password. $form";
}
else
echo "You must enter your username. $form";
}
else
echo $form;
?>
</body>
</html>

You dont need to use 8080 simply use localhost because that port number is not related to mysql but related to webserver. Inorder to address the webserver only you need to use it like localhost:8080/project-name/
And dont use mysql_* methods. will get disappointed in future. Use mysqli
$con = new mysqli("localhost","root","","membersystem") or die('Connection failed');
$result = $con->query("Your query here");
or else you can use the same in procedural method with mysqli_* functions. But i prefer to go along with object oriented php.
Refer the documentation.
http://php.net/manual/en/book.mysqli.php

Make connection like
$conn=mysqli_connect("localhost","root","","membersystem");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
and w3schools link is http://www.w3schools.com/php/func_mysqli_select_db.asp

Related

PHP Warning: ldap_bind(): Unable to bind to server: invalid credentials

Hello to anyone who's reading this. So let me explain my issue first and I'll attach the code below.
I am using xampp apache server and microsoft active directory domain services on windows server 2016 (both on same VM). I am not a programmer myself particularly but what I am trying to do is using PHP to try to authenticate users in my active directory. At first the code worked and when I entered correct username and password it showed authenticated and this happened only once. Now whenever I try to authenticate, it just keeps giving me the same error that can't bind to ldap server and invalid credentials even though the usernames and passwords are totally correct. Before this I used a code that used one user credential hardcoded to bind and other hardcoded user credentials whos information I am fetching from AD and that code works fine but the other scenario mentioned above doesn't. PLZ Help
(my separate html form file that i am using)
<html>
</head><style>
body {text-align:center;}
form {margin: 0 auto;width:500px;}
input {padding:10px; font-size:20;}
</head></style>
</body>
<h1>Authentication With Active Directory</h1>
<form action="ldap.php" method="post">
<input type="text" name="username" /><br>
<input type="password" name="password" /><br>
<input type="submit" value="login" />
</form>
</body>
</html>
(my php file and both are stored in c:/xampp/htdocs/)
<?php
$ldap_dn = "CN=".$_POST["username"].",DC=example,DC=example";
$ldap_password = $_POST["password"];
$ldap_con = ldap_connect("example");
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);
if(ldap_bind(#$ldap_con,$ldap_dn,$ldap_password))
{
echo "Authenticated";
}
else
{
echo "Invalid Credential";
}
?>
(I have also tried following code to check if connection is established or not and the connection does establish but still it gives invalid credentials. I think there is something wrong with bind in my code but can't figure it out)
<?php
$username; $password;
$ldap_dn = "CN=".$_POST["username"].",DC=ADLAB,DC=local";
$ldap_password = $_POST["password"];
$ldap_con = ldap_connect("ADLAB.ADLAB.local");
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);
if ($ldap_con)
{
echo "connection established";
if(ldap_bind(#$ldap_con,$ldap_dn,$ldap_password))
{
echo "Authenticated";
}
else
{echo "Invalid Credential";
}
}
else
echo "conection failed";
?>
All Active Directory provides an internal email (ex: username#domain.dom). You can use this to authenticate the user with LDAP bind.
Before use, the values provided by the user, validate it to not contains an invalid character. See preg_match: https://www.php.net/manual/en/function.preg-match
CAUTION: The password must contain one character. If a password is not specified or is empty, an anonymous bind is attempted. See: https://www.php.net/manual/en/function.ldap-bind.php
<?php
$username = $_POST['username'];
$ldap_password = $_POST['password'];
$ldap_dn = $username.'#ADLAB.local';
if (empty($username) || empty($ldap_password) || !preg_match('/^[A-Za-z0-9\-_]$/', $username)) {
die("Invalid credential");
}
$ldap_con = ldap_connect("ADLAB.ADLAB.local");
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);
if ($ldap_con) { echo "connection established";
if(ldap_bind(#$ldap_con,$ldap_dn,$ldap_password))
{
echo "Authenticated";
}
else
{echo "Invalid Credential";
}
}
else
echo "conection failed";
?>

read database through sql without admin login

I have a problem every time two or more users are connecting to my app.
This is my code:
<?php
session_start();
$servername = "localhost";
$username = "admin";
$password = "my password";
$dbname="my dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully".'<br>';
if($_SESSION["connected"] == 1)
{echo "you are logged in";}
else { die("Please log in to access this page");
echo "not logged in";}
?>
<!DOCTYPE html>
<html>
<head>
<title>Messages</title>
<meta http-equiv="refresh" content="1">
</head>
<body>
<?php
$sql="SELECT * FROM `mesaje` where reciever='all' order by data desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
{
if($row["sender"]==$_SESSION["username"])
echo '<div style="background-color:blue;" align="right">';
else echo '<div style="background-color:black;" align="left">';
echo '<p style="color:white;">'.$row["mesaj"]."</p></div>";
} }}
?>
</body>
</html>
When I am the only user connected, there is no problem, everything is alright.
when 2 or more users connect, they receive this error:
WARNING: mysqli_construct():MySQL server has gone away
I think that this is because they are more users logged in with the same admin account (maybe I am wrong)
Is there any way to connect to the database and only read it using sql without admin login? Or any other solution to the problem, please!
I am new to SQL
The status report that you get on your phone would make me think, that the server can't handle the second login. What are you hosting it on?
If you think that it's because the two admins, then try create a guest login and connect your user to the db with that.
If all doesn't help, create a login system, that adds a little table with users and so on.

Comparing MYSQL password vs HTML form password

I have a Login form with UserId and Password.
I guess the problem is with md5 password in the mysql database.so How to compare HTML form password with mysql password.??
here is the code for the login form
<body>
<form method="post" action="validate_login.php" >
<table border="1" >
<tr>
<td><label for="LoginID">LoginID</label></td>
<td><input type="text"
name="LoginID" id="LoginID"></td>
</tr>
<tr>
<td><label for="password">password</label></td>
<td><input name="password"
type="password" id="password"></input></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/>
<td><input type="reset" value="Reset"/>
</tr>
</table>
</form>
</body>
And the php code :
<?php
// Grab User submitted information
$LoginID = $_POST["LoginID"];
$password = $_POST["password"];
//$UserID= $_POST["UserID"];
// Connect to the database
$username = "avaninfo_dairy";
$password = "CMANcustomersupportsystem1234#";
$hostname = "localhost";
//connection to the database
$con = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Select the database to use
mysql_select_db("avaninfo_dairy",$con);
$result = mysqli_query("SELECT * FROM cman_users WHERE LoginID = $LoginID");
$row = mysqli_fetch_array($result);
if($row["LoginID"]==$LoginID && $row["Password"]== $password)
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
?>
The way to do this would be to md5 encode using the same salt the password from the user and check it against the md5 hash stored on the database. http://php.net/md5
Use the md5 function
$row = mysqli_fetch_array($result);
if($row["LoginID"]==$LoginID && $row["Password"]== md5($password))
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
Use MD5 built in function:
if($row["LoginID"]==$LoginID && $row["Password"]== MD5($password))
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
(Assuming you want to compare an unhashed password to an md5 hashed password.)
Change $row["Password"] == $password to $row["Password"] == md5($password).
$row = mysqli_fetch_array($result);
if($row["LoginID"]==$LoginID && $row["Password"]== md5($password))
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
More info on md5: http://php.net/manual/en/function.md5.php
P.S. - If it is within your control, I recommend that you use password_hash() and password_verify() to hash your passwords.
It is much securer than md5().
You can use the md5 function. Also you do not need to check the LoginID because the SQL Select prefilters.
if($row["Password"]== md5($password))
However the overall security system is wrong. The web browser should send username and md5(password). The password should never be sent over the internet.
Also, the MD5 hash has been proven to be hackable. Use SHA-1 hash at a minimum.
And most systems Salt the Hash so that the same password for different users have a different hash value in the database.
<?php
// Grab User submitted information
$LoginID = $_POST["LoginID"];
$password = md5($_POST["password"]);
//$UserID= $_POST["UserID"];
// Connect to the database
$username = "avaninfo_dairy";
$password = "CMANcustomersupportsystem1234#";
$hostname = "localhost";
//connection to the database
$con = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Select the database to use
mysql_select_db("avaninfo_dairy",$con);
$result = mysqli_query("SELECT * FROM cman_users WHERE LoginID = $LoginID" and Password=$password);
$row = mysqli_num_row($result);
if($row>0)
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
?>
Try this one it will be work fine
The answer is simple. To have some clarity first you need to get an idea of whats going on.
Your MD5 Hashing algorithms which is stored in your database
"md5 password in the mysql database"
are one way. That means you cannot "undo" it once its encrypted. What you can do is compare a hashed value to it to see if it matches.
How to compare HTML form password with mysql password.??
this will compare the html form password with mysql password,
$hashed_value_from_mysql being your encrypted password from mysql and
$_POST[password] being your password from the form submission
where your name="password" is accessible through $_POST after
you submit the form depending on which method you use.
if ($hashed_value_from_mysql === md5('$_POST[password]')) {
//if the password matched do whatever here
} else {
//it doesn't match, throw an error
echo "password doesn't match";
}

Array Based Login - PHP

I wrote a script which verifies login detail based on array concept. It's not db based. Everything is working fine except one thing. Actually i have stored two login credentials in an array called $users.
If the user uses first login detail then login is always failed and prints message - "Wrong username or password" because the script matches the combination of each username and password with the incoming post data. And when user uses first credential, then the second credential gets failed and that's why we get "Wrong username or password". But if the user uses second login credential, then there is no problem and we get - "Login successful".
I know the reason why this is happening so, but couldn't resolve it yet. One common workaround could be to use header/redirection upon successful login so that wrong message for second login credentials dont appear.
But i want to print both the message according to login credential used - means successful login message should appear whether the user uses either first login credential or second one, and failed login message should appear if user doesn't use either of two login credentials. Here is my code -
<?php
$users = array();
$users["admin"] = "admin";
$users["test"] = 12345;
echo "<pre>";
print_r($users);
echo "</pre>";
if(isset($_POST['btnlogin']))
{
$uname = $_POST['txtuname'];
$pass = $_POST['txtpass'];
foreach($users as $username => $password)
{
if($username == $uname && $password == $pass)
{
$msg = "<p>Login successful</p>";
}
else
{
$msg = "<p>Wrong username or password</p>";
}
}
echo $msg;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Array Based Login</title>
</head>
<body>
<form method="post" action="">
<input type="text" name="txtuname" /><br /><br />
<input type="password" name="txtpass" /><br /><br />
<input type="submit" name="btnlogin" value="Login" />
</form>
</body>
</html>
if(isset($_POST['btnlogin']))
{
$uname = $_POST['txtuname'];
$pass = $_POST['txtpass'];
foreach($users as $username => $password)
{
if($username == $uname && $password == $pass)
{
$msg = "<p>Login successful</p>";
//if success break the loop
break;
}
else
{
$msg = "<p>Wrong username or password</p>";
}
}
echo $msg;
}
$username=$_POST['username'];
$password=$_POST['password'];
if(isset($users[$username])&&$users[$username]['userPassword']==$password)
{
echo $_POST['username'];
}
else{
echo "not found";
}
the multidimensional array data can be accessed without using for loops check this out
this answer for the this is the question

Verifying username/password via MySQL server using PDO functions

I am having some problem connecting properly to the MySQL server using the PDO function.
I can't query what I need from the database and I am not quite sure what PDO functions to use.
I GET 0 as a result of this.
I wish to verify the password and username I enter via the database and make an if statement that launches the session if the information is correct.
Here is my UPDATED code:
<?php
// if a value is given
if (isset($_POST['username' && 'password'));
{
// starts the session created if login info is correct
session_start();
// connectivity to MySQL server
$db = new PDO('mysql:host=host;dbname=name', 'username', 'password');
// information entered in form made into a variable
$username = PDO::quote($_POST['username']);
$password = PDO::quote($_POST['password']);
// after pressing login, checking if the variables exist in the database
if ($_POST['button'] == 'Login')
{
$query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
// Check the number of rows that match the SELECT statement
if($query = $db->fetch(PDO::FETCH_OBJ))
{
echo "No records found";
}
else
{
header("Location: members.php");
$_SESSION['username'] = $_POST['username'];
}
}
// After pressing register, stores variable and adds it in register field
else if ($_POST['register'] == 'Register')
{
header("Location: register.php");
$_SESSION['usernamereg'] = $_POST['username'];
}
// If no button is pressed, send to index
else
{
header("Location: http://www.gjertgjersund.com");
}
// closes the if value is given statement
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Folder </title>
<link rel="stylesheet" type="text/css" href="frontpage.css">
</head>
<body>
<div id="box">
<div id="wrap">
<center>
<img src="./img/logo.png" alt="logo">
<form action='index.php' method='POST' autocomplete='off'>
<div class="usernameform">
<input type='text' name='username' style='border: none; font-size: 20px;'>
</div>
<br />
<div class="passwordform">
<input type='password' name='password' style='border: none; font-size: 20px;'>
</div>
<br />
<div class="registerlogin">
<input type='submit' name='button' value='Login' class='input'>
<input type='submit' name='register' value='Register' class='inputtwo'>
</div>
</form>
</center>
</div>
</div>
</body>
</html>
That's a very good question, partially because it demonstrates a lot of bad practices that, sadly, exist to this day, almost a decade since this question has been posted. Let's sort them out
Connection
I am having some problem connecting properly to the MySQL server using the PDO function.
That's a fair question and nowhere the connection is just a single line of code. Мany important options have to be set, see a canonical connection example I wrote. You can store the connection code in a separate file and then just include it in your scripts.
Password hashing
You should never store plain passwords in your database. Instead, password must be hashed, using a dedicated function made for the purpose - password_hash().
Then, to verify the password, you've go to use password_verify()
Don't move any further until you have your passwords properly hashed. Note that the field size for the hashed password must be 60 characters long.
The code to verify username and password
Finally, now we can write the code. It could be much simpler, just a few lines. Actually, only one condition is needed. We shouldn't provide any details as to whether login or username not found - just "Login and password don't match". So here it goes:
<?php
if (isset($_POST['username']))
{
// get the PDO instance
include 'pdo.php';
// getting the record for the given username
$stmt = $pdo->prepare("SELECT * FROM login WHERE username=?");
$stmt->execute([$_POST['username']]);
$user = $stmt->fetch();
// verifying the password
if ($user && password_verify($_POST['password'], $user['password']))
{
// starts the session created if login info is correct
session_start();
$_SESSION['username'] = $user['username'];
header("Location: members.php");
exit;
} else {
$error = "Login and password don't match";
}
}
Here, we are checking whether such a user exists and whether the password matches in a single condition.
You should not have to use ' in prepared statement and $username is string not integer
$query = $db->query("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
$row_count = $query->rowCount();
//{ remove it
Your if condition is wrong change
// if a value is given
if (isset($_POST['username' && 'password'));
{
to
// if a value is given
if (isset($_POST['username']) and isset($_POST['password']))
{
Codepad
Some databases may return the number of rows returned by a SELECT statement. However, this behaviour is not guaranteed for all databases and should not be relied on see Manual. You can use COUNT(*) and fetchColumn() as in following query to emulate rowCount().
$query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
// Check the number of rows that match the SELECT statement
if($query->fetchColumn() == 0) {
echo "No records found";
}else{
//CODE FOR Success
//Etc
}

Categories