SQLite PDO - Data not inserted to database - php

sorry for my bad english, im new in php.
so I have a game server, I want to make players register through the website and save the data via the Accounts.db file
my database configuration
try {
# SQLite Database
$dbh = new PDO("sqlite:/home/samp/scriptfiles/Accounts.db");
}
catch(PDOException $e) {
echo $e->getMessage();
}
my php file
$error = '';
$success = '';
if (isset($_POST['submit'])){
global $dbh;
$username = $_POST['username'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$hashed = num_hash($password);
$checkusername = strpos($username, "_");
$sql = "SELECT COUNT(*) FROM `Accounts` WHERE `Username` = '$username'";
$checkexist = $dbh->query($sql);
if (!empty(trim($username)) && (!empty(trim($password)))){
//$recaptcha_secret = "6LcM1EYUAAAAAF1cINK71jkpRfoqlGec58r8bIkf";
//$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
//$response = json_decode($response, true);
//if($response["success"] === true) {
if ($checkusername) {
if ($password == $cpassword){
if ($checkexist->fetchColumn() == 0) {
$sql = "INSERT INTO `Accounts` (`Username`, `Password`) VALUES(?, ?)";
$insert->execute(array($username, $hashed));
if ($insert) {
$success = 'Berhasil melakukan registrasi.';
} else {
$error = 'Database error.';
}
} else {
$error = 'Username sudah digunakan.';
}
} else {
$error = 'Password yang anda masukan tidak sama.';
}
} else {
$error = 'Username akan digunakan sebagai Nama Karakter, gunakan format NamaDepan_NamaBelakang. Contoh: John_Smith';
}
//} else {
// $error= 'Apakah anda robot? Silahkan selesaikan captcha sebelum login';
//}
} else {
$error = 'You should input Username & Password!';
}
}
when I try to register on the website, it gives a successful notification but the data is not entered into the Accounts.db file. you can try it on my website
Thanks for your help

Related

localhost: data not going into database

i am trying to make a registration system but when i register the data isn't there.
i tried to search same questions but i couldn't find the issue, and the worst is that the script detect the database but wont get the data in.
The PHP script :
<?php
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
if(isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = sha1($_POST['pass']);
$pass2 = sha1($_POST['pass2']);
if(!empty($_POST['username']) AND !empty($_POST['email']) AND !empty($_POST['email2']) AND !empty($_POST['pass']) AND !empty($_POST['pass2'])) {
$usernamelength = strlen($username);
if($usernamelength <= 255) {
if($email == $email2) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$reqemail = $bdd->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
if($pass == $pass) {
$insertmbr = $bdd->prepare("INSERT INTO members(username, email, pass) VALUES(?, ?, ?)");
$insertmbr->execute(array($username, $email, $pass));
$error = "Your account has been created! Connect";
} else {
$error = "Your passs are not the same!";
}
} else {
$error = "Email already used!";
}
} else {
$error = "Your email is invalid!";
}
} else {
$error = "Your emails are not the same!";
}
} else {
$error = "Your username can't get upper than 255 characters!";
}
} else {
$error = "Every fields should be filled!";
}
}
?>

Multilevel Login in PHP

I have php code for login, it is worked if i input just username and password, but i need to check it with column hak_akses. For example if i login with hakakses = Dosen, the response says "Login Berhasil", if i login with hakakses = TU, the response says "Login Failed"
This is my code login php
<?php
$con = new mysqli("localhost","root","","komplain");
if($con->connect_error)
{
die("Connection Failed: " .$con->connect_error);
}
$response = array();
if(isset($_GET['apicall']))
{
switch ($_GET['apicall']) {
case 'signup':
# code...
break;
case 'login':
if(isParameterAvailable(array('username','password')))
{
$username = $_POST['username'];
$password = password_hash($_POST['password']);
$stmt = $con->prepare("SELECT id_user, username, email, no_telp FROM user WHERE username = ? AND password = ?");
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0)
{
$stmt->bind_result($id,$username,$email,$no_telp);
$stmt->fetch();
$user = array(
'id'=>$id,
'username'=>$username,
'email'=>$email,
'no_telp'=>$no_telp
);
$response['error'] = false;
$response['message'] = "Login Berhasil";
$response['user'] = $user;
}
else
{
$response['error'] = false;
$response['message'] = "Username / Password Salah";
}
}
break;
default:
$response['error'] = true;
$response['message'] = 'Invalid Operation Called';
}
}
else
{
$response['error'] = true;
$response['message'] = 'Invalid API call';
}
echo json_encode($response);
?>
This is my database
enter image description here
This is response from postman
enter image description here
My question is what should i do if i need to check login with hakakses(level user) ?
This code is just simulation, i am not using this code for my project, so i want to know how to login with multilevel user base on my code
Sorry for my English
Thank You
You should use password_hash() for PHP versions less than 5.5.
I'm using PHP 7.0 and I'm using hash() with a salt for extra security.
I'm first looking for the user inside the db based on username/email and then compare the password with the hashed entered password.
In that way you can show an invalid password error or even a user not found error.
$stmt = $con->prepare("SELECT id_user, username, email, no_telp, password, salt FROM user WHERE username = ? ");
$stmt->bind_param("ss",$username);
$stmt->execute();
$login_ok = false;
$row = $stmt->fetch();
if($row){
$check_password = hash('sha256', $row['password'] . $row['salt']);
if($check_password === $row['password']){
$login_ok = true;
}
else{
// invalid password
}
}
else {
// no user found
}
Based on $login_ok you can do stuff like showing errors
By creating a new user you should add the hashed password + the salt inside the db.
First generate a new salt:
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
And save the password into the db like this:
hash('sha256', $password . $salt)
Also don't forget to add the salt itself to the db.
Okay i find a solution. First i changed my code to this
<?php
$con = new mysqli("localhost","root","","tugas_akhir");
if($con->connect_error)
{
die("Connection Failed: " .$con->connect_error);
}
$response = array();
$username = $_POST['username'];
$password = $_POST['password'];
$login = mysqli_query($con,"SELECT * from user WHERE username='$username'and password='$password'");
$cek = mysqli_num_rows($login);
if ($cek > 0) {
while($data = mysqli_fetch_assoc($login))
{
$id = $data['id_user'];
$email = $data['email'];
$hak = $data['hak_akses'];
$no_telp = $data['no_telp'];
if ($data['hak_akses'] == "Dosen") {
$user = array(
'id_user'=>$id,
'username'=>$username,
'email'=>$email,
'hak_akses'=>$hak,
'no_telp'=>$no_telp);
$response['error'] = false;
$response['message'] ="Berhasil Login";
$response['user'] = $user;
}
else{
$response['error'] = true;
$response['message'] = "Tidak Mempunyai Akses";
}
}
}
else{
$response['error'] = true;
$response['message'] = "Username/Password Salah";
}
echo json_encode($response);
?>
I use mysqli_fetch_assoc() to retrieve data from database. And then i store data with $data
If user input is true, the message is Berhasil Login(Successful), else the message is Tidak Punya Akses(Access Denied) because i give statement if($data['hak_akses'] == "Dosen")

How to verify user password and echo user data as a json string?

I'm working on an android app, a java app, and i called for a response from a php file uploaded on my host, and my response is ' []', i checked the php code and i dont know what the problem is, i saw some posts it's an encode problem about which i dont know nothing, can you help me please , here's my php code.
<?php
require_once '../includes/DbConnect.php';
$response =array();
if($_POST['username'] && $_POST['password']){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username=?";
$stmt = mysqli_stmt_init($con);
mysqli_stmt_bind_param($stmt,"s",$username);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if($user = mysqli_fetch_assoc($result))
{
$passwordCheck = password_verify($password,$user['password']);
if($passwordCheck == false){
$response['error'] = true;
$response['message'] = "Invalid username or password";
}
else if($passwordCheck == true) {
$response['error'] = false;
$response['id'] = $user['idUsers'];
$response['email'] = $user['email'];
$response['username'] = $user['username'];
$response['country']= $user['country'];
$response['firstname']= $user['firstname'];
$response['lastname']= $user['lastname'];
$response['points']= $user['points'];
}
}
}
echo json_encode($response);
?>
My recommended adjustments:
<?php
require_once '../includes/DbConnect.php'; // <-- change from procedural to obj-oriented
$response['error'] = true; // default value
if (!isset($_POST['username'], $_POST['password'])) {
$response['message'] = "Invalid username or password";
} elseif (!$con) {
$response['message'] = "Database Connection Error: "; // for private debugging only: . $con->connect_error;
} elseif (!$stmt = $con->prepare("SELECT * FROM users WHERE username = ?")) {
$response['message'] = "Prepare Syntax Error"; // for private debugging only: . $con->error
} elseif (!$stmt->bind_param("s", $_POST['username']) || !$stmt->execute() || !$result = $stmt->get_result()) {
$response['message'] = "Statement Error"; // for private debugging only: . $stmt->error
} elseif (!$user = $result->fetch_assoc() || !password_verify($_POST['password'], $user['password'])) {
$response['message'] = "Invalid username or password";
} else {
$response['error'] = false;
$response['id'] = $user['idUsers'];
$response['email'] = $user['email'];
$response['username'] = $user['username'];
$response['country'] = $user['country'];
$response['firstname'] = $user['firstname'];
$response['lastname'] = $user['lastname'];
$response['points'] = $user['points'];
}
echo json_encode($response);

Checking sha1 against stored sha1 password

I'm hashing a password using sha1 and it is successfully storing it in the database, however i cannot seem to properly check to see if the sha1 matches one that is in the database. I've tried numerous different iterations of the below code, but nothing seems to work - what am i missing?
Registration
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$passwordEncrypted = sha1($password);
try {
$result = $db->prepare("INSERT INTO
user_info
SET
username = :user,
pass = :pass
");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $passwordEncrypted);
$result->execute();
}
catch (Exception $e) {
echo "Could not create username";
}
if (isset($_POST['submit'])) {
foreach ($_POST as $field) {
if (empty($field)) {
$fail = true;
}
else {
$continue = false;
}
}
if ($field == $fail) {
echo "You must enter a username and/or password";
}
else {
echo "Your account has been successfully created.";
}
}
?>
Logging in
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$encryptedPassword = sha1($password);
try {
$result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
if ($rows) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true;
include("inc/redirect.php");
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect (passwords are case sensitive)";
}
}
?>
You need to hash the password before querying the table, not afterwards:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$passwordEncrypted = sha1($password);
try {
$result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $passwordEncrypted);
$result->execute();
if ($result->fetch(PDO::FETCH_NUM)) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true;
include("inc/redirect.php");
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect (passwords are case sensitive)";
}
}
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
?>

No errors given and script isn't executed

As stated in the question before this, I have a registration system on my website and I am updating my mysql statements to PDO statements. I have updated all the statements and now the script runs through but it doesn't execute any of the script and doesn't give me any errors. It redirects me back to the registration.php page.
reg.php
<?php
include("sql.php");
require("includes/password.php");
session_start(); //Start session for writing
$errmsg = array(); //Array to store errors
$noterr = array();
$errflag = false; //Error flag
function UniqueID() {
include("sql.php");
$UID = rand(); //Create unique ID
$check = $db->prepare('SELECT * FROM `users` WHERE `UID` = :UID');
$UIDarray = array(
UID => $UID
);
$check->execute($UIDarray);
if($check->fetchColumn() > 0) { //Check if it exists
UniqueID(); //Redo the function
} else {
return $UID; //return the uniqueid
}
}
$UID = UniqueID(); //Unique ID
$username = ($_POST['username']); //Username
$email = $_POST['email']; //Email
password_hash($_POST['password'], PASSWORD_BCRYPT, array("cost" => 10)); //Password
password_hash($_POST['rpassword'], PASSWORD_BCRYPT, array("cost" => 10)); //Repeated Password
//Check Username
if($username == '') {
$errmsg[] = '<span style="color: red;">Where is your username?</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Password
if($password == '') {
$errmsg[] = '<span style="color: red;">Oops! No password!</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Repeated Password
if($rpassword == '') {
$errmsg[] = '<span style="color: red;">Your repeated password is missing!</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Make sure passwords match
if(strcmp($password, $rpassword) != 0 ) {
$errmsg[] = '<span style="color: red;">Passwords do not match</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Make sure username is availible
if($username != '') {
$qry = $db->prepare("SELECT * FROM `users` WHERE `Username` = :username"); //MySQL query
$params = array(
username => $username
);
$qry->execute($params);
if($qry->execute($params)) {
if($qry->fetchColumn() > 0) { //If username is in use
$errmsg[] = '<span style="color: red;">Sorry, that username is already in use</span>'; //Create error
$errflag = true; //Set flag so it says theres an error
}
$qry->closeCursor();
}
}
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
}
else
{
$errmsg[] = '<span style="color: red;">That is not what the picture displayed!</span>'; // Create error
$errflag = true; //Set flag so it says theres an error
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG'] = $errmsg; //Write errors
session_write_close(); //Close session
header("location: register.php"); //Rediect
exit(); //Block scripts
}
//Create INSERT query
$query = $db->prepare("INSERT INTO `userauthenticate`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES(:UID,:username,:email,:password)");
$params2 = array(
UID => $UID,
username => $username,
email => $email,
password => $password
);
$query->execute($params2);
//Check whether the query was successful or not
if($query->execute($params2)) {
header("Location: login.php");
exit();
} else {
die("There was an error, try again later");
}
?>
sql.php
<?php
ob_start();
session_start();
//database credentials
$dbhost = 'dbhost';
$dbuser = 'dbuser';
$dbpass = 'dbpass';
$dbname = 'dbname';
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
It might be worth adding some try/catch blocks to catch any errors if there are any
//Make sure username is availible
if($username != '') {
try {
$qry = $db->prepare("SELECT * FROM `users` WHERE `Username` = :username"); //MySQL query
$params = array(
username => $username
);
$result = $qry->execute($params);
if($result) {
if($qry->fetchColumn() > 0) { //If username is in use
$errmsg[] = '<span style="color: red;">Sorry, that username is already in use</span>'; //Create error
$errflag = true; //Set flag so it says theres an error
}
$qry->closeCursor();
}
}
catch(PDOException e) {
// write the error to the log
$errmsg = $e->getMessage();
error_log('$errmsg-> '.$errmsg);
echo $errmsg;
}
}
if(isset($_POST["captcha"]) && $_POST["captcha"] !="" && $_SESSION["code"] == $_POST["captcha"])
{
}
else
{
$errmsg[] = '<span style="color: red;">That is not what the picture displayed!</span>'; // Create error
$errflag = true; //Set flag so it says theres an error
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG'] = $errmsg; //Write errors
session_write_close(); //Close session
header("location: register.php"); //Rediect
exit(); //Block scripts
}
try {
//Create INSERT query
$query = $db->prepare("INSERT INTO `userauthenticate`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES (:UID,:username,:email,:password)");
$params2 = array(
UID => $UID,
username => $username,
email => $email,
password => $password
);
$result $query->execute($params2);
}
catch(PDOException e) {
// write the error to the log
$errmsg = $e->getMessage();
error_log('$errmsg-> '.$errmsg);
echo $errmsg;
}
//Check whether the query was successful or not
if($result) {
header("Location: login.php");
exit();
} else {
die("There was an error, try again later");
}
?>

Categories