I am trying something very basic yet it is failing to work for some reason! well basically I am trying to create a new username and password for my site. It is only for testing. When I submit the request, I get this:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'santoshs'#'localhost' (using password: NO) in /home/khali197/public_html/test/enroll.php on line 27
I have no idea who is santoshs that is showing here # localhost. From home it shows someone different. What could it be?
I've got the following code to try achieve my objective...all pretty simple really:
<?php
class ServerConnection{
function connect(){
$mysqli = new mysqli("localhost", "dsdssd_admin", "sddsdsd",
"khadsdsli197_dsd");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" .
$mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
//echo $mysqli->host_info . "\n";
}
}
?>
the register.php form:
<form name="register" action="enroll.php" method="post">
Username: <input type="text" name="username" maxlength="30" />
Password: <input type="password" name="pass1" />
Password Again: <input type="password" name="pass2" />
<input type="submit" value="Register" />
</form>
and the form to handle that, i.e. enroll.php:
<?php
include("ServerConnection.php");
//retrieve our data from POST
$username = $_POST['username'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 != $pass2)
header('Location: register_form.php');
if(strlen($username) > 30)
header('Location: register_form.php');
$hash = hash('sha256', $pass1);
//creates a 3 character sequence
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
$connection = new ServerConnection();
$connection->connect();
$username = mysql_real_escape_string($username);
$query = "INSERT INTO users ( username, password, salt )
VALUES ( '$username' , '$hash' , '$salt' );";
mysql_query($query);
mysql_close();
header('Location: index.php');
?>
Any help here would be highly appreciated! Thanks in advance
MySQL is not MySQLi. If you're using the MySQLi extension, don't use the mysql_real_escape_string function. They're two entirely different database drivers.
When you call the mysql_real_escape_string() function it searches for earlier mysql connection opened, NOT mysqli connection. If it can not find it tries to open a new connection with system login user. If your system username is santoshs then this is the reason.
The solution would be to change the ServerConnection class to use mysql extension or use the mysqli extension in enrole.php
That you're seeing the error when calling mysql_real_escape_string() implies you've not trapping the error at mysql_connect() - so even before considering what the user is, it's evident that the code which is running is not the code you've shown us.
Try adding some error detection at mysql_connect() in ServerConnection.php and check the permissions for the user santoshs
Related
I have a login.html in which the form is defined as follows:
<form method="post" action= "do_authorize.php" name="lform">
<span class="style1">First Initial Plus Last Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
My do_authorize is as follows:
<?php
session_start();
require('../databaseConnectionFileFolder/dbconnection.php');
$user = $_POST["user"];
var_dump($user);
$_SESSION['username']=$user;
var_dump($user);
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
var_dump($sql);
$result=#mysql_query($sql,$connection) or die("couldn't execute query");
$num=mysql_numrows($result);
if ($num != 0) {
/*$cookie_name="$user";
$cookie_value="ok";
$cookie_expire=time()+86400;
$cookie_domain=".columbia.edu";
setcookie($cookie_name, $cookie_value, $cookie_expire, "/", $cookie_domain, 0);
*/
print "<script>";
print "self.location='somethingelse.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
My dbconnection.php file is as follows:
<?php
$db_server = "localhost";
$db_name = "DailyExerciseDB";
$db_user = "abc5"; //the database username
//$db_password = "123"; // the database user pasword
$connection=#mysql_connect($db_server,$db_user) or die("Could Not Connect to the Database : ". mysql_error());
var_dump($connection);
$db=#mysql_select_db($db_name, $connection) or die("Could Not Select the Database". mysqli_connect_error());
//var_dump($db);
?>
My Questions:
1) I keep on getting Could Not Select the Database, why does the warning/error message corresponding to . mysqli_connect_error() doesn't get printed on the browser?
2) I have manually entered the user with username abc5 in the database and still it's not able to connect.Does anyone know why?
3) Even if I don't enter anything in the login.html and press login button, the following files gets executed, how can I take user entered into account while verifying with database? I believe since its hardcoded right now abc5, all files are getting executed.
4) var_dump($connection); prints resource(4, mysql link)
mysql_connect() has a third parameter which I'm not seeing you use: the password. Consider the following line:
mysql_connect($db_server, $db_username, $db_password);
Also, you should probably be using mysqli extension instead of the mysql extension (mysql is deprecated in PHP 5.5.0).
I also see you're mixing the mysql and mysqli functions in your code. This is the reason why mysqli_connect_error() shows nothing.
I´ve a problem a login, the page doesn´t show anything. This is the code:
PHP:
<?php
require 'connect_db.php';
/* start the session */
session_start();
conectar();
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM teachers WHERE email='$email' and password='$password'";
$result = mysql_query($sql);
// counting table row
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['loggedin'] = true;
$_SESSION['email'] = $email;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (10 * 60) ;
echo "<body><p>Welcome! </p></body>";
}
else
{
echo "Mail or password not correct.";
echo "<a href='teacher.html'>Try again</a>";
}
//$conexion->close();
?>
The HTML calling this code is:
<form action= "php/login_profesores.php" method="POST" onsubmit="return validacion()">
<label>Mail</label>
<input type="text" class="" id="inputMail"></input></br></br>
<label>DNI</label>
<input type="password" id="inputDNI"></input></br>
<input name="Enviar" type="submit" class="submit" value="Send" /></input></br>
</form>
validación() is the javascript code what works, but the problem is that php doesn´t show any page when the user logins in the system. The DB is well-configured and teacher´s table exists.
connect_db
<?php
function conectar()
{
define('DB_SERVER','http://**/');
define('DB_NAME','**');
define('DB_USER','**');
define('DB_PASS','**');
$conexion=new mysqli();
$conexion->connect('DB_SERVER','DB_USER','DB_PASS', 'DB_NAME');
$error=$conexion->connect_error; //Tambien vale connect_error
echo $error;
}
?>
You must have name attribute in your input fields if you want to pass the value using POST, GET or any other method.
<input type="text" class="" name="email" id="inputMail"></input></br></br>
<label>DNI</label>
<input type="password" name="password" id="inputDNI"></input></br>
In the form you are specifing input types but you are not specifying names for that.
You are using MySQL_ procedural in your PHP page but you're using MySQLi_ Object Orientated in your connection page.
Update everything to MySQLi (object orientated). MySQL_ is now deprecated and no longer supported and should not be used.
You should also check with your SQL that it allows access from the IP address your page is trying to access it from. If they are on the same server then you should replace your SQL database connection address with localhost .
Thanks, it works! I had to write the name of server without http:// and I had another problem mixing mysql and mysqli because it is not correct.
I'm trying to use the following form to log in, but it always jump to invalid username. Am I missing anything in here?
Database Connection:
$link = mysqli_connect("localhost","X","X","X");
if($link == false) {
die("Error" .mysqli_connect_error());
}
Login Script:
<?php
if (!isset($_POST['submit'])) {
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
// Include database credentials
include('../db_connect.php');
$mysqli = new mysqli($link);
// check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from admin WHERE admin_email LIKE '{$username}' AND admin_password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
}
?>
I'm not 100% sure, but I think getting rid of the {} around the $username and $password should fix the issue, and yea, using LIKE for login is bad. I could then type %abijeet% in my username and %p% in the password field and get logged in as long as there is someone called abijeet in the system and has a password with the letter p in it.
Using PDO
Also, filtering the input from the $_POST is a good idea. In general, I'd ask you to drop using mysqli and look into PDO - http://php.net/manual/en/book.pdo.php
Using PDO properly with parameters will secure you against SQL Injection attacks.
Hashing the password
Don't store the password in plain test, hash it before saving. Check here - http://php.net/manual/en/function.password-hash.php
UPDATE -
OK, so as pointed out the {} are ok. Another thing that looks suspicious to me is the condition checking.
I would change it to this -
// Check the condition checking below!
if ($result->num_rows !== 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
It could be an operator precedence issue and is anyways more confusing.
I'm creating a Log-in Form for my employees. I think there's a port problem with my local host port for mySQL on xampp but I don't know. Aren't Apache and mySQL supposed to be run from the same port? but anyway...
On xampp, my apache port is 8080 so "localhost:8080". My mySQL port is 3306 so I used "localhost:3306" for my "$host" variable in my php. Now, "login.php" is the "form action" I used in my html which is also the name of the document, so my php and my html are all on the same page - no separate documents; just to clear that up.
The problem: When I click the equivalent of "submit", none of my "echoed" or "error" code goes through. Basically, the page stays the same. Nothing happens. If I screw up the password on purpose, none of my errors come through. I stay on the same page, unable to see if ANYTHING worked. There's nothing to show me if what I did worked or not.
My phpMyAdmin database name is "accounts" and the table is named "users".
My php is located here
My html is located here
Again:
PHP
<?php
session_start();
$host = "localhost:3306";
$user = "root";
$pass = "password";
$db = "accounts";
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if (isset($_POST['user'])) {
$username = $_POST['user'];
$password = $_POST['pass'];
$sql = "SELECT * FROM users WHERE User='".$user."' AND Pass='".$pass."' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows($res) == 1) {
echo "You have successfully logged in.";
exit();
} else {
echo "Invalid login information. Please return to the previous page.";
exit();
}
}
?>
HTML
<form action="login.php" method="post">
<p>User</p><input type="text" name="user" size="30" />
<p>Pass</p><input type="password" name="pass" size="30" />
</br><p><submit><input type="submit" name="submit" value="Log In" /></submit></p>
</form>
Please help. I have to get this up and running for an event I have in a week and a half and I still have a LOT of work to do because this has taken me too long.
Thank You,
Dan
You're using the wrong variables in
$sql = "SELECT * FROM users WHERE User='".$user."' AND Pass='".$pass."' LIMIT 1";
Look at these, those are the variables you should be using.
$username = $_POST['user'];
$password = $_POST['pass'];`
Error reporting would have thrown an Undefined variable notice.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Plus this:
<submit><input type="submit" name="submit" value="Log In" /></submit>
<submit></submit> are invalid tags; remove them.
I would also like to note that your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Edit:
As per your comment about deprecation, it's time for you to move to mysqli_ or PDO.
Here is a mysqli_ basic version and variables fix:
<?php
session_start();
$host = "localhost:3306";
$user = "root";
$pass = "password";
$db = "accounts";
$connect = mysqli_connect($host, $user, $pass, $db);
if (isset($_POST['user'])) {
$username = $_POST['user'];
$password = $_POST['pass'];
$sql = "SELECT * FROM users WHERE User='".$username."' AND Pass='".$password."' LIMIT 1";
$res = mysqli_query($connect, $sql) or die (mysqli_error($connect));
if (mysqli_num_rows($res) == 1) {
echo "You have successfully logged in.";
exit();
} else {
echo "Invalid login information. Please return to the previous page.";
exit();
}
}
?>
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
I looked at previos Undefined error questions to see if I could find help for my question, but I can't seem to fix it for my problem.
So when I try to log in a user I get an error that says Undefined index:
No sure why Im getting this message on my login.php page
I have a database and a table called users with data inserted
this is what I use to connect to the database
conn.php
<?php
session_start();
$dbhost = "127.0.0.1"; // my database
$dbname = "fxdme";
$dbuser = "root";
$dbpass = "";
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname) or die("MySQL Error: " . mysqli_error("Cant Connect"));
?>
the login script
login.php
<?php include 'template/header.php';?>
<form action="login.php" method="POST">
User Name: <input type="text" name="username" />
Password: <input type="password" name="password"/>
<input class="submit" name="submit" type="submit" value="Log In"/>
</form>
<?php
$result=$mysqli->query('SELECT * FROM users WHERE username = "' .
$_POST['username'] . '" AND password = "' . $_POST['password'] . '"');
//set session user
$row = $result->fetch_assoc();
$_SESSION['user_id'] = $row['id'];
if ($_SESSION['user_id']) {
echo "You are logged in, $session_username. <a href='logout.php'>Log out</a>"; }
else {
echo " cant log in";
}
?>
// Index page
My index page
index.php
//in the template header is where Im calling my conn file
<?php include 'template/header.php'; ?>
<?php
if (isset($_GET['invalid'])) {
echo "<tr><td colspan='2' align='right'>Invalid login.</td></tr>";
}
?>
Im trying to get the error fixed so I'm not worried about sql injections at the moment. I just want to be able to login and and worry about the other stuff later.
You will find that $_POST["username"] will return invalid index if username is not in the post variables.
I usually create a set of variables to hold the my post variables so I can do validation and normalisation of the data first
So before your query statement
$username=(isset($_POST) && isset($_POST["username"]) ? $_POST["username"] : "";
$password=(isset($_POST) && isset($_POST["password"]) ? $_POST["password"] : "";
then use $username and $password in your query. You could event turn the previous statements into a function call passing in the variable name to check.
function getPostVar($name) {
return (isset($_POST) && isset($_POST[$name]) ? $_POST[$name] : "";
}
$username=getPostVar("username");
$password=getPostVar("password");
Obviously your code is ripe for sql injection with at username of ' union select * from users --
There is not anything in your code to make a query string in URL to fetch by $_GET. How can you have an index when you don't have anything ?
For what you said, you must use a header('location:index.php?invalid=1'); if the user can not log in to your system.
Might not be the same issue for you but I had this same error when converting to mysqli and my fetch statement looked the same as yours.
try changing.
$row = $result->fetch_assoc();
to
$row = $result->fetch_array(MYSQLI_ASSOC));