I am trying to use a simple hash for users emails and passwords.
But when I run the following php script that is called on an ajax request i fet a 505 error.
<?php
$user = json_decode(file_get_contents('php://input'));
$email = $user->email;
$pass = $user->pass;
$cpass = $user->cpass;
$ssid = $user->ssid;
$type = $user->type;
$date = $user->regtime;
$con = mysqli_connect("localhost", "", "", "");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$validateEmail = "SELECT `Email` FROM `newUsers` WHERE `Email` = '$email' ";
$newVar = password_hash($pass, PASSWORD_DEFAULT);
if ($result = mysqli_query($con,$validateEmail)) {
if ($result->num_rows == 0){
$sql = "INSERT INTO `newUsers`(`email`, `type`, `date`, `ssid`, `hashpass`) VALUES ('$email', '$type', '$date', '$ssid', '$newVar')";
mysqli_query($con,$sql);
}
}
mysqli_close($con);
?>
If i remove the hash attempt and leave the pass word as it is received the password gets inserted so I believe it is the hashing function that is causing the 505. Can anyone see what is going wrong with my hash attempt?
Related
I'm going through a course on MySQL, and I'm learning how to make a user entry bit of code (email and password) where the info in the script will be put into the database on phpMyAdmin. I can't seem to get it to work? My code doesn't have any errors when I put it through an error checker. I'm also completely new to PHP and MySQL. I know it can find the database, because I can update existing data.
<?php
$link = mysqli_connect("host", "username", "password", "username");
if (mysqli_connect_error()) {
die ("There was an error connecting to the database");
}
$query = "INSERT INTO `users` (`email`, `password`) VALUES('email', 'password')";
mysqli_query($link, $query);
$query = "SELECT * FROM users";
if ($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo "Your email is ".$row[1]." and your password is ".$row[2];
}
?>
Created a refined version. Check it.
<?php
$link = mysqli_connect("host", "username", "password", "username");
if (mysqli_connect_error()) {
die ("There was an error connecting to the database");
}
$query = "INSERT INTO `users` (`email`, `password`) VALUES('email', 'password')";
$result = mysqli_query($link, $query);
if($result != false)
{
echo "The record has been successfully inserted.<br>";
}
else
{
echo "Error Occured in the INSERT query.<br>Error : ".mysqli_error($link);
}
$query = "SELECT * FROM users";
$result = mysqli_query($link, $query);
if($result != false)
{
echo mysqli_num_rows($result)." Records found.<br>";
while($rows = mysqli_fetch_array($result))
{
echo $rows["email"]."<br>";
}
}
else
{
echo "Error Occured in the SELECT query.<br>Error : ".mysqli_error($link);
}
mysqli_close($link);
?>
Update
It turns out I didn't set the auto_increment setting, therefore making the way I set up my database incorrect! He set up another database in the tutorials I was going through, and I found out that as he did it. Thank you everyone for the effort to help me solve my problem!
Why you don't try receiving them with php?
And simply make
$email= $POST['email']
$password= $POST['password']
And change the query to
$query = "INSERT INTO `users` (`email`, `password`) VALUES(" .$email. ", ". $password.")";
I've got a problem with my PHP Registration Script that firstly checks, if the user exists.
It always outputs "false".
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$database = #mysql_connect("***********", "********", "******") or die("Can't connect to the server. Error: ".mysql_error());
//$username = mysql_real_escape_string($username);
$passwort = hash("sha256", $passwort);
$numrows = mysql_query("SELECT * FROM *******.mikgames WHERE username='".$username."' LIMIT 1");
$checkuserexists = mysql_num_rows($numrows);
if($checkuserexists==0) {
$abfrage = mysql_query("INSERT INTO *******.mikgames (username,passwort) VALUES ('$username', '$passwort')");
echo'true';
}
else {
echo'false';
}
?>
Edit: Now I'am using MySQLi and I've changed the code into this:
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$con = mysqli_connect('************','******','******') or die(mysqli_error());
mysqli_select_db($con, "*******") or die("cannot select DB");
$passwort = hash("sha256", $passwort);
$query = mysqli_query($con,"SELECT * FROM *******.mikgames WHERE username='".$username."'");
$result = mysqli_num_rows($query);
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames (username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
echo 'true';
}
else {
echo 'false';
}
?>
And it works.
You could go one step better and take an OOP approach using the PDO driver; PDO invokes security by allowing secure parameter binding and uses the SQL preferred functions.
Inside your pdo_driver.php file:
namespace ProjectName\App\Drivers;
if(!defined('IN_PROJECTNAME'))
{
die('No Script Kiddies Please...');
}
interface EntityContainer
{
public function query($statement, array $values = array());
}
class Entity extends \PDO implements EntityContainer
{
public function __construct(
$dsn = 'mysql:host=XXXX;dbname=XXXX', $user = 'XXXX', $pass = 'XXXX'
) {
try {
parent::__construct($dsn,$user,$pass);
} catch (PDOException $ex) {
die('FATAL ERROR: ' . $ex->getMessage());
}
}
public function query(
$statement, array $values = array()
) {
$smpt = parent::Prepare($statement);
(empty($values)) ? $smpt->execute() : $smpt->execute($values);
return $smpt;
}
}
Inside any other php file:
define('IN_PROJECTNAME', 0);
require_once dirname(__FILE__) . '/path/to/pdo_driver.php';
$container = array();
$container['Connection'] = new ProjectName\App\Drivers\Entity();
$username = $_GET['username'];
$passwort = $_GET['passwort'];
if(empty($container['Connection']->query('SELECT passwort FROM ******.mikgames WHERE username = ?', [$username])->fetch()['passwort'])) {
$container['Connection']->query('INSERT INTO ******.mikgames (username,passwort) VALUES (?, ?)', [$username,$passwort]);
}
Two Factors:
Firt Factor
You need to add an error output for debugging purposes:
$query = mysqli_query($con,"SELECT * FROM <tablename> WHERE
username='".$username."'") or die(mysqli_error($con));
I can't see a clear error with the information you have displayed here so far so you should also check what the value of $username acutally is and how closely it fits the value in the DB. Also read and take on board what the error output tells you.
Second Factor:
Your problem is you're running/articulating a query twice, here:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
You see $abfrage is a MySQL result object and you're then plugging it back into a MySQL query call, with the variable declaration $result. So your result is querying a query. This is an error.
What you probably want to do is use MySQLi_affected_rows to count how many rows have been inserted and run the appropriate IF clause:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_affected_rows($con);
echo 'true';
}
else {
echo 'false';
}
Use #mysql_***** for your ptoject.
$sql="SELECT * FROM table_name";
$result=#mysql_query($sql, $conn);
while ($name = # mysql_fetch_array($result)){
echo $name ['username'];
}
You just used simple mysql_***
I have a simple bit of code that I can't get working.
<?php
$mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
$username = 'Eddie';
$username = mysql_real_escape_string($username);
$email = 'eddie_the_eagle#hotmail.com';
$email = mysql_real_escape_string($email);
$sql = "INSERT INTO `users` (`username`, `email`)
VALUES ( '".$username."', '".$email."')";
$res = $mysqli_connection->query($sql);
}
?>
When I run the code no error appears but the users table remains empty.
Try This
<?php
$mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
if ($mysqli_connection->connect_error)
{
echo "Not connected, error: " . $mysqli_connection->connect_error;
}//Change
$username = 'Eddie';
$username = mysqli_real_escape_string($mysqli_connection,$username);//Change
$email = 'eddie_the_eagle#hotmail.com';
$email = mysqli_real_escape_string($mysqli_connection,$email); //Change
$sql = "INSERT INTO users (username, email) VALUES ( '".$username."', '".$email."')";
$res = $mysqli_connection->query($sql);
?>
You were mixing two API's mysql and mysqli. Stop using deprecated mysql
$username = mysqli_real_escape_string($mysqli_connection,$username);
$email = mysqli_real_escape_string($mysqli_connection,$email);
And you forgot to close your if condition too
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
}//<------forgot
There are two problems:-
you are mixing mysql_* with mysqli_*
no error checking is done.
Try like this:-
<?php
$mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
if ($mysqli_connection->connect_error)
{
echo "Not connected, error: " . $mysqli_connection->connect_error;
}//Change
$username = 'Eddie';
$username = mysqli_real_escape_string($mysqli_connection,$username);//connection link must be provided as a first parameter
$email = 'eddie_the_eagle#hotmail.com';
$email = mysqli_real_escape_string($mysqli_connection,$email); //same here
$sql = "INSERT INTO users (username, email) VALUES ( '".$username."', '".$email."')";
$res = $mysqli_connection->query($sql);
?>
Note:-Please habitat yourselves to use error reporting when you are going to do any stuff. thanks.
You forgot to close your if statement, so your insert logic will only run if there is an connect error.
Move the last } to a new line after
$mysqli_connection->connect_error;
I have PHP + AS3 user login®ister 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.
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']);