php how to check if condition for unicode password - php

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);
}
}

Related

Using function inside $_REQUEST

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)

problem with registration and login php,will you check my code?if there is an error

I have a problem with either registration and login shows (undefined offset) and look at registration is there some problem with my code?it is the registration form the problem it sometimes saves the existing email in spite of the fact that I wrote a function for not submitting the existing email which is inside my data.txt. shortly the functions do not work properly
<?php
if(isset($_POST['submit_reg'])){
$var=file("data.txt");
$userData = $_POST['email'] . " " . $_POST['password'] . "\r\n";
$lines=0;
$db = fopen("data.txt", "a+");
foreach($var as $key=>$value){
$user = (explode(' ', $value));
if ($_POST["password"] === $_POST["confirm_password"]) {
//print_r($value);
if (trim($user[0]) == $_POST['email']) {
$lines++;
}
break;
}
}
if($lines){
echo "The email is already exists ";
}else{
fwrite($db,$userData."\r\n");
fclose($db);
echo "you are registered successfully ";
}
}
?>
and it is my login form the problem with login is it gives an error undefined offset 12
<?php
if (isset($_POST['submit_log'])) {
$email =isset($_POST['email']);
$password =isset($_POST['password']);
$file = explode( PHP_EOL, file_get_contents( "data.txt" ));
$auth = false;
foreach( $file as $line ) {
list($email, $password) = explode(" ", $line);
if ($_POST['email'] == $email && $_POST['password'] == $password) {
$auth =true;
break;
}
}
if($auth) {
echo "Login successfull!";
} else {
echo "Invalid username or password";
}
}
?>
Let me say first off, storing plaintext passwords in a .txt file is probably not the best way of building a longin system. (that's the disclaimer anyway).
Undefined offset (just a guess)
That said I see a few places to improve your code. My guess without more specifics about the error, is you may be pulling a empty array at the end of the file, it's typical to leave a hanging line return at the end (a new line with nothing else for the last line). Which may turn into something like this once you explode it for the second time on the space ['']. And then you try to access it using list which gives you undefined offsets.
You could use array_filter and maybe trim but instead of doing this:
$file = explode( PHP_EOL, file_get_contents( "data.txt" ));
You could try (which you should know as you use this function already)
$file = file( "data.txt", FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES ));
The file function, takes a file and breaks it into an array based on the line returns. So this takes the place of both explode and file_get_contents.
Then it has 2 (bitwise) flags which you could make use of:
array file ( string $filename [, int $flags = 0 [, resource $context ]] )
Reads an entire file into an array.
FILE_IGNORE_NEW_LINES
Omit newline at the end of each array element
FILE_SKIP_EMPTY_LINES
Skip empty lines
http://php.net/manual/en/function.file.php
These take the place of filtering the data for empty lines (something you weren't doing). Granted this is a file you created but you never know when a errant line return could creep in there.
Non-unique entries
if(isset($_POST['submit_reg'])){
$var=file("data.txt");
$userData = $_POST['email'] . " " . $_POST['password'] . "\r\n";
$lines=0;
$db = fopen("data.txt", "a+");
foreach($var as $key=>$value){
$user = (explode(' ', $value));
if ($_POST["password"] === $_POST["confirm_password"]) {
//NOTE: the uniqueness check only happens when the confirm password matches
if (trim($user[0]) == $_POST['email']) {
$lines++;
}
break;
}
}
if($lines){
echo "The email is already exists ";
}else{
//NOTE:yet you save it no matter if that is the case
fwrite($db,$userData."\r\n");
fclose($db);
echo "you are registered successfully ";
}
}
Your uniqueness check only works when the confirm password matches the password, however when it comes time to save the data, there is no check. Instead of just adding that check in around the saving bit, it would be better to wrap the whole thing inside this confirm test, as both pieces of that are known before touching the file:
Here I reworked this a bit for you
if(isset($_POST['submit_reg'])){
if ($_POST["password"] === $_POST["confirm_password"]) {
//VERIFY AND SANITIZE user input, if you put junk in you get junk out
$password = trim($_POST['password']);
//again use something better then die
if(empty($password))die('Password cannot be empty');
//because you split on space, you cannot allow it in inputs
if(preg_match('/\s+/', $password)) die('Password cannot contain spaces');
$email = trim($_POST['email']);
if(empty($email))die('Email cannot be empty');
//you may want to validate using something better
if(preg_match('/\s+/', $email )) die('Email cannot contain spaces');
//Use the flags
$var=file("data.txt", FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES);
//for duplication we only care if there is 1 previous entry
//which is enough to say its a duplicate
$exists=false;
foreach($var as $key=>$value){
$user = explode(' ', $value);
if (trim($user[0]) == $email) {
//we found a match this is enough to call it a duplicate
$exists = true;
break;
}
}
if($exists){
echo "The email is already exists ";
}else{
file_put_contants("data.txt", $email." ".$password.PHP_EOL, FILE_APPEND);
echo "you are registered successfully ";
}
}else{
echo "Confirm password must match password";
}
}
Other stuff
These are also incorrect:
$email =isset($_POST['email']);
$password =isset($_POST['password']);
Isset returns a boolean value, so you are assigning true or false to those two variables. This doesn't matter as you never check them and in your loop you overwrite with the call to list(). But just because someting "doesn't matter" doesn't mean it's correct.
These really should be something like this:
if(!isset($_POST['email']))
die("no email"); //dont use die but do some kind of error message
if(isset($_POST['password']))
die("no password"); //dont use die but do some kind of error message
SUMMERY
Really it's quite a mess. What I mean by this is you used 3 different ways to open and access the file data. You used the PHP line constant in some places but not all. You had code that was somewhat haphazardly thrown around, where you were setting things long before you need them, and in some cases you may not have needed them, so you were wasting resources setting them.
Please don't take the criticism hard, as I am not trying to offend. Simply pointing out places you could improve the flow of the code and simplify things. The big thing is don't get discouraged, in order to program effectively you have to have a no-quite attitude and the drive for continuous self improvement. Even after 9 years of PHP programing I still learn new things all the time, I learned (and wrote a library around it) something new just 2 days ago...
As I said at the beginning and to be honest a database would actually reduce the amount of code you need. It might be intimidating at first to use a database but you'll find that it's easier then doing this. An example is your check for uniqueness, you can set a field to be unique in the Database then you never need to worry about duplicates, only catching the errors for them.
I would suggest looking into PDO and prepared statements, password_hash and password_verify.
A final word of warning is I didn't test any of this so forgive me if there are any typos...
Hope it helps.

Header won't work with conditions

I have been trying to get a page working for a number of days now, and there doesn't seem to be much help from the "related" questions on this site.
I have made a signup.php page, which has a form for inputting user credentials to signup up for the site I am building, when the form is filled out and the user presses the 'submit' button, the form uses the action "signupsuccess.php" which has all of the php code for inserting the credentials into the database, and then redirects the user to the "Login.php" page.
My problem:
I have written code to say that if the user has not put in any data for one of the fields in the form, then they are brought back to the signup.php page by using this code:
<?php
if(!isset($_POST['fname'])&&($_POST['lname'])&&($_POST['email'])&&($_POST['pass'])){
header('Location:Signup.php');
exit;
}
else{
$host = "localhost";
$user = "******";
$password = "******";
$conn = mysql_connect($host, $user, $password);
$db = mysql_select_db('*****', $conn);
if(! get_magic_quotes_gpc() )
{
$fname = addslashes ($_POST['fname']);
$lname = addslashes ($_POST['lname']);
$email = addslashes($_POST['email']);
$pass = addslashes($_POST['pass']);
}
else
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass= $_POST['pass'];
}
$query = mysql_query("select * from users where pass='$pass' AND email='$email'", $conn);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$errors[] = 'That user already exists, try another email';
}else
{
$sql = "INSERT INTO users ".
"(fname,lname, pass, email) ".
"VALUES('$fname','$lname','$pass','$email')";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
}
mysql_close($conn);
?>
But the header() just won't bring the user back when they haven't put anything in to the fields. Is there anything I am doing obviously wrong or can anyone help me sort out the redirection of the user if they haven't entered anything.
Your if statement is incorrect. If you're just trying to check to see if those variables are set you need to call isset() on all of them.
You can do this with individual calls to isset() or all in one call.
if(!isset($_POST['fname'],$_POST['lname'],$_POST['email'],$_POST['pass'])){
header('Location:Signup.php');
exit;
}
FYI, you are wide open to SQL injections. addslashes() does not prevent SQL injections. Also, the mysql_* funcstions are obsolete and you should not be writing new code using them. Look into mysqli or PDO instead.
I don't think you really need a redirection, you probably should overcome this issue from the frontend, maybe a js validation could do the trick and is way simpler.
1.- change the action of submit to run the function "validate()"
2.- create the function that will be something like:
$(document).ready(function(){
function validate(){
if ($.trim($("#inputid").val()) == ""){
$(this).css('border', '2px solid red');
} else if ($.trim($("#inputid2").val()) == "") {
$(this).css('border', '2px solid red');
} else if ($.trim($("#inputid3").val()) == "") {
$(this).css('border', '2px solid red');
} else {
submit();
}
}
});
Where '#input?' is the selector for the input you want to validate and null is the value that you want to avoid, in this case, no value, just empty input. Then if all the inputs are filled it will execute submit() function which you should create to do whatever he has to.
Note: This kind of selectors are for jquery so you must include it in your code as well, put this in your header
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
Note 2: This is the frontend approach. I don't know if this is convenient but at least is an option and helps.
Good luck!
Your if statement was the problem. because the isset was only affecting
$_POST['fname'],
the if statment was being skipped so
header('Location:Signup.php')
was not being reached.
I like to put
echo 'test';
in my code while i am testing it and move it around the code. That way, if it is not echoing 'test', i know that the code isn't even being reached. That could have helped you in this case, showing you that the problem wasn't the header, it was the if statement. Also, consider using PDO for mysql connections. It is more secure against mysql injections.
Your condition (if corrected according to the previous answers) would still always result in the else case. Since you are checking for $_POST fields, those will always be present. isset()returns false if the variable is not set (but it is: it comes from your form) or is NULL (which it is not: it contains an empty value). So, isset() will return true fopr every field. What you need is, for each field: if (empty(trim($_POST['fname']))) || ... )empty() returns false when the variable is not set or empty (i.e NULL, an empty string, 0, 0.0, false, etc, see here: http://php.net/manual/en/function.empty.php)Plus, you need to do something about the deprecated mysql_functions and your vulnerability to attacks.

$_SESSION equals value from database?

when a person logs into my site i need to check a value in a database for their roleid, and dependent on that i need to allow/deny access to a page.
I have this code but it says that the $_SESION variable 'Access' is undefined, i cant see why?
$email = mysql_real_escape_string($_POST['email']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM person WHERE email = '" . $email . "' AND password2 = '" . $password . "'");
if (mysql_num_rows($checklogin) == 1) {
$row = mysql_fetch_array($checklogin);
$roleid = $row['roleid'];
$_SESSION['Email'] = $email;
$_SESSION['LoggedIn'] = 1;
$_SESSION['Access'] = $roleid;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo "<meta http-equiv='refresh' content='2;index.php' />";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
This is the if statement that is saying the session in undefined:
if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Email']) && $_SESSION['Access'] == '2')
EDIT
Sorry, should have mentioned, session_start() is called in my base.php file which is included in this file.
EDIT
I don't know what the problem is, i can assign the variable $email to the other session variable and display that so the user can see who they are logged in as?
Does anybody have any suggestions? Both of the other session variables work fine.
From the code you have posted, you are missing session_start()
If this is not within a framework that performs this for you, it must be called on every page that will utilize the session before any session calls are made.
I assume the error is occurring after the redirect, in your logic that is checking for it using isset() or empty(). Add session_start() to both pages before any session logic is performed.
EDIT:
Ok, you have session_start(). Can you print_r() your $_SESSION and check the output?
Also, the file you mention that runs the session start should be included in both files, as its necessary for setting and checking values from the session.
Make sure before running any empty() conditionals, you also run isset(). Empty does not check if the key is present.
EDIT AGAIN:
Is it possible your value for $y isn't coming out of the database as a single value? can you die() at that point, just printing the value of $y out to see what is output?
Just add another check to your if statement, !empty($_SESSION['Access'])
if (!empty($_SESSION['LoggedIn'])
&& !empty($_SESSION['Email'])
&& !empty($_SESSION['Access'])
&& $_SESSION['Access'] == '2')
Check the spelling of $row['roleid']. Is the field name in the database table EXACTLY like it ?
Change
SELECT * FROM person WHERE
to
SELECT roleid FROM person WHERE
see if it breaks... :-)
This might not be related to your problem but I think it's worth mentioning: Your username / password SQL statement can be dangerous. Although you escape the input variables it is usually better practice to do it this way:
$checklogin = mysql_query("SELECT * FROM person WHERE email='".$email."'");
$row = mysql_fetch_array ($checklogin, MYSQL_ASSOC);
if (mysql_num_rows ($checklogin) == 1 && $row['password'] == $password)
{
// you are logged in
}
else
{
// wrong email or password
}
Reason being is that your current statement only needs to return ANY row in your table whereas this statement needs to return one specific row in the table.

Error comparing hash to hashed mysql password (output values are equal)

Im trying to compare a hashed password value in a mysql database with the hashed value of an inputted password from a login form.
However, when I compare the two values it says they aren't equal. I removed the salt to simply, and then tested what the outputs were and got the same values
$password1 = $_POST['password'];
$hash = hash('sha256', $password1);
...connect to database, etc...
$query = "SELECT *
FROM users
WHERE username = '$username1'";
$result = mysql_query($query);
$userData = mysql_fetch_array($result);
if($hash != $userData['password']) //incorrect password
{
echo $hash."|".$userData['password'];
die();
}
...other code...
Sample output:
7816ee6a140526f02289471d87a7c4f9602d55c38303a0ba62dcd747a1f50361| 7816ee6a140526f02289471d87a7c4f9602d55c38303a0ba62dcd747a1f50361
Any thoughts?
I was having the exact same problem. var_dump() was telling me that I had two variables with the same properties, string(128). The only way I was able to get the comparison to work was to cast the hashed values as strings:
$password1 = $_POST['password'];
$hash = (string)hash('sha256', $password1);
...
$userData = (string)mysql_fetch_array($result);
if($hash == $userData) {
//This should return true.
}
Try using strcmp. String comparisons with == or != rarely go well.
if(strcmp($hash, $userData['password']) != 0) {
//this would be where the password was incorrect.
}
It may very well be treating it as a number for some reason and failing the comparison.
Try switching != to == and switch content. Like this
if($hash == $userData['password']) //incorrect password
{
//proc login...
}
else
{
echo $hash."|".$userData['password'];
die();
}
I'm not sure why is that happening but you can be sure it will work in my case
EDIT: you did something wrong in your case. works for me
== is an object hashcode comparison, you need to use a strcmp function to compare string literals.
Not sure if you ever got this solved but I just wasted 30 minutes with the exact same problem. Turns out my mysql value had an extra space at the end. It was a test user I manually added to the database and somehow got an extra space when copying and pasting the hashed password.
Not sure if this applies to your situation or not but I thought I'd share anyway.

Categories