I have a little problem. I have a register form. It works almost perfectly, I can check the value of the input fields, I can check weather do we have the same username in the db, but if everything is OK I cannot send the datas to my db. I use it as administrator/root, so I have the privileges. What is the problem? Please, help!
<?php
// declaring variables from input fields
$email = $_POST['email'];
$username=$_POST['username'];
$password=$_POST['password'];
$password2=$_POST['password2'];
function registration ($username, $email, $password) {
//new user registering
//return true or errormessage
//connecting to database, YEAH IT WORKS!
$connection = connecting_to_db();
//checking unique of username and IT WORKS!
$result = $connection->query("SELECT * FROM user WHERE username='".$username."'");
if (!$result) {
throw new Exception ('We couldnt query. Sorry.');
}
if ($result->num_rows>0) {
throw new Exception ('We have already this username! Choose something else!');
}
// if it is OK send it to the DB AND THIS IS NOT WORKING :-(
$result = $connection->query("INSERT INTO user VALUES'".$username."', shal('".$password."'), '".$email."')");
// I get alwasy this way and get this message.
if (!$result) {
throw new Exception ('We couldnt save your datas in our database. Try it later!');
}
return true;
}
?>
it looks like you have shal(letter L) instead of sha1(# one) in your insert query. print out your result from the query and you should see your issue.
Connect the database and the table then get the data
$servername = "localhost";
$username = "root";
$password = "";
Related
Somehow my conditional simply doesnt work. Once I click the button on my login form which is set to "post" and has the action defined as the below login script I only get directed to the script but not redirected as defined in my conditional statement. What is wrong with my code?
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$database = "project";
$connection = mysqli_connect($servername, $username, $password, $database) or exit(header("location:maintenance.php"));
function login_check() {
global $connection;
$name = $_POST['name'];
$password = $_POST['password'];
$prepared = mysqli_stmt_init($connection);
$request = mysqli_stmt_prepare($prepared, "SELECT id FROM members WHERE name = ? AND password = ?");
mysqli_stmt_bind_param($prepared, "ss", $name, $password);
$result= mysqli_stmt_bind_result($request);
$rows_counter = mysqli_num_rows($result);
mysqli_stmt_close($prepared);
if ($rows_counter > 0) {
$_SESSION['member'] = $name;
header("location:../../success.php");
}
else {
header("location:../../relogin.php");
}
}
Here is my input and approach to your code.
First of all before writing a solution and tell to much, it is always a good practice to make step by step code troubleshooting.
Before going and building a complete login system and put if statement or make prepare statement with inputs etc.
Make your solution in small working chops and put the puzzle together.
You question was focused on if statement and most of the help and answer was also focused on if statement which is nice, but the problem was not there.
I removed the if statement and a lot and just focused to see if I get some thing returned, I did not.
You $result= mysqli_stmt_bind_result($request); missed arguments, when that fixed, the next line missed also something else. I already there quit debugging.
I have rewrite your code and it works, what I did I have redefined the naming of variable so they are crystal clear to understand what is name, call it username, database username call it dbUser or dbUsername etc.
And if you want to check your code returning some thing or not, use var_dump($someVariable).
Last thing, before making a post form, you could create a dummy username and password in your database and inject that directly in your code like, just to see if every thing is working, and then move to your form:
$username = "user1";
$password = "1234";
The solution I did is just to demonstrate how to do it and not necessarily representation of the best logic, but it is up to you to find the correct logic and all depends on your strategy.
Here is my suggestion:
<?php
session_start();
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "product";
$connection = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
// Check connection
if ($connection->connect_error)
{
header("location:maintenance.php");
exit();
// or for debugging, activate following line
//die("Connection failed: " . $connection->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
//if username and password empty stop login
if (!$username || !$password)
{
//do something, die is only example
die ("Not all the fields were filled in");
} else
{
login_check($username, $password);
}
function login_check($username, $password)
{
global $connection;
//sql statements is corrected, change field name to username
$sql = "SELECT * FROM `members` WHERE `username` = ? AND `password` = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$output = $stmt->get_result();
$row = $output->fetch_array(MYSQLI_NUM);
$stmt->close();
//print what comes out in $row
//print_r($row);
//check if $row has data
if ($row)
{
echo "success do something";
$_SESSION['member'] = $username;
} else
{
echo "fail do something";
}
}
After defining the function login_check(), you should also call it (if the conditions are right):
function login_check() {
// your implementation as above
}
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
As a side note, it is good practice to also explicetely close the connection before redirecting.
Edit
as KhomeHoly comments, only call the function when necessary...
You need to call your functions if you define them. Not doing so is like building a room within a new house but forgetting the door. It's there, but nobody can use or access it.
So what you need to do is the following:
// your script as it is right now
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
With isset() you check if the certain $_POST parameters are set, but not validated. You should at least do a basic validation of the data to see if they are correct!
Something like this would work, depends on your requirements
if (isset($_POST['name']) && strlen($_POST['name') >= 4 && isset($_POST['password']) && strlen($_POST['password']) >= 4) {
login_check(); // actually call the function
}
The code above would check if those paramters are set and check if name and password are at least 4 characters long. (I wouldn't accept usernames lower than 4 chars personally, passwords should be at least 8 for me)
Now of course this misses an correct error reporting and all that stuff, but I think that should give you the basic idea based on your quesiton.
Always, always, always put exit() after header redirect call. Even in that case, it might solve your issue.
header("location:../../success.php");
exit();
Why?
I have a website that I need users to be able to login to. It is currently on a different server from the company's actual website. I would like to have a single login form that checks for a username and password in multiple databases on the same server.
Heres the setup.
1 Database has 2 different tables that I need to check for username and password.
the other database has 1 table that I need to check.
I will have a checkbox for 1 of the tables in the first database. So the form will have 3 field. (Username, Password, and "I am a reporter" checkbox)
I believe that it has something to do with the UNION sql command.
I don't know a LOT about sql but I am trying to learn as I go...
Here is the code so far.. also, I hope someone will tell me whether the information will be passed securely or not.
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['uname']) || empty($_POST['pswd'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$uname=$_POST['uname'];
$pswd=$_POST['pswd'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("company", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from dbo.contacts where WebPwd='$password' AND WebAcctName='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: "); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
It is not all complete yet and I am still researching but I am also trying to do this as quick as possible.
any help will be greatly appreciated!
It appears you make a connection declaring one name and then a different connection object name later.
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
$db = mysql_select_db("company", $connection);
I believe the later should use the same name $con and also at the end mysql_close($con);
First, you should use the mysqli_ or PDO API instead of mysql statements
If you need to use mysql, here is what to do:
$QueryReporter = mysql_query("SELECT * FROM $ReporterTable WHERE Username = '$Username' AND Password = '$Password'");
$QueryOthers = mysql_query("SELECT * FROM $UserTable WHERE Username ='$Username' AND Password = '$Password'");
if(mysql_num_rows($QueryReporter)==1){
//Its a reporter
}
else if(mysql_num_rows($QueryOthers)==1){
//Its not a reporter, but a user
}
else{
//Its no user or reporter, show error :)
}
EDIT:
If you are thinking about two different DB servers, you can use a function, then close the connection after the full query and return the result:
function CheckIfReporter($Username, $Password){
//DATABASE CONNECTION TO REPORTER DB
$Query = mysql_query("SELECT * FROM MyTable WHERE Username = '$Username' AND Password = '$Password'");
if(mysql_num_rows($Query)==1){
return TRUE;
}
//Else, no result:
else{
return FALSE;
}
//Close mysqlconnection:
mysql_close();
}
Now, make a similar function for user check,
if(CheckIfReporter($UsernameInput, $PasswordInput)==TRUE){
//Its a reporter
}
else if(CheckIfUser($UsernameInput, $PasswordInput)==TRUE){
//Its a user
}
else{
//Its none
}
I'm in the process of adding password hashing and SQL injection defenses into my Login system. Currently, I've ran into an error.
<?php
session_start(); //start the session for user profile page
define('DB_HOST','localhost');
define('DB_NAME','test'); //name of database
define('DB_USER','root'); //mysql user
define('DB_PASSWORD',''); //mysql password
$con = new PDO('mysql:host=localhost;dbname=test','root','');
function SignIn($con){
$user = $_POST['user']; //user input field from html
$pass = $_POST['pass']; //pass input field from html
if(isset($_POST['user'])){ //checking the 'user' name which is from Sign-in.html, is it empty or have some text
$query = $con->prepare("SELECT * FROM UserName where userName = :user") or die(mysqli_connect_error());
$query->bindParam(':user',$user);
$query->execute();
$username = $query->fetchColumn(1);
$pw = $query->fetchColumn(2);//hashed password in database
//check username and password
if($user==$username && password_verify($pass, $pw)) {
// $user and $pass are from POST
// $username and $pw are from the rows
//$_SESSION['userName'] = $row['pass'];
echo "Successfully logged in.";
}
else {
echo "Invalid.";
}
}
else{
echo "INVALID LOGIN";
}
}
if(isset($_POST['submit'])){
SignIn($con);
}
?>
In the above code, when I enter a valid username and password, the system prints out "Invalid". It could be a error in the password_verify() in the if statement(because if I remove it, I login successfully). I'm pretty sure I've done the preparing, binding and execution of the query properly? Does anyone know why it is doing this?
Thanks!
You're doing a SELECT *, and using fetchColumn, so the results are dependent of the returned columns order. You should either select the specific columns you need, or fetch the whole row as an associative array , and access it by column name.
There are other two issues that you should fix:
You shouldn't be using mysqli_connect_error() as you're using PDO. The right function would be $con->errorInfo().
You're defining some constants with the connection settings, yet you don't use them on the PDO() call, repeating the values instead.
Use
// it will be an array('name' => 'John', 'password_hash' => 'abcd')
// or FALSE if user not found
$storedUser = $query->fetch(PDO::FETCH_ASSOC);
instead of
$username = $query->fetchColumn(1);
$pw = $query->fetchColumn(2);
Because fetchColumn moves cursor of result. So first call extracts 1 column of first row, and second call will extract data from SECOND row!
I'm creating a login page where the user name and password are entered and then checked against the database to see if they match (I have posted on this previously but my code was completely incorrect so I had to start over) Upon clicking the submit button the user should be directed to the homepage (index.php) if the two values match up or an error message should appear stating "Invalid login. Please try again." Very simple basic stuff. Yet, I cannot get any variation to work.
Here is my code without the validation check. I believe this code is right but, if not, could someone please explain as to why. I am not asking anyone to write any code, just explain why it is not working properly.
<?php
function Password($UserName)
{
//database login
$dsn = 'mysql:host=XXX;dbname=XXX';
$username='*****';
$password='*****';
//variable for errors
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
//try to run code
try {
//object to open database
$db = new PDO($dsn,$username,$password, $options);
//check username against password
$SQL = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME");
$SQL->bindValue(':USER_NAME', $UserName);
$SQL->execute();
$username = $SQL->fetch();
if($username === false)
{
$Password = null;
}
else
{
$Password = $username['USER_PASSWORD'];
}
return $Password;
$SQL->closeCursor();
$db = null;
} catch(PDOException $e){
$error_message = $e->getMessage();
echo("<p>Database Error: $error_message</p>");
exit();
}
?>
Now the validation code. I've googled this and found several hundred ways to do so but this method most closely matches my coding style. It is incomplete and I would like some help as to how to finish it properly and then where to place it within the code above. My assumption is right after this comment: "//check username against password". Now I've seen this version twice and in one version the check is for txtUserName and the other is just username. I believe there should be else statements after each if statement to direct them to the index.php page. Also, the third if statement is the check to see if the password matches the username. No variation of this did I understand. They were far too complex.
function Login()
{
if(empty($_POST['txtUserName']))
{
$this->HandleError("UserName is empty!");
return false;
}
if(empty($_POST['txtPassword']))
{
$this->HandleError("Password is empty!");
return false;
}
$username = trim($_POST['txtUserName']);
$password = trim($_POST['txtPassword']);
if(!$this->($username,$password))
{
return false;
}
}
I know I am asking a lot here. But I am very new to PHP and am really trying hard to learn it. And there is way too much info out there and most of it is not for beginners. Any, and all, help would be greatly appreciated.
To begin with, let's assume that we have a PDO connection, just like you do already, for example with this function:
You can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(Exception $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
So that you can have a database connection like this:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
$db = connectToDataBase($host, $databaseName, $user, $pass);
So far we have the same stuff as you.
Now, I assume that we're on a PHP page where the user submitted his username and password, to begin with: check if we really received the username and the password, with the ternary oprator:
// receive parameters to log in with.
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
Now you can validate if those inputs were actually posted:
// Check if all required parameters are set and make sure
// that a user is not logged in already
if(isset($_SESSION['loggedIn']))
{
// You don't want an already logged in user to try to log in.
$alrLogged = "You're already logged in.";
$_SESSION['warningMessage'] = $alrLogged;
header("Location: ../index.php");
}
else if($userName && $password)
{
// Verify an user by the email address and password
// submitted to this page
verifyUser($userName, $password, $db);
}
else if($userName && (!($password)))
{
$noPass = "You didn't fill out your password.";
$_SESSION['warningMessage'] = $noPass;
header("Location: ../index.php");
}
else if((!$userName) && $password)
{
$noUserName = "You didn't fill out your user name.";
$_SESSION['warningMessage'] = $noUserName;
header("Location: ../index.php");
}
else if((!$userName) && (!($password)))
{
$neither = "You didn't fill out your user name nor did you fill out your password.";
$_SESSION['warningMessage'] = $neither;
header("Location: ../index.php");
}
else
{
$unknownError = "An unknown error occurred.". NL. "Try again or <a href='../sites/contact.php' title='Contact us' target='_blank'>contact us</a>.";
$_SESSION['warningMessage'] = $unknownError;
header("Location: ../index.php");
}
Now, let's assume that everything went well and you already have a database connection stored in the variable $db, then you can work with the function
verifyUser($userName, $password, $db);
Like already mentioned in the first else if statement:
// Usage: verifyUser($userName, $password, $db);
// Pre: $db has already been defined and is a reference
// to a PDO connection.
// $userName is of type string.
// $password is of type string.
// Post: $user exists and has been granted a session that declares
// the fact that he is logged in.
function verifyUser($userName, $password, $db)
{
$userExists = userExists($userName, $db); // Check if user exists with that username.
if(!($user))
{
// User not found.
// Create warning message.
$notFound= "User not found.";
$_SESSION['warningMessage'] = $notFound;
header("Location: ../index.php");
}
else
{
// The user exists, here you can use your smart function which receives
// the hash of the password of the user:
$passwordHash = Password($UserName);
// If you have PHPass, an awesome hashing library for PHP
// http://www.openwall.com/phpass/
// Then you can do this:
$passwordMatch = PHPhassMatch($passwordHash , $password);
// Or you can just create a basic functions which does the same;
// Receive 1 parameter which is a hashed password, one which is not hashed,
// so you hash the second one and check if the hashes match.
if($passwordMatch)
{
// The user exists and he entered the correct password.
$_SESSION['isLoggedIn'] = true;
header("Location: ../index.php");
// Whatever more you want to do.
}
else
{
// Password incorrect.
// Create warning message.
$wrongPass = "Username or password incorrect."; // Don't give to much info.
$_SESSION['warningMessage'] = $wrongPass;
header("Location: ../index.php");
}
}
}
And the function userExists($userName, $db) can be like:
function userExists($userName, $db)
{
$stmt = $db->prepare("SELECT * FROM users WHERE USER_NAME = :USER_NAME;");
$stmt->execute(array(":USER_NAME "=>$userName));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
// User exists.
return true;
}
// User doesn't exist.
return false;
}
Where the function Password is like:
function Password($UserName)
{
$stmt = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME;");
$stmt->execute(array(":USER_NAME"=>UserName));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['USER_PASSWORD'];
}
// No result.
return false;
}
Again, make sure you're not matching plain text passwords, or basic shai1, md5 encryptiones etc. I really recommend that you take a look at PHPass.
I hope I'm making myself clear.
I'm trying to look up user's username using $_GET but not actually seing the result of the query. Here's the code:
<?php
$host = "localhost";
$username = "root";
$password = "toor"; // :)
$database = "db";
$link = mysql_connect($host, $username, $password);
if(!$link){
exit('Could not connect to database: '. mysql_error());
}
$email = mysql_real_escape_string(htmlspecialchars(stripslashes($_GET["e"])));
$query = "SELECT username FROM cc_card WHERE email = '$email'";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$user = mysql_fetch_assoc($result);
echo $user['username'];
} else {
echo "Something's wrong";
}
it's only returnung "Something's wrong". I wanted it to display the username field of the cc_card table where email = email. What am I doing wrong?
If you're getting "Something's wrong" from the posted code it means nowhere in the cc_card table does the email column match the email value you specify in your query.
You need to verify that the contents of your sanitized $email variable do, in fact, exist somewhere in the table. Try:
} else {
echo "Something's wrong";
var_dump($email);
}
To see the contents of the sanitized $email variable and manually query the database from the shell (or phpmyadmin or whatever) to find whether the value you're specifying exists or not. I'm betting it doesn't exist.
You'd better add the error check after the query.
if (!$result) {
die('Error: ' . mysql_error());
}
If no error, then it means there is no matched email in your database.