PHP registered user check - php

I have PHP + AS3 user login&register modul.I want to check registered user by username.But can't do it because I'm new at PHP.If you can help it will helpfull thx.(result_message part is my AS3 info text box.)
<?php
include_once("connect.php");
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";
mysql_query($sql) or exit("result_message=Error");
exit("result_message=success.");
?>

Use MySQLi as your PHP function. Start there, it's safer.
Connect your DB -
$host = "////";
$user = "////";
$pass = "////";
$dbName = "////";
$db = new mysqli($host, $user, $pass, $dbName);
if($db->connect_errno){
echo "Failed to connect to MySQL: " .
$db->connect_errno . "<br>";
}
If you are getting the information from the form -
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
you can query the DB and check the username and password -
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $db->query($query);
If you get something back -
if($result) {
//CHECK PASSWORD TO VERIFY
} else {
echo "No user found.";
}
then verify the password. You could also attempt to verify the username and password at the same time in your MySQL query like so -
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password';
#Brad is right, though. You should take a little more precaution when writing this as it is easily susceptible to hacks. This is a pretty good starter guide - http://codular.com/php-mysqli

Using PDO is a good start, your connect.php should include something like the following:
try {
$db = new PDO('mysql:host=host','dbname=name','mysql_username','mysql_password');
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Your insert would go something like:
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES (?, ?, ?)";
$std = $db->prepare($sql);
$std = execute(array($username, $password, $userbio));
To find a user you could query similarly setting your $username manually of from $_POST:
$query = "SELECT * FROM users WHERE username = ?";
$std = $db->prepare($query)
$std = execute($username);
$result = $std->fetchAll();
if($result) {
foreach ($result as $user) { print_r($user); }
} else { echo "No Users found."; }
It is important to bind your values, yet another guide for reference, since I do not have enough rep yet to link for each PDO command directly from the manual, this guide and website has helped me out a lot with PHP and PDO.

Related

PHP not posting onto mySQL database

This code should check for existing usernames and if there isn't one, it should create a new one. No matter what it won't add. Additionally, as you can see in the code it only echoes 'here' and doesn't echo 'not here'.
<?php
$password = "hey";
$username = "hi";
require "conn.php";
//$password = $_POST["password"];
//$username = $_POST["username"];
echo 'here';
$result = $conn->query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
echo 'not here';
if ($result) {
if($result->num_rows === 0)
{
$stmt = $conn->prepare("INSERT INTO UserData (username,password) VALUES (:username,:password)");
$params = array(
':username' => $username,
':password' => $password
);
$stmt->execute($params);
}
}
?>
This is the connection code:
<?php
//$db_name = "xxx";
//$mysql_username = "xxx";
//$mysql_password = "xxx";
//$server_name = "xxx";
// Create connection
$conn = new mysqli("xxx","xxx","xxx","xxx");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Changes:
<?php
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', /*$_POST["username"]*/ $username );
$username = 'hi';
$stmt->execute();
$stmt->store_result();
echo "debug 2";
if ($stmt->num_rows == 0){ // username not taken
echo "debug 3";
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
$password =(/*$_POST["password"]*/ "hey");
$username =(/* $_POST["username"]*/ "hi");
$stmt2->bind_param('s',$username);
$stmt2->bind_param('s',$password);
$stmt2->execute();
if ($stmt2->affected_rows == 1){
echo 'Insert was successful.';
}else{ echo 'Insert failed.';
var_dump($stmt2);
}
}else{ echo 'That username exists already.';}
?>
This code gets through all of the debugs but for some reason, it is still not inserting.
Replace this line
$result = **$mysqli->**query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
with following
$result = **$conn->**query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
The mysqli and PDO interfaces must not be mixed. Here the database connection and the SELECT query are both using the mysqli interface. But the second INSERT query is attempting to use the PDO interface, as evidenced by the use of named placeholders, and also the passing of a data array directly to execute(). The latter two features are not supported by mysqli, hence the code fails at the second query. Also, note that the second query is using prepared statements, while the first one is not. Again, different approaches should not be mixed together.
Also it appears that passwords are being stored as plain text, with no security. The proper approach is to use the password_hash function.
Just ensure that the database field has enough width (say 80-120 characters or more) to handle the current bcrypt hash, plus allow some more for future changes.
Staying with the mysqli interface (and with password_hash), the code could go something like this:
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', $_POST["username"]);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0){ // username not taken
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
$stmt2->bind_param('s', $_POST["username"]);
$stmt2->bind_param('s', $password);
$stmt2->execute();
if ($stmt2->affected_rows == 1)
echo 'Insert was successful.';
else echo 'Insert failed.';
}
else echo 'That username exists already.';
Note that the above approach would not be suitable for a high-traffic site, where there is a chance condition of another user trying to INSERT the same username, during the brief interval of time between the SELECT and INSERT database queries. That would require a different approach, like ensuring the subject database field is set to UNIQUE (which is good practice anyway), and then testing for violation of that UNIQUE field upon attempted duplicate insertion.
Assuming database and INSERT permissions are all set up OK and it is still not inserting, try enhancing the error-reporting.
Ensure the following are at the top of the page:
ini_set('display_errors', true);
error_reporting(E_ALL);
And put the following before the first query:
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;
Then try again.

multiple query in one php file , i tried to write the code but i am not getting it done

I want to execute mysql_qry1 also , how should i do it , till now my code is working fine but i want to execute the second query also(mysql_qry1) , please help.
<?php
require "conn.php";
$status=1;
$user_name = $_POST["user"];
$user_pass = $_POST["pass"];
$mysql_qry = "select * from tbl_client where username like '$user_name' and password like '$user_pass'";
$mysql_qry1 = "insert into login_status (username, status) values ('$user_name','$status)";
$result = mysqli_query($conn , $mysql_qry);
if(mysqli_num_rows($result)==1) {
echo "login success , Hello";
}
else {
echo "login failed";
}
$conn->close();
?>
Your SQL is one of most dangerous, please try to re-write:
//$mysql_qry = "select * from tbl_client where username like '$user_name' and password like '$user_pass'";
I m not sure what is in our conn.php, here is one of the example to update (PDO):
$sql = 'select 1 from tbl_client where username = :user and password = :pass';
$sth = $dbL->prepare($sql);
$sth->execute(':user' => $user_name, ':pass' => $user_pass);
$row = $sth->fetch(PDO::FETCH_NUM);
if ($row[0]) {
echo 'Login OK';
} else {
echo 'Login Failed';
}
$sql = 'insert into login_status (username, status) values (:user, :status)';
$sth = $dbL->prepare($sql);
$sth->execute(':user' => $user_name, ':status' => $status);
OK, so your conn.php is using mysqli_ . Please refer to this page for help:
http://php.net/manual/en/mysqli-stmt.bind-param.php
And change above answer to:
$sql = 'select 1 from tbl_client where username = ? and password = ?';
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $user_name, $user_pass);
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch();
if ($row[0]) {
echo 'Login OK';
} else {
echo 'Login Failed';
}
I have not used mysqli before, so not quite familiar, even php.net is hard to find out some docs about it. Please google howto use: mysqli_stmt_fetch() and replace it with proper code
Why not update your conn.php to use PDO? (be careful, you might need to update all your other pages as well which are calling this file):
// conn.php
$pdo = 'mysql:host=' . $server_name . ';dbname=' . $db_name;
$dbL = new PDO($pdo, $mysql_username, $mysql_password);

PHP / MySQL: Login form doesn't work

I've got a login.php file which looks like this:
include "myfuncs.php";
$connect = dbConnection();
$username = $_POST["username"];
$passwort = md5($_POST["password"]);
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
if($row->password == $passwort)
{
echo "Hi $username";
$_SESSION["username"] = $username;
echo "Login successfully";
}
else
{
echo "Login doesn't work";
}
and a myfuncs.php file which looks like this:
function dbConnection()
{
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
$db_connect = new mysqli($servername, $username, $password, $dbname);
if ($db_connect->connect_error)
{
die("Connection failed: " . $db_connect->connect_error);
}
return $db_connect;
}
Unfortunately the login form doesn't work - it always gives the error "Login doesn't work" even when the username and password matches with the database entry.
Arg, you are mixing a mysqli with class mysql functions. I dont think it works...
It works this way : PHP MySQLI
$stmt = $mysqli->prepare($query)
while ($stmt->fetch()) {
(...)
}
I see you have error in your variable name in line #6.
try this:
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$result= mysql_query($query);
$row = mysql_fetch_object($result);
There are several problems with your code. In myfuncs.php you use mysqli and after that, in your code you use mysql (without "i"). mysql (without "i") is deprecated, so you should use mysqli everywhere.
More than that, in your code you have:
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
Please see the bold text from next two lines (it should be the same variable):
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
You should have
$result = mysql_query($query);
if you will use mysql.

Reducing MSQL Query to a specific session

Using the code below, I was able to display each username and trial 1/0 flag in the table. What I want to do is display the data only for the existing user so I can say something like "Hello USERNAME, you have TRIAL access..." etc...
We're using standard HTACESS as the un/pass to enter the info area.
What needs to change here to only show the existing user's session?
<?PHP
$user_name = "blahblahblah";
$password = "blahblahblah";
$database = "blahblahblah";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM member_auth";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) ) {
print $db_field['username'] . " : ";
print $db_field['trial'] . " <br> ";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
please don't use mysql_ functions.. look into PDO or MySQLi here: http://www.phptherightway.com/#databases
Update your query to only return specific user results.
Using Form POST:
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Using URL Parameters:
$username = mysql_real_escape_string($_GET["username"]);
$password = mysql_real_escape_string($_GET["password"]);
So your SQL query will now look like:
$SQL = "SELECT * FROM member_auth WHERE username = '" . $username . "' AND password = '" . $password . "'";

PHP mysql_real_escape_string(); whats the correct method using mysqli?

its a little difficult to explain. I've build the mysql function which works fine and with the depreciation of mysql I will need to change this function to use mysqli rather than the mysql method.
I current have:
$con = mysql_connect("host", "username", "pass");
mysql_select_db("db", $con);
$Username = mysql_real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$Query = mysql_query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'") or die(mysql_error());
$Query_Res = mysql_fetch_array($Query, MYSQL_NUM);
if($Query_Res[0] === '1')
{
//add session
header('Location: newpage.php');
}
else {
echo 'failed login';
}
Now I've applied mysqli to this and it's not returning any data or errors but the function still complies.
$log = new mysqli("host", "user", "pass");
$log->select_db("db");
$Username = $log->real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$qu = $log->query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'");
$res = $qu->fetch_array();
if($res[0] === '1'){
//add session
header('Location: newpage.php');
}
else {
$Error = 'Failed login';
sleep(0.5);
}
echo $res['username'].' hello';
}
But I'm unsure on why this is wrong. I know it's probably a simply answer
Just to have it as an answer:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
e.g.
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
You may check if the connection is establishing before using real_escape_string()
if ($log->connect_errno) {
echo "Failed to connect to MySQL: (".$log->connect_errno.")".$log->connect_error;
}
afaik, there's no problem with $log->real_escape_string($_POST['user']);

Categories