I want to save my password in encrypted formatting, so, I saved my password using base64_encode in table, For login when i used to fetch my password again in decode format, using base64_decode, it returns blank data, please help me for better solution.
Here is my code.
login_admin.php
<?php
include('connection.php');
if(isset($_POST['submit'])){
$email = $_POST['email'];
$password = decryptIt($_POST['pwd']);
print_r($password); die;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$admin= $_SESSION['email'];
$query = "SELECT * FROM `user` Where (email = '$email' && role_id = 'admin' )";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if($row > 0){
if($admin == $row['email'] && $password == $row['password']){
header('location:dashboard1.php');
}
}
}
else{
echo "Login Failed";
}
?>
connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "example_user";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function encryptIt( $q ) {
$cryptKey = 'qJB0rGtIn5UB1xG03efyCp';
return base64_encode( base64_encode($q).'+'.$cryptKey );
}
function decryptIt( $q ) {
$cryptKey = '+qJB0rGtIn5UB1xG03efyCp';
return base64_decode(str_replace($cryptKey, "",base64_decode( $q ))) ;
}
?>
Code seems fine, try to put check in the "decryptIt" method for empty value in parameter.
function decryptIt( $q ) {
if($q==''){
return array('error'=>1,"msg"=>"parameter cant be empyt")
}else{
$cryptKey = '+qJB0rGtIn5UB1xG03efyCp';
return array('success'=>1,"decrypt"=>base64_decode(str_replace($cryptKey, "",base64_decode( $q ))))
}}
Related
here am trying to get username and password from the database and if their result is found then redirect to some page but mysqli_num_rows returns 0 always i dunno why `
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `login` WHERE username = '$username' AND password = '$password'";
$run = mysqli_query($con,$query);
if (mysqli_num_rows($run) == 1) {
header("location: login.php");
}}?>
`
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ornament"; // My local DB Name
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$username = "test"; // $_POST["username"] value
$password = "test"; // $_POST["password"] value
$sql = "SELECT * FROM `ornament` WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
echo "correct";
} else {
echo "wrong";
}
mysqli_close($conn);
?>
</body>
</html>
OUTPUT:
correct
I have a database name and table name are same, But for me it's working fine.
NOTE: Please check the whether you are using correct password while getting from POST.
Any how you got a solution, Have a great day
Thanks
Muthu
So I made a function that checks if the data that the user enters is already in my database of users. The function works in a testing environment (but runs on open of the page). For some reason it assigns the user input to the $username function regardless of the outcome of the query. I think I may have to AJAX it but I don't know how.
<?php
function checkIfEntered($data, $conn)
{
$query = "SELECT * FROM users
WHERE username= '" . $data . "'";
if ($result = mysqli_query($conn, $query)) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
/* close result set */
mysqli_free_result($result);
}
if (($row_cnt) >= 1)
{
return TRUE;
}
if (($row_cnt) == 0)
{
return FALSE;
}
}
error_reporting(E_ALL);
ini_set('display_errors',1);
// define variables and set to empty values
$servername = "localhost"; $username = "root";
$password = "root";
$dbname = "MyDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = '';
$emailErr = '';
$usernameErr = '';
$UserPasswordErr = '';
$username = '';
$UserPassword = '';
$confirm = '';
$confirmErr = '';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{
$usernameErr = "username is required";
}
else
{
if (checkIfEntered($username, $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
}
else
{
$username = test_input($_POST["username"]);
}
}
You are not even calling the "checkIfEntered" function. Instead, you are calling "isEnteredUsername" function, which I don't see it here. So the code is always going in else and assigning the POST value to $username.
I am not sure why you think AJAXing it will solve the problem, but you can use AJAX call on document ready or some event like this $.ajax({ ... }) as explained here.
http://api.jquery.com/jquery.ajax/
you are forgot return num of record this function "checkIfEntered"
<?php
function checkIfEntered($data, $conn)
{
$query = "SELECT * FROM users
WHERE username= '" . $data . "'";
if ($result = mysqli_query($conn, $query)) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
/* close result set */
mysqli_free_result($result);
return $row_cnt;
}
if (($row_cnt) >= 1)
{
return TRUE;
}
if (($row_cnt) == 0)
{
return FALSE;
}
}
error_reporting(E_ALL);
ini_set('display_errors',1);
// define variables and set to empty values
$servername = "localhost"; $username = "root";
$password = "root";
$dbname = "MyDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = '';
$emailErr = '';
$usernameErr = '';
$UserPasswordErr = '';
$username = '';
$UserPassword = '';
$confirm = '';
$confirmErr = '';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{
$usernameErr = "username is required";
}
else
{
if (checkIfEntered(test_input($_POST["username"]), $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
}
else
{
$username = test_input($_POST["username"]);
}
}
?>
The Problem with this code is the function checkIfEntered() is coming up false because when you pass the $username parameter it has not been assigned. so it is coming up as false.
Code:
if (checkIfEntered(test_input($_POST["username"]), $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
}
else
{
$username = test_input($_POST["username"]);
}
Correction
$username = test_input($_POST["username"]);
if (checkIfEntered(test_input($_POST["username"]), $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
$username = '';
//set username back to nothing to avoid more errors.
}
else
{
$username = test_input($_POST["username"]);
}
Its a simple registration with username and password, but when I try to insert it to the database it always fails and I don't know why, can someone help me with this?
include "db.php";
if (isset($_POST['submit']))
{
$username= $_POST['leguser'] ;
$password= $_POST['legpass'] ;
$pwhash = password_hash($password, PASSWORD_DEFAULT) ;
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
echo var_dump ($username);
echo var_dump ($password);
echo var_dump ($pwhash);
$sql = "SELECT * FROM tbl_users WHERE fld_username = '$username'";
$result = $conn->query($sql);
if ($result->num_rows === 1) {
echo "<script>alert('Username already used!');</script>"; }
else
{
$q = "INSERT INTO `tbl_users` (`fld_username`) VALUES ('$username')";
$result = mysql_query($q);
if ($result) {
echo 'success';
} else {
echo 'failure';
}
}
This is the code of the database connection (db.php)
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'rsi_db';
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
By the way I only want to input only one data on the database which is the username, for me not to get complicated with every data that I want to put in the future.
So I am trying to compare user input from a form with data from a database, first name, last name, and email. My problem has been comparing my results with the ones that the user put in. What I am trying to do is put the results from my query into an array and then compare each array item against the input of the user. Yet I can't get through my process. What am I doing wrong?
Thank you all in advance.
P.S. I am a php newbie so any suggestions would also be appreciated
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user
$firstname = $_POST['first'];
$lastname = $_POST['last'];
$email = $_POST['email'];
//query for the database to select the columns
$queryFirst = "SELECT firstname FROM users";
$queryLast = "SELECT lastname FROM users";
$queryEmail = "SELECT email FROM users";
//query results
$resultFirst = $conn -> query($queryFirst);
$resultLast = $conn -> query($queryLast);
$resultEmail = $conn -> query($queryEmail);
$firstResult = array();
$lastResult = array();
$emailResult = array();
array_push($firstResult, $resultFirst);
array_push($lastResult, $resultLast);
array_push($emailResult, $resultEmail);
$firstValid = mysqli_result::fetch_array($firstResult);
$lastValid = mysqli_result::fetch_array($lastResult);
$emailValid = mysqli_result::fetch_array($emailResult);
//comparing query results to user input
foreach($firstResult as $comp) {
if(strpos($firstname, $comp) !== false) {
$firstname = true;
} else {
return false;
}
}
foreach($lastResult as $comp) {
if(strpos($lastname, $comp) !== false) {
$lastname = true;
} else {
return false;
}
}
foreach($emailResult as $comp) {
if(strpos($email, $comp) !== false) {
$email = true;
} else {
return false;
}
}
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($firstname && $lastname && $email = true) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Okay so first thing as already told you andrewsi, you can get all the info in one query. But if you want to select only one row, you should use a WHERE clause telling what to look for.
Check this:
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user . addslashes is for security, so they won't break your query and potentially abuse it.
$firstname = addslashes($_POST['first']);
$lastname = addslashes($_POST['last']);
$email = addslashes($_POST['email']);
//query for the database to select the columns
$query = "SELECT firstname, lastname, email FROM users WHERE firstname = '$firstname' and lastname = '$lastname' and email = '$email'";
//query results
$result = $conn -> query($query);
$numRows = $result->num_rows;
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($numRows > 0) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Haven't tested it but the idea is to check for a match in the query, not afterwards. Then if there's a match, it will return at least one row (if you defined your table correctly it shouldn't be possible to have duplicates).
Then based on that you make your choice.
I have a function which authenticates user for login.
$login_query = mysqli_query($GLOBALS['conn'],
"SELECT COUNT(`user_id`) as `count`,`user_id` FROM `users`
WHERE `user_email`='$email' AND `user_password` = '" . md5($password) . "'") or die(mysqli_error($GLOBALS['conn']));
return ($mysqli_result->num_rows == 1) ?
mysqli_result($login_query, 0, 'user_id') : false;
I was using mysql_* and now switching to mysqli_*.
What I want to know is that, in return statement how do I return user_id from the row that has been selected from DB?
I've simplified the query a little. This function will return the user_id if the login is successful or "0" if not.
Make the $mysqli connection in a config file that you can include at the top of each page
#config.php#
$dbhost = "localhost";
$dbuser = "";
$dbpassword = "";
$dbdatabase = "";
$salt = "";
$mysqli = mysqli_connect($dbhost,$dbuser,$dbpassword,$dbdatabase);
if (mysqli_connect_errno())
{
echo '<p>There was a problem with the mysqli connection:
<br> '.mysqli_connect_error().'</p>';
exit;
}
#Calling the function:#
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
checklogin($email, $password, $salt, $mysqli);
function checklogin($email, $password, $salt="", $mysqli)
{
$email = $mysqli->real_escape_string($email);
$password = $mysqli->real_escape_string($password);
$login_query = '
SELECT *
FROM
`users`
WHERE
`user_email`='$email'
AND
`user_password` = "' . md5($salt.$password) . '";';
$result = $mysqli->query($login_query)
$row = $result->fetch_array();
if ($result->num_rows > 0)
{$user_id = $row['user_id'];}
else
{$user_id = 0;}
return $user_ID
}