How can I get a string from a function - php

So, this is my code:
class Functions{
public static function login($email,$password){
$email = $_GET['email'];
$password = $_GET['password'];
if(isset($_GET['submit']) AND isset($email) AND isset($password)){
$password = md5($password);
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$_SESSION['nume'] = $row["name"];
$_SESSION['uid'] = $row["id"];
$_SESSION['admin'] = $row["admin"];
$_SESSION['email'] = $row["email"];
$_SESSION['points'] = $row["points"];
}else{
$errortxt = "Invalid Login Credentials";
$error = true;
}
}
return $error;
}
}
In my HTML file I'm calling for the function like this:
Function::login($email,$password);
But I'm wondering how can I get the $errortxt string to echo in the HTML file.
Thanks!

You just need a simple fix:
class Functions{
public static function login($email,$password){
$response['error'] = false;
$response['errortxt'] = "";
$email = $_GET['email'];
$password = $_GET['password'];
if(isset($_GET['submit']) AND isset($email) AND isset($password)){
$password = md5($password);
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$_SESSION['nume'] = $row["name"];
$_SESSION['uid'] = $row["id"];
$_SESSION['admin'] = $row["admin"];
$_SESSION['email'] = $row["email"];
$_SESSION['points'] = $row["points"];
}else{
$response['error'] = true;
$response['errortxt'] = "Invalid Login Credentials";
}
}
return $response;
}
}
And you need to call it this way:
$fnCallStatus = Function::login($email,$password); //Now you have the response;
if($fnCallStatus['error']) //we have an error
{
echo $fnCallStatus['errortxt']; //we print the message
}

Hi I fixed little bit your code because it lacks good coding principles and good taste (calling superglobal $_GET variable will always get you something after request despite you place something else into function parameters).
class Functions{
public static function login($email,$password)
{
$error['is'] = true;
$email = htmlspecialchars($email);
$password = md5(htmlspecialchars($password));
if(!empty($email) AND !empty($password))
{
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
$row = $result->fetch_assoc();
$_SESSION['nume'] = $row["name"];
$_SESSION['uid'] = $row["id"];
$_SESSION['admin'] = $row["admin"];
$_SESSION['email'] = $row["email"];
$_SESSION['points'] = $row["points"];
} else {
$error['mismatch'] = "Email or password does not match.";
return $error;
}
} else {
$error['empty'] = "Please fill all login fields. Thank you";
return $error;
}
}
}
$error = Function::login($_GET['email'],$_GET['password']);
if($error['is'])
{
if ($error['mismatch']) {
echo $error['mismatch'];
} elseif ($error['empty']) {
echo $error['empty']
}
}
Your function also always return $error despite none occurred. I fixed that and function return error only in not query case.
Functions can return arrays. So if you need to set multiple fields with different text, you can place into array anything you like. This solution is more buletproof.

Related

having problems with removing sha1 encryption from my code

ill like to remove the sha1 encryption on this code so i can store my password as typed in the database instead of the encrypted code. Am new to coding so I need help
The code (settings_model.php)
<?php
$settings = new Datasettings();
if(isset($_GET['q'])){
$settings->$_GET['q']();
}
class Datasettings {
function __construct(){
if(!isset($_SESSION['id'])){
header('location:../../');
}
}
function changepassword(){
include('../../config.php');
$username = $_GET['username'];
$password = $_GET['password'];
$current = sha1($_POST['current']);
$new = sha1($_POST['new']);
$confirm = sha1($_POST['confirm']);
$q = "select * from userdata where username='$username' and password='$current'";
$r = mysqli_query($db,$q);
if(mysqli_num_rows($r) > 0){
if($new == $confirm){
$r2 = mysqli_query($db,"update userdata set password='$new' where username='$username' and password='$current'");
header('location:../settings.php?msg=success&username='.$username.'');
}else{
header('location:../settings.php?msg=error&username='.$username.'');
}
}else{
header('location:../settings.php?msg=error&username='.$username.'');
}
}
function addaccount(){
include('../../config.php');
$level = $_GET['level'];
$id = $_GET['id'];
$q = "select * from $level where id=$id";
$r = mysqli_query($db,$q);
$row = mysqli_fetch_array($r);
if($level == 'student'){
$username = $row['studid'];
$fname = $row['fname'];
$lname = $row['lname'];
$password = sha1($username.'-'.$fname);
}else{
$username = $row['teachid'];
$fname = $row['fname'];
$lname = $row['lname'];
$password = sha1($username.'-'.$fname);
}
$verify = $this->verifyusername($username);
if($verify){
$q2 = "insert into userdata values(null,'$username','$password','$fname','$lname','$level')";
mysqli_query($db,$q2);
header('location:../'.$level.'list.php?r=added an account');
}else{
header('location:../'.$level.'list.php?r=updated');
}
}
function verifyusername($user){
$q = "select * from userdata where username='$user'";
$r = mysql_query($q);
if(mysql_num_rows($r) < 1){
return true;
}else{
return false;
}
}
function getuser($search){
include('../config1.php');
$user = $_SESSION['id'];
$q = "select * from userdata where username !='$user' and username like '%$search%' order by lname asc";
$r = mysqli_query($db, $q);
return $r;
}
function addaccounts(){
include('../../config1.php');
extract($_POST);
$q = "select * from $level where id=$id";
$r = mysqli_query($db,$q);
$row = mysqli_fetch_array($r);
if($level == 'student'){
$username = $row['studid'];
$fname = $row['fname'];
$lname = $row['lname'];
$password = sha1($username.'-'.$fname);
}else{
$username = $row['teachid'];
$fname = $row['fname'];
$lname = $row['lname'];
$password = sha1($username.'-'.$fname);
}
$verify = $this->verifyusername($username);
if($verify){
$q2 = "insert into userdata values(null,'$username','$password','$fname','$lname','$level')";
mysqli_query($db,$q2);
header('location:../'.$level.'list.php?r=added an account');
}else{
header('location:../'.$level.'list.php?r=updated');
}
}
}
?>
please help need an answer soon. thanks.
just change this line
$confirm = sha1($_POST['confirm']);
to this
$confirm = $_POST['confirm'];

returning values from within functions

I have defined a function to check user credentials and would like it to return true if the auth passed and false if it failed. my function is defined as follows:
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
return $logged_in;
}
the problem I am running into is this, when I call the function and try to use what should be the returned value I get an error that the variable is not defined.
_userLogin($username, $password);
if ($logged_in == True){
'do something';
} else {
'do something else'
}
what am I doing wrong?
You are trying to use the variable $logged_in that is defined in function _userLogin outside the block. Assign the return value that is returned by the function like,
$logged_in = _userLogin($username, $password)
if ($logged_in == True){
'do something';
} else {
'do something else'
}
Also you will always receive TRUE because you are accessing variables $salt, $password outside the if block where they are being retrieved thus the fields not being assigned properly.
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in = false;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
$dbpass = '';
$salt = '';
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
}
}
return $logged_in;
}
PLEASE NOTE: I did not perform any logic checks other than fix your syntax
Replace your branching (where you use the function) with the simpler:
if( _userLogin($username, $password) ){
//success
}else{
//failure
}

Login form validation always says WRONG USER DETAILS

This php code for login form validation. Why it always returns 'Wrong user data' (Грешни данни!). $name & $pass1 come from the login form which is in other file.
$activated has values 0 || 1 and it is to see if user confirmed registration from email.
<?php
//connection with database
require "db_connect.php";
require "password_compat-master/lib/password.php";
$name = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'name'))));
$pass1 = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'pass1'))));
$errorName = '';
$errorPass1 = '';
$feedback = '';
$mainError = false;
//get hash
$retHash = "SELECT password FROM users WHERE user_name='$name'";
$query_retHash = mysqli_query($conn, $retHash);
$row = mysqli_fetch_array($query_retHash);
$hash = $row['password'];
//get name
$retName = "SELECT user_name FROM users WHERE user_name='$name'";
$query_retName = mysqli_query($conn, $retName);
$row = mysqli_fetch_array($query_retName);
$uname = $row['user_name'];
//get 'activated'
$retAct = "SELECT user_name FROM users WHERE user_name='$name'";
$query_retAct = mysqli_query($conn, $retAct);
$row = mysqli_fetch_array($query_retAct);
$activated = $row['activated'];
if (filter_input_array(INPUT_POST)) {
if ($name !== $uname) {
$mainError = true;
}
if (!password_verify($pass1, $hash)) {
$mainError = true;
}
if ($activated != 1) {
$mainError = true;
}
if (!$mainError) {
$feedback = 'Здравей,' . $name . '!';
} else {
$feedback = 'Грешни данни!';
}
}
?>
As #Rajdeep Answered,
$retAct = "SELECT user_name FROM users WHERE user_name='$name'";
^ it should be activated
Better use one query. Fetch all details.
<?php
//connection with database
require "db_connect.php";
require "password_compat-master/lib/password.php";
$name = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'name'))));
$pass1 = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'pass1'))));
$errorName = '';
$errorPass1 = '';
$feedback = '';
$mainError = false;
//get hash
$retHash = "SELECT * FROM users WHERE user_name='$name'";
$query_retHash = mysqli_query($conn, $retHash);
$row = mysqli_fetch_array($query_retHash);
$hash = $row['password'];
$uname = $row['user_name'];
$activated = $row['activated'];
if (filter_input_array(INPUT_POST)) {
if ($name !== $uname) {
$mainError = true;
}
if (!password_verify($pass1, $hash)) {
$mainError = true;
}
if ($activated != 1) {
$mainError = true;
}
if (!$mainError) {
$feedback = 'Здравей,' . $name . '!';
} else {
$feedback = 'Грешни данни!';
}
}
?>
Look at this statement here,
//get 'activated'
$retAct = "SELECT user_name FROM users WHERE user_name='$name'";
^ it should be activated
And there's no point running three separate queries. You can achieve the same thing using only one query, like this:
// your code
$query = "SELECT user_name, password, activated FROM users WHERE user_name='$name' LIMIT 1";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
$uname = $row['user_name'];
$hash = $row['password'];
$activated = $row['activated'];
if (filter_input_array(INPUT_POST)) {
// your code
}

PHP PDO Logging Into Account

<?php
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
$rowcount = $query->rowCount();
if($rowcount == 1){
$row = mysql_fetch_array($query);
$dbPass = $row["password"];
if($password == $dbPass){
session_start();
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else
return false;
} else
return false;
}
?>
This is a PHP code snippet from a project I am globally converting to PDO. This is the functions.php file for the login page. Obviously it is not fully converted to PDO so don't criticize that, but basically in the login.php file I have it access this method, and pass the database(which is required in), the username, and the password from the form. I setup a basic query to find all users with the username input of the form. Then i prepare, and execute the query. I then need a row count, so I setup a $rowcount variable running the rowCount() method on the query, but the code does not move past there. The rowcount is == 0 when I echo it out so it won't proceed to the following if statement. Am I doing something wrong with the PDO or something? Or the rowCount(). My suspicion is that perhaps I am calling the rowCount() too late, so I tried moving it up before I execute the $query but no luck. Thank you!
___EDIT___
<?php
session_start();
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
if($query->rowCount()){
$row = $query->fetch();
echo $row;
$dbPass = $row["password"];
if($password == $dbPass){
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
Don't mix pdo and mysql_ functions together. NEVER!
Don't store password in plain text. NEVER! Instead try Password_compat !
First:
Is to replace
$row = mysql_fetch_array($query);
with
$query->fetchAll(PDO::FETCH_ASSOC)
Second:
session_start() should appear at the top of your script, not inside your function.
Third:
Is to replace
$rowcount = $query->rowCount();
if($rowcount == 1){
//
}
with this:
if($query->rowCount()){}
Fourth:
This is BAD!!
return true;
} else
return false;
} else
return false;
}
Always, use a complete delimiter. You are instilling a bad-codding practice, that will haunt you for life.
Simple do
if($foo){
if(){
//do something
}else if{
//do something
}else{
//do something
}
}
Fifth:
~Not good, but definitely better that your approach.
function small_query(pdo $pdo, $query, array $value){
$stmt = $pdo->prepare($query);
$stmt->execute($value);
return $stmt->fetchAll();
}
$pdo = new PDO('mysql:host=localhost; dbname=foo', 'root', 'pass');
$result = small_query($pdo, "SELECT * FROM users WHERE name = ?", array($_POST['name']))
EDIT.
Since you seem to love your code so much, I have done it your way. Try this:
<?php
session_start();
function login($database, $username, $password){
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $database->prepare($query);
$stmt->execute(array($username));
if($stmt->rowCount()){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_SESSION["id"] = $result["id"];
$_SESSION["username"] = $result["username"];
$_SESSION["email"] = $result["email"];
return true;
}else{
return false;
}
}

PHP Login Script Broken

Hello Ladies and Gentlemen, I have been working on this project for some time now. And all of a sudden when I go into the web page to login I just get a blank screen at the 'success_login.php' which is literally just the login script that runs once login is clicked on my screen.
Here is the success_login.php script:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/luke/classes/userFunctions.php');
$userFunctions = new userFunctions();
session_start();
//assign all posted values to a session
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
$_SESSION['login_info'][$key] = $value;
}
}
//Get the username and password
$username = htmlentities($_POST["username"], ENT_QUOTES);
$password = htmlentities($_POST["password"], ENT_QUOTES);
//Get the user id if the login was valid
$userId = $userFunctions->validLogin($username,$password);
if($userId != 0) {
$_SESSION['login_info']['username'] = $username;
$_SESSION['login_info']['password'] = $password;
$_SESSION['login_info']['user_id'] = $userId;
header('LOCATION: home.php');
exit;
}
header('LOCATION: login.php');
exit;
?>
and here is the function it refers to:
public function validLogin($username,$password) {
$dbact = new DbInteraction();
$query = "select * from person";
$result = $dbact->interact($query,true);
$row = mysql_numrows($result);
$valid = false;
$userId = 0;
while ($row = mysql_fetch_array($result)) {
//Check to see if the username and password are valid
$validUsername = strcmp($username,$row['username']);
if($validUsername == 0) {
$hashedPassword = md5($password . Constants::SALTED);
$validPassword = strcmp($hashedPassword,$row['password']);
if($validPassword == 0) {
$valid = true;
$userId = $row['idperson'];
}
}
}
if(!$valid) {
$_SESSION['login_info']['username'] = "error";
$_SESSION['login_info']['password'] = "";
header('LOCATION: login.php');
exit;
return $userId;
} else {
$_SESSION['login_info']['username'] = "";
$_SESSION['login_info']['password'] = "";
return $userId;
}
}
Like I said, its been working for months and now all of a sudden its not anymore, and it has me really worried. Could someone shed some light for me?
Thanks a million for your time!

Categories