Php throwing sqli count errors - javascript

<? php
include_once("connection.php");
// email and password sent from form
$email = $_POST['email'];
$password = $_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$sql = "SELECT * FROM users WHERE email='$email' and password='$password'";
$result = mysqli_query($connection, $sql);
// Mysql_num_row is counting table row
$count = mysqli_num_rows($connection, $result);
// If result matched $username and $password, table row must be 1 row
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['email'] = $email;
}
?>
<div id="openModal" class="modalDialog">
<div>
X
<form class="pop" method="post" action="login.php">
<p class="login">LOGIN</p>
<div class="form-group">
<div class="left-inner-addon "><i class="fa fa-envelope-o fa-fw"></i>
<input type="email" name="email" class="form-control" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<div class="left-inner-addon"><i class="fa fa-key fa-fw"></i>
<input type="password" name="password" class="form-control" id="password" placeholder="Password" required>
</div>
</div>
<p>Forgot Password?</p>
<div class="form-group">
<button class="btn btn-default" role="button" name="login" id="login">LOGIN</button>
</div>
</form>
</div>
</div>
<? php
$host = 'localhost';
$user = 'root';
$password = '';
$db = 'members';
$connection = mysqli_connect($host, $user, $password, $db);
if ($connection) {
echo "Connected Successfully";
} else {
echo "Error connecting: . mysqli_connect_error()";
}
?>
I have index.php, connection.php and login.php files. I have already created register.php for sign up it's working fine. In login.php, it is connected successfully but throwing an error in Warning: mysqli_num_rows() expects exactly 1 parameter, 2 given
One more thing I want to figure out how do I know if the users is login in my website I means I want to find out if it is stored to the database or I don't know as I'm new to SQL and after login there should valid or invalid email and password but not showing. In my database, I have created table the list of id, username, email, password. Please help in proper way and simple, don't confuse me.

The mysqli_num_rows() function returns the number of rows in a result set.
It accepts only one parameter say $result which is Required. $result is a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result(). You are passing the $connection object along with the $result which causes the issue.
For saving sessions in Database, reffer these posts
Storing Sessions in a Database
or
Saving PHP's Session data to a database

config.php
< ?php
$mysql_hostname = "hostname";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
Login.php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myemailid=addslashes($_POST['emailid']);
$mypassword=addslashes($_POST['password']);
$sql="SELECT id FROM admin WHERE username='$myemailid' and passcode='$mypassword'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
Session -> variables hold information about one single user, and are available to all pages in one application
if($count==1)
{
session_register("myusername");
$_SESSION['login_user']=$myusername;
header("location: welcome.php");
}
else
{
$error="Your Login Name or Password is invalid";
}
}
?>
Logout.php
< ?php
session_start();
if(session_destroy())
{
header("Location: login.php");
}
?>

Related

Ajax call for the Bootstrap Modal not working

I'm trying to make a simple Ajax call for a Bootstrap login modal. The main HTML code of the login Modal looks like this:
<form method="post" id="loginForm">
<div id="loginMessage"></div>
<div class="modal-footer">
<button type="button" class="btn btn-success mr-auto" data-target="#signupModal" data-toggle="modal" data-dismiss="modal">Register</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<input class="btn" name="login" type="submit" id="inputButton" value="Login">
</div>
</form>
In case the whole HTML code for the modal would help : https://jsfiddle.net/aslah/hykxLqd5/2/
The jQuery code looks like this:
$('#loginForm').submit(function(event){
//prevent default php processing
event.preventDefault();
//collect user inputs:
var datatopost = $(this).serializeArray();
//send the user data to login.php using AJAX
$.ajax({
url: "login.php",
type : "POST",
data : datatopost,
success : function(data){
if(data == 'success'){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
},
error : function(){
$('#loginMessage').html('<div class="alert alert-danger">There was an error with the AJAX call. Please, try again later!</div>');
}
});
});
This is my login.php code :
<?php
//starting the session
session_start();
//connecting to database
include('connection.php');
//check user inputs
// DEFINE ERROR MESSAGES //
$missingEmail = '<p><strong>Please enter your email address!</strong></p>';
$missingPassword = '<p><strong>Please enter a password!</strong></p>';
// $email = $_POST["loginEmail"]
// $password = $_POST["loginPassword"]
if(empty($_POST["loginEmail"])){
$error .= $missingEmail;
}else{
$email = filter_var($_POST["loginEmail"], FILTER_SANITIZE_EMAIL);
}
if(empty($_POST["loginPassword"])){
$error .= $missingPassword;
}else{
$password = filter_var($_POST["loginPassword"], FILTER_SANITIZE_STRING);
}
//If there are any ERRORS
if($error){
$resultMessage = '<div class="alert alert-danger">'. $error .'</div>' ;
echo $resultMessage ;
}else{
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
// $password = md5($password); no secure
$password = hash('sha256', $password);
//check if the user is registered by matching EMAIL & PASSWORD
$sql = "SELECT * FROM users WHERE email = '$email' AND password = '$password' AND activation='activated' ";
$result = mysqli_query($link, $sql);
//if any errors while running the query
if(!$result){
echo '<div class="alert alert-danger"> Error running the query!</div>';
exit;
}
//if login failed print ERROR
$count = mysqli_num_rows($result);
if($count !== 1){
echo '<div class="alert alert-danger">Wrong username or password</div>';
}else{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
//if remember me is not checked
if(empty($_POST['rememberme'])){
echo "success";
}else{
// if rememberme is checked
}
}
}
?>
On submit of the the Login button I want to redirect the user to the mainpage.php. I tried all the different fixes I found here but nothing worked. I can't figure out what I'm doing wrong. Any help is highly appreciated.
This is what I get when I submit the form
Aslah P Hussain
I have tested your code. The first thing that caught my attention is Notice about the undefined variable $error. Possibly you have defined it in include('connection.php'); but if not, this can cause problems with PHP output that you are expecting.
Additionally, if you are 100% sure that the console returns the message success - you can change your check in JavaScript to:
if(data.indexOf('success') >= 0){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
Possibly not the best solution to the problem, but at least will show you that redirect is working

how to grab input/select information and then print database information from there. Is this possible?

so no code I was just wondering if this was possible to do before I start it. So I'm going to make one php page. So no submit form with action to another php page.
On that page it will have the user type or select login information (id, pass, name etc). Below the login info I was grab the information from the above part to figure out which database they have access to and print the list of database they have access to in a html/php table.
So would this be possible to do in one page. Or do I need to make a form (to grab their information). And then from there print the list of database the user has access to. If it is possible how hard is it I'm pretty new to programming just finished HS. Will you guys be able to guide/point me in the right direction. Much help would be appreciated
you need to connect to db at top of page (or better in another file and require it)
so you can do sth like that
db.ph:
<?php
$host = '';
$dbuser = '';
$paswrd = '';
$dbname = '';
$dns = 'mysql:host=' . $host .'; dbname=' . $dbname;
try
{
$pdo = new PDO($dns, $dbuser, $paswrd);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "polaczono z mysql";
}
catch(PDOException $e)
{
// echo "nie udało się połączenie: " . $e->getMessage();
}
?>
next in login page you do:
require('db.php');
if(isset( $_POST['login']))
{
require('./config/db.php');
/*
$userName = $_POST['userName'];
$userEmail = $_POST['password'];
*/
$userName = filter_var( $_POST['userName'], FILTER_SANITIZE_STRING);
$userPassword = filter_var( $_POST['userPassword'], FILTER_SANITIZE_STRING);
$stmt = $pdo -> prepare('SELECT * FROM Users WHERE name =?');
$stmt -> execute([$userName]);
$user = $stmt ->fetch();}
and you can check if its correct for example if($user->password==$userPassword)
and in html:
<form action="login.php" method="POST">
<div class="form-group">
<label for="userName">Name</label>
<input required type="text" name="userName" ">
</div>
<div class="form-group">
<label for="userPassword">Password</label>
<input required type="password" name="userPassword"/>
</div>
<button name="login" type="submit" >Login</button>

PHP and JavaScript variable passing and security

I'm trying to make a notification system for my essay review website here is the basic flow of what should happen:
and here are my tables' structures(MySQL):
The problem I'm having is that I can't figure out how to update the status in the relations table securely once a user accepts or declines a review request. I could set the values of the accept/decline buttons to the id of the relationship and use ajax to update the status of that relationship, but that doesn't seem secure as a user could just change the value with inspect element.
Here is an example of what I have:
request.php
<?php
//define global variables
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbdatabase = "test";
$conn = new mysqli($dbhost, $dbusername, $dbpassword, $dbdatabase);
?>
Click here to go to user 43's notifications<br><br>
<!--Example requests-->
<form action="request.inc.php" method="post">
op_id: 43<br>
reviewer_id: 42<br>
essay_id: 34<br>
<input type="hidden" name="op_id" value="43">
<input type="hidden" name="reviewer_id" value="42">
<input type="hidden" name="essay_id" value="34">
<input type="submit" name="submit">
</form>
<form action="request.inc.php" method="post">
op_id: 43<br>
reviewer_id: 16<br>
essay_id: 135<br>
<input type="hidden" name="op_id" value="43">
<input type="hidden" name="reviewer_id" value="16">
<input type="hidden" name="essay_id" value="135">
<input type="submit" name="submit">
</form>
<form action="request.inc.php" method="post">
op_id: 78<br>
reviewer_id: 12<br>
essay_id: 25<br>
<input type="hidden" name="op_id" value="78">
<input type="hidden" name="reviewer_id" value="12">
<input type="hidden" name="essay_id" value="25">
<input type="submit" name="submit">
</form>
request.inc.php
<?php
//define global variables
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbdatabase = "test";
$conn = new mysqli($dbhost, $dbusername, $dbpassword, $dbdatabase);
$op = mysqli_real_escape_string($conn, $_POST['op_id']);
$reviewer = mysqli_real_escape_string($conn, $_POST['reviewer_id']);
$essay = mysqli_real_escape_string($conn, $_POST['essay_id']);
$sql = "INSERT INTO `reviewer_relations` (`reviewer_id`, `essay_id`, `status`)
VALUES ('$reviewer', '$essay', 0)";
$result=mysqli_query($conn, $sql);
if($result === TRUE){
$title = mysqli_real_escape_string($conn, $reviewer." has requested to review your essay: essay#".$essay.".");
$message = mysqli_real_escape_string($conn, '<button onclick="location.href=\'scripts/review_request.php?confirmation=accept\'" class="review-accept">Accept</button><button onclick="location.href=\'scripts/review_request.php?confirmation=decline\'" class="review-decline">Decline</button>');
$sql = "INSERT INTO `notifications` (`user_id`, `title`, `message`)
VALUES ('$op', '$title', '$message')";
$result=mysqli_query($conn, $sql);
if($result === TRUE){
echo 'notification and relation insert success';
}
else{
echo 'notification insert fail: '.mysqli_error($conn);
}
}
else{
echo 'relation insert fail: '.mysqli_error($conn);
}
?>
user43notifs.php
<?php
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbdatabase = "test";
$conn = new mysqli($dbhost, $dbusername, $dbpassword, $dbdatabase);
$sql="SELECT *
FROM notifications
WHERE user_id = 43";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
echo '**********************************************<br>';
echo $row['title'].'<br>';
echo $row['message'].'<br>';
}
?>
using these two table tables setup up with PHPMyAdmin:
reviewer_relations
notifications
I need a secure way to update the status column of the reviewer_relation that is represented by the notification when the user clicks on said notification's accept or decline button.
The problem is I can't figure out a way to associate the relationship id (or the reviewer_id and essay_id that describe the relationship) to it's notification without putting it directly into the notification's HTML where it's vulnerable to be changed.
I don't often ask questions, so any critique on how the question is titled, written, or stated is greatly appreciated. If any additional information is needed please ask. Thanks!
I believe I've found a solution:
I've added a token column to the user-essay relations table so that each request can be identified with a unique, cryptographically secure token (See Scott's updated answer here for token generating code).
Then when the notification is inserted into the notification table I set the value of the accept button as the token. That way when the notifications page is loaded the token can be retrieved by using .val() and used with ajax to update the status of the appropriate request. So, while a user could change the value of the button the chances of them guessing the 100-character-long token of another request is astronomically small.
Please let me know if this is not as secure as I think it to be.

PHP / Mysql : Register isn't creating new users in database

So I have two PHP files that are supposed to talk to eachother during User Registration.
The first: register.inc.php is supposed to create a new user in mysql database on MAMP and the second is register.php which is the basic form and is supposed to send it's data to register.inc.php. I am not receiving any errors in either files but it does not want to both: create the user and redirect to the register-success.php page.
Any idea what is going on?
register.inc.php:
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
//echo var_dump($_POST['username']);
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
// Sanitize and validate the data passed in
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg .= '<p class="error">The email address you entered is not valid</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
// Username validity and password validity have been checked client side.
// This should should be adequate as nobody gains any advantage from
// breaking these rules.
//
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
// check existing email
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this email address already exists
$error_msg .= '<p class="error">A user with this email address already exists.</p>';
$stmt->close();
}
$stmt->close();
} else {
$error_msg .= '<p class="error">Database error Line 39</p>';
$stmt->close();
}
// check existing username
$prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this username already exists
$error_msg .= '<p class="error">A user with this username already exists</p>';
$stmt->close();
}
$stmt->close();
} else {
$error_msg .= '<p class="error">Database error line 55</p>';
$stmt->close();
}
// TODO:
// We'll also have to account for the situation where the user doesn't have
// rights to do registration, by checking what type of user is attempting to
// perform the operation.
if (empty($error_msg)) {
// Create a random salt
//$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE)); // Did not work
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
// Create salted password
$password = hash('sha512', $password . $random_salt);
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
}
}
header('Location: ./register_success.php');
}
}
register.php:
<?php
include_once 'includes/register.inc.php';
include_once 'includes/functions.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Secure Login: Registration Form</title>
<script type="text/JavaScript" src="js/sha512.js"></script>
<script type="text/JavaScript" src="js/forms.js"></script>
<link rel="stylesheet" href="styles/main.css" />
</head>
<body>
<!-- Registration form to be output if the POST variables are not
set or if the registration script caused an error. -->
<h1>Register with us</h1>
<?php
if (!empty($error_msg)) {
echo $error_msg;
}
?>
<ul>
<li>Usernames may contain only digits, upper and lower case letters and underscores</li>
<li>Emails must have a valid email format</li>
<li>Passwords must be at least 6 characters long</li>
<li>Passwords must contain
<ul>
<li>At least one upper case letter (A..Z)</li>
<li>At least one lower case letter (a..z)</li>
<li>At least one number (0..9)</li>
</ul>
</li>
<li>Your password and confirmation must match exactly</li>
</ul>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>"
method="post"
name="registration_form">
Username: <input type='text'
name='username'
id='username' /><br>
Email: <input type="text" name="email" id="email" /><br>
Password: <input type="password"
name="password"
id="password"/><br>
Confirm password: <input type="password"
name="confirmpwd"
id="confirmpwd" /><br>
<input type="button"
value="Register"
onclick="return regformhash(this.form,
this.form.username,
this.form.email,
this.form.password,
this.form.confirmpwd);" />
</form>
<p>Return to the login page.</p>
</body>
</html>
You have this
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
But you do not have input in the form with name "p" -> $_POST['p']
so isset always return false
I suppose you wanted to type $_POST['password']
You just have to change the order of your db_connect and psl-config:
include_once 'psl-config.php';
include_once 'db_connect.php';

php: Form to change password and insert current password

I'm making a form at which if user wants to change their password, i made a code that could change password from database but I want to implement some function before changing password, current password would be asked so that they can change their password, But how to do it?
code to update database:
strong text
$result = mysqli_query($con,"SELECT * FROM admin");
if ($row = mysqli_fetch_array($result)) {
$id=$row['id'];
mysqli_query($con,"update admin set password=SHA1( CONCAT('Rajendra')) WHERE id='$id'");
}
echo "<h2>Your password is successfully changed..</h2>";
mysqli_close($con);
?>
here is a code for form:
<?php
include('lock.php');
?>
<form method="post" action="db_change_password.php">
<label><strong>Current password: </strong></label>
<input type="password" name="current_password" value="password"><br><br>
<label><strong>New password: </strong></label>
<input type="password" name="password" value="password"><br><br>
<label><strong>Confirm password: </strong></label>
<input type="password" name="confirm_password" value="password"><br><br>
<input type="submit" value="Submit">
<label><p><strong><br>NOTE: </strong>After changing password, you have to put your new password during login time.</p></label>
</form>
EDITING
login script:
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myemail=mysql_real_escape_string($_POST['email']);
$mypassword=mysql_real_escape_string($_POST['password']);
$sql="SELECT * FROM admin WHERE email='$myemail' AND password='".sha1($mypassword)."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myemail and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION["myemail"];
$_SESSION['login_user']=$myemail;
header("location: home.php");
}
else
{
header("location: invalid_login_form.php");
}
}
?>
I would however make a session with the user_id
$result = mysqli_query($con,"SELECT * FROM admin WHERE email = '".$_SESSION['email']."'");
if ($row = mysqli_fetch_array($result)) {
if(sha1($_POST['current_password']) == $row['password'])
{
$id=$row['id'];
mysqli_query($con,"update admin set password=SHA1( CONCAT('Rajendra')) WHERE id='$id'");
} else {
echo "incorrect password";
}
}
Just before updating the password, you can add a check to test the current password.

Categories

Resources