So I'm trying to check if an user exist before deleting it (if user exists, it will compare the passwords and then the user will be deleted), but I'm stuck in the comprobation of the user existing.
At beggining, I was making the user existing and password matching inside the isset($_REQUEST), but I thought making functions for these things will be cleaner and clearer for me (I was having problems making everything inside $_REQUEST). So I decided to make a function to check if an user exists in the database and I want it to be called inside my $_REQUEST(botonBaja) button.
What am I doing wrong?
I have this line at beggining, so $conexion is not out of scope:
<?php
include 'conexionBBDD.php';
function checkUserExist($nif){
$selectPass = "SELECT PASSWORD FROM votante WHERE NIF='".$nif."';";
$resultado= $conexion->query($selectPass);
if (mysqli_num_rows($resultado) == 0) {
return false;
}else return true;
}
The previous code is called by this isset($_REQUEST), which is a button (the button is working well). $nif and $password are being collected well, trust me, I've debugged it, it and it stops when it reaches the function.
if (isset($_REQUEST['botonBaja'])) { //DELETE USERS
$nif = $_REQUEST['nif'];
$password = $_REQUEST['password'];
if (checkUserExist($nif)){
echo "The user already exist";
}else echo "The user doesn't exist";
}
(Both codes are in the same php file)
Related
I have a change password script which is supposed to reset a users password with the values they provide assuming they match however this script is breaking something as users are not able to login with the password they provide to the script.
I'm not sure what is wrong as I also have an add_user script which is what I use to create the user accounts. The code to generate the password (hash) is the same and the data is successfully being put into the DB so I really don't know what is causing the problem. I'm guessing it has something to do with the data being provided prior to PHP hashing it thus in the DB it looks like it all went well as it's already hashed but I'm guessing if I was storing in plaintext it wouldn't be exactly the same as what the user entered otherwise the script would be working...
I've been working on the site all day so I'm really struggling to spot the error here.
I think my script used to work as this is the first I'm noticing the issue however I don't remember making any changes to this script in particular so cannot figure out why it would suddenly stop working.
session_start();
define('MyConst', TRUE);
include "includes/server.php";
if (!(isset($_SESSION['name']) && $_SESSION['name'] != ''))
{
header("location:login.php");
}
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die(mysqli_error($con));
$password1 = mysqli_real_escape_string($con, $_POST['newPassword']);
$password2 = mysqli_real_escape_string($con, $_POST['confirmPassword']);
$username = mysqli_real_escape_string($con, $_SESSION['name']);
$passwordhashed = password_hash("$password1", PASSWORD_DEFAULT);
if ($password1 <> $password2)
{
echo "your passwords do not match";
$referrer = $_SERVER['HTTP_REFERER'];
header ("Refresh: 2;URL='$referrer'");
}
else if (mysqli_query($con, "UPDATE accounts SET password='$passwordhashed' WHERE username='$username'"))
{
echo "You have successfully changed your password.";
$referrer = $_SERVER['HTTP_REFERER'];
header ("Refresh: 2;URL='$referrer'");
}
else
{
mysqli_error($con);
}
mysqli_close($con);
Expected to check that passwords match and echo "You have successfully changed your password" if the change was successful and then redirect.
The form page was missing a method as I had forgotten to add one in so it was defaulting to _GET when the rest of the script was referencing _POST.
Fix was simply adding method as post.
Iam new to php. I need to check whether newpassword(unicoded) variable is empty or null. If the value is a normal string, i could have checked as if($newpass){echo 'inside if'} but unforutnately, $newpassword value is getting a different value.
Below is the code: (which is already written by someone, i need to fix it)
if($newPassword != ""){
print_r('inside if');
$userdata["unicodePwd"] = $newPassword;
}
var_export($userdata);
I am sure there is something wrong in the code, but iam not able to fix it. Ultimately I should be able to check if $newPassword have some value, then it should go inside if. Sorry if its a dumb query.
if (isset($_POST['userpassword'])) {
// password sent from client
$userPassword = trim($_POST['userpassword']);
if ($userPassword !== '') {
// userPassword isn't empty, and spaces have been removed
$utf8Password = utf8_encode($userPassword);
}
}
$query = "SELECT username, email
FROM members
WHERE username = :username OR email = :email";
$stmt = $sql->prepare($query);
$stmt->execute(array(
':username' => $_POST['username'],
':email' => $email
));
$existing = $stmt->fetchObject();
if ($existing)
{
if ($existing->username == $_POST['username'])
{
$errors['username'] = "Username already in use !";
}
if ($existing->email == $email)
{
$errors['email'] = "Mail already in use !";
}
}
This is the part of register.php file. Not sure that just this part is responsible for the problem, but I suppose.
So, if table members is empty, and form is submitted - Firefox shows it's busy-gif about a half minute, but ends without registering new user, and without showing any error. Just keep freezing.
Then i press F5 - a window to approve resend information appears - click Resend - and the new user is registered.
If the tablemembersis not empty - everything works normally.
It seems - problem is because the code above is busy to find non-existing data.
If so, how to tell something like - if the table is empty - stop trying - just register the new user.
I'm pretty sure $existing = $stmt->fetchObject(); is fetching you an empty object, but one that does not implicitly evaluate to false. After that there's nothing in your code that would trigger, leading to your blank output.
Try a var_dump($existing) to see what your code is actually operating on.
edit
$existing = $stmt->fetchObject(); //this might be returning an empty object
if ($existing) { //empty objects evaluate to true
if ($existing->username == $_POST['username']) {
$errors['username'] = "Username already in use !";
} else if ($existing->email == $email) {
$errors['email'] = "Mail already in use !";
} else {
//this will trigger if something ELSE is wrong other than what you're explicitly checking for.
$errors['other'] = "Something else is wrong.\n" . var_export($existing, TRUE);
}
}
It should be noted that it is generally a bad idea from a security standpoint to confirm to a would-be attacker that a username or email address exists in your system. This presumably would give them half of the information needed to execute a dictionary attack on your login.
I would make the the username and email fields in your table have unique indexes, and just go straight to the insert. If the insert fails because one of the uniqueness constraints doesn't allow it, just give the user a generic message about not being able to register.
This will also happen to save you a lot of unnecessary queries against the database.
Should $email be $_POST['email']? And what is the full code - you don't have a closing if brace here. In that case, everything after would only execute if $existing is true. So the first time, nothing would be displayed. Also, it's better to use database constraints to ensure no duplicates like MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table
Hello I have a question. I have set up my login system with cookies and it works. But I wonder is there a more clean version of doing this.
<?
include('../config/db_config.php');
$username = $_COOKIE['user'];
$password = $_COOKIE['pass'];
$result = mysql_query("SELECT * FROM users WHERE isadmin = 1");
while($row = mysql_fetch_array($result))
{
if($username == $row['username'] && $password == $row['password'])
{
//User entered correct username and password
echo("ALLOW");
}
else
{
//User entered incorrect username and password
echo("DENY");
}
}
?>
You see I want all my content to be shown ONLY if I am logged in as admin. So what, now only way of doing this would be ECHO'ing out my HTML/PHP/Javascript instead of echoing ALLOW because if I just include("somepage.php") there that page would still be avialable for usage without logging in, and even if I do same check there I still would be ECHO'ing out everything.
Why are you loading every user, then comparing the username and the password? Wouldn't be easier to load a single user matching the username and the password?
Loading a single user will allow to remove the while().
In PHP, don't use mysql_query; do use PDO (if need, google for it to know why it's better).
Check your input (quite optional here, I agree).
Do never store passwords in plain text format.
You can probably do something like (I haven't used PHP/PDO for years, so the code may be inexact):
if (strlen($username)> 128)
{
// Something wrong. The username is too long.
}
$hash = sha1($password);
$sth = $dbh->prepare('if exists(select * from users where isadmin = 1 and username = :username and password = :password) select 1 else select 0');
$sth->bindParam(':username', $username, PDO::PARAM_STR, 128);
$sth->bindParam(':password', $hash, PDO::PARAM_STR, 40);
$sth->execute();
$isFound = $sth->fetchAll();
if ($isFound)
{
// User entered correct username and password.
echo 'ALLOW';
}
You could set a session variable on your login page (or any page that checks the login) that stores whether or not they're logged in and it will persist across pages. Then you can simple wrap your admin html in an if statement like so:
<?php
if ($_SESSION['isAdmin'] == true) {
?>
<p>My admin html</p>
<?php
} else {
?>
<p>My non-admin html</p>
<?php
}
?>
To save the info in a session, just add this to the part where you have echo("ALLOW");:
$_SESSION['isAdmin'] = true;
You'll also want to add session_start(); to the top of the script.
I would suggest that you do something like that only once, when the user first accesses the page, and then set a $_SESSION['is_admin'] or something for the rest of the time, so that you don't have to make an extra db call each page.
You could always put your "somepage.php" above the document root. This is a common way of preventing direct execution.
For example, if your webserver looks like 'project/public_html/index.php' put your admin-only include in 'project/somepage.php' then reference it using something like include("../somepage.php").
Obviously this will need adjustment according to the real paths you use.
i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner
First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}
Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? ยป Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>
Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.
It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.