Compare values given by user to values in ini file - php

I am trying to make a login validation page for my class and this is the code I have for the page LoginDataModel.php.
<?php
//define a constant variable for fxUsers.ini
define('FX_LOGIN_INI_FILE', 'fxUsers.ini');
class LoginDataModel {
private $ini_array;
//construct class will read and store an associative array
public function __construct() {
$this->ini_array = parse_ini_file(FX_LOGIN_INI_FILE);
}
//validateUser function will compare the username and password
//given by the user to the values stured in the ini file.
public function validateUser($username, $password){
if(in_array($username,$this->ini_array) && in_array($password,$this->ini_array)){
return TRUE;
} else {
return FALSE;
}
}
}
?>
This code will be called in my login.php page once the user passes through his credentials. If the users credentials do not match, he will simply be rerouted back to the login page to try again. The code for the login page is
<?PHP
//check for key to see if this is the first time loading the page
if (empty($_POST['txtUser'])){
$user = '';
$pass = '';
} else {
$user = $_POST['txtUser'];
$pass = $_POST['txtPassword'];
}
//call method from a different file
require_once ('LoginDataModel.php');
$LoginDataModel = new LoginDataModel();
$control = $LoginDataModel->validateUser($user, $pass);
//if user and password match, continue to next file and exit current file
if($control === TRUE){
include 'fxCalc.php';
exit();
}
?>
While I believe to have everything set, The only thing I need is how to compare the values between the user and the values in the ini file. Any help would be appreciated
EDIT
I should have mentione that my ini file will just be
[section]
admin = pass
EDIT 2
My code reflect the changes I've made thanks to the support from this post as well as looking back at my text book. My problem is now that When I pass the user and pass through the file, it returns as false even though the strings match perfectly.

You are doing the wrong way of comparison in the below line..
if($ini_array == $username && $ini_Array == $password){
The parse_ini_file() returns an array , so you just can't check a variable $username inside an array (i.e. $ini_array) using a == operator. You should be using array_search or in_array() functions as such.
Something like...
if(in_array($username,$ini_array) && in_array($password,$ini_Array)){

Related

need help understand how this PHP login array code works?

So the code at the bottom is an example code from my class of how to do a login page, it takes what is posted in an input box from an html file and receives this in a php file, the code then checks the username and password from an array and verify it or declines it, I can't understand what the syntax means in the if(), specifically the "isset($_POST['user']) && !isset($_SESSION['user'])" and such, I was hoping someone could break down what exactly each line does or what the syntax means? thanks for your time.
// (A) START SESSION
session_start();
// (B) HANDLE LOGIN
if (isset($_POST['user']) && !isset($_SESSION['user'])) {
// (B1) USERS & PASSWORDS - SET YOUR OWN !
$users = [
"joe" => "123456",
"jon" => "654321",
"joy" => "987654"
];
// (B2) CHECK & VERIFY
if (isset($users[$_POST['user']])) {
if ($users[$_POST['user']] == $_POST['password']) {
$_SESSION['user'] = $_POST['user'];
}
}
// (B3) FAILED LOGIN FLAG
if (!isset($_SESSION['user'])) { $failed = true; }
}
isset = Check whether a variable is empty. here you are checking $_POST['user'] has any value set or not.
$_POST['user'] = there is a value sent to this page using post method, and name is 'user'
$_SESSION['user'] = there is a session named user
now
isset($_POST['user']) && !isset($_SESSION['user']))
means
check whether page received any post method named user and there isn't any session named user

security for a page function in php

so here I have a page that holds all the functions.
I give name "init-admin" and I call all these functions on all admin pages
this is the content of init-admin.php
<?php
session_start();
require_once "admin-functions/db.php";
require_once "admin-functions/admin.php";
require_once "admin-functions/navigation1-content.php";
require_once "admin-functions/navigation1-press.php";
require_once "admin-functions/navigation1-restrospective.php";
require_once "admin-functions/navigation1-inquiries.php";
require_once "admin-functions/navigation2-earrings.php";
require_once "admin-functions/navigation2-necklaces.php";
require_once "admin-functions/navigation2-bracelets.php";
require_once "admin-functions/navigation2-sets.php";
require_once "admin-functions/navigation2-men-jewelrys.php";
require_once "admin-functions/navigation2-object_arts.php";
require_once "admin-functions/navigation2-rings.php";
require_once "admin-functions/navigation2-pin_pendant.php";
?>
and this is one of the functions I call as an example. Its function name is "admin.php" this is his content
//1. REGISTER
function Register($username, $email, $password){
global $connect;
$username = mysqli_real_escape_string($connect, $username);
$email = mysqli_real_escape_string($connect, $email);
$password = mysqli_real_escape_string($connect, $password);
$password = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO admin (admin_username, email, password, actor) VALUES ('$username', '$email', '$password', '1')";
if( mysqli_query($connect, $query) ){
return true;
}else{
return false;
}
}
function prevent_twin_names($username){
global $connect;
$username = mysqli_real_escape_string($connect, $username);
$query = "SELECT * FROM admin WHERE admin_username ='$username'";
if( $result = mysqli_query($connect, $query) ){
if(mysqli_num_rows($result) == 0) return true;
else return false;
}
}
my problem here if i give session like
require_once "core-admin/init-admin.php";
if( !isset($_SESSION['admin_username']) ){
$_SESSION['msg'] = 'page can not open';
header('Location:admin_login.php'); exit();
}
on the function page I get an error "to many redirect".
so I want to ask here if the function page if not given session will be dangerous?
but if I try to call the page function in the browser page that appears only blank pages.
can anyone explain? ty
Okay, so you seem to have various problems here, I will try to answer one question at a time.
header()
With PHP we have the header function; we can use for various purposes, to change the location of the page:
header('Location: index.php');
Or to set the type of content your page is displaying:
header('Content-Type: text/plain');
This is useful when dealing with certain parts of your code. header location is probably the most used function, but you have to be careful when using it. It's usually bound to run you into problems.
The error you are getting comes from redirecting the user too many times with one attempt. That, I believe, is different for each browser.
To fix that error you have to look for where else you set a header, and make sure you only set one header per page. Also note:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Functions
So first let's deal with your function questions. The reason your function page is blank when you load it in your browser it's because it's inside of a function. That means that the block of code before your eyes will only run when initiated. Thus, a blank page.
In practice this would look like:
function foo()
{
return 'Hello Foo!';
}
To get the output out of that function I have to initiate it in my code somewhere, either in it's own file (not a good practice) or where in the code I need it. You can initiate it by
echo foo();
or assign it to a variable:
$foo = foo();
The purposes of functions is so that you do not have to write the same code over and over again. You write one block of code with general guidelines and each time you need the code to be executed, you then call the function.
Sessions
Now that we have discussed functions, please do not add a session to your function. You want functions to be as reusable as possible, add a session at the top of your page.
<?php
session_start();
// some code ...
if(isset($_POST['submit'])
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if( Register($username, $email, $password) === true )
{
echo 'Registration Complete';
}
else
{
echo 'Registration failed';
}
}
?>
<html>
<head>
</head>
<body>
<form id="registration">
</form>
</body>
</html>
Now when the register, you can call the function. That would be better practice than to start you session with your function.
Here's why, your registration function will come after some code has already been written; a session has to start at the top. Or else it would not run properly. To fix that you can create a function which create a session for you:
function start_my_session()
{
session_start();
}
This one is very simple, but you can buff up your security with different session function. For more information on session security look at PHP's Manual.

Sometimes Trying to get property of non-object

After login after some random time when i refresh any page on website, sometimes it works perfectly, but sometimes it shows error like Trying to get propert on different lines of model and controller file.
For example, when i refresh the page error was shown in below function of model named user_model and controller named User.php:
User_model.php:
public function get_client_id($email)
{
$this->db->select('id');
$this->db->where('email', $email);
$query = $this->db->get('crm_accounts');
$result = $query->row();
return $result->id; //line 135
}
Users.php:
$email = $_SESSION['email'];
$id = $this->user_model->get_client_id($email); //line 145
Setting the session value after login:
$email = $this->input->post("email");
$password = $this->input->post("pass");
$result = $this->user_model->login($email, $password);
if ($result == TRUE)
{
$this->session->set_userdata('email',$email);
$this->session->set_userdata('logged_in',TRUE);
$data = $this->user_model->get_username($email);
$this->session->set_userdata('data', $data);
redirect('admin_view');
}
else
{
$this->load->view('all_field');
}
code for deleting the session after logout:
$logged_in = $this->session->userdata('logged_in');
$log = $this->session->userdata('email');
if($logged_in || (!empty($log)))
{
$array_item = array('email', 'logged_in');
$this->session->unset_userdata($array_item);
redirect('');
}
else
{
$this->load->view('error_page');
}
Here, i got error on like
Tring to get property of non-object on line 135 of user_model.php and in backtrace it found error on Users.php on line 145
I have noticed that when i get this type of error in model, i am getting data in that particular method using session variable $email in which the session data is stored. But i have put such condition in controller:
public function index()
{
if(!empty($_SESSION['email']))
{
$email = $_SESSION['email'];
$data = $this->user_model->get_username($email);
$this->session->set_userdata('data',$data);
redirect('clientview');
//echo "You are already logged in";
}
else
{
$this->load->view('signup');
}
}
So, if the value of session variable $email is not set than it should go on signup page.
So, i am not getting what is actually problem. Because sometimes it works perfectly and sometimes not. Once if i get such error, i have to clear my history and than i have to log in again.
In Codeigniter you have a specific way to get form or set values in the session.
If you want to check if the session exist you need to do
$this->session->userdata('email');
Which will retrieve the stored value.
And as you already do:
$this->session->set_userdata('email', $email);
To set a value in the session.
Additionally when the user is logging out yoi need to reset the stored value, ptherwise it will never be empty.
$this->session->set_userdata('email', '');
NOTE: What you are doing is of course not the best way to do such kind of stuff, as a login and logout system. I suppose you are just learning and you are doing this not for a production application.
If you do, please try to use ionAuth authentication library for Codeigniter, that you can find here:
http://benedmunds.com/ion_auth/
And follow some tutorial about it:
http://www.tutorials.kode-blog.com/codeigniter-authentication
Just keep in mind that user authentication is a serious security matter so be carefull.

PHP class sessions

I'm sorry, I followed WikiHow steps (link is down there) and I made everything but here is the problem:
My index.php contains password input.
if(isset($_POST['login']))
{
require('session.class.php');
if(hash('sha256', $_POST['pass']) == hash('sha256', 'password123'))
{
$session = new session();
$session->start_session('_s', false);
$_SESSION['namesession'] = 'something';
header(location: /mama.php);
}
else
{
echo "<font color='#FF0000'>Wrong password!</font>";
}
}
I don't understand how to put session check on other pages. Other words:
How to put inside if password is correct, you can stay on mama.php page..
http://www.wikihow.com/Create-a-Secure-Session-Management-System-in-PHP-and-MySQL#Create_session.class.php_file_sub
When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.
So if you want to check the post data put the if statement after the session_start().

OO PHP | Properly Passing POST Paramaters

I am relatively new to OO PHP and I am trying to create a login class.
The issue I am having is that I want to pass the POST values username and password to my class but I cannot establish a decent way of doing so.
below is a snippet of my class
class PortalLogin{
private $username;
private $password;
function __construct(){
//I connect to DB here
}
function login($username, $password){
//error check the paramaters here
//then I can run the query
}
function __destruct(){
//I disconnect from DB here
}
}
Above is a breakdown of the class I am creating below is how i plan to execute it (my main issue at the moment).
$login = new PortalLogin();
if(isset($_POST['username'])){
if(isset($_POST['password'])){
$login->login($_POST[username],$_POST[password]);
} else {
//throw error
}
} else {
//throw error
}
I really do not like the construction of the code above it seems to messy to be doing so much outside of my class. how can I pass the POST information to the class and execute the checks there? I am worrying that if I pass the POST information to the class and one of the POSTS contains nothing it will error.
I think you got a problem with the syntax of post..
if(isset($_POST['username']) && isset($_POST['password'])){
$login->login($_POST['username'],$_POST['password']);
}
use AND.. so if both username and password exist then call the login function()
I’m not sure where OOP comes in to this, but if you were going the object-oriented route you would have a class that represents a request from which you could grab POST data from:
$username = $request->post('username');
$password = $request->post('password');
Your post() method could return a default value (null) if the variable didn’t exist in the POST data.
You could then have a class that checks your user based on these variables:
$auth = new AuthService($dbConnection);
if ($auth->checkCredentials($username, $password)) {
// Valid user
} else {
$error = $auth->getLastError();
}
I know I might be in the minority with suggesting this, but I favour static methods for things like this. PortalLogin represents an action rather than data
class PortalLogin
{
/**
* Attempt login
* #param string $username
* #param string $password
*/
public static function login ($username, $password)
{
// do your login stuff
}
}
Then to use you would do this:
if (isset($_POST['username']
&& !empty($_POST['username']
&& isset($_POST['password']
&& !empty($_POST['password']
) {
PortalLogin::login($_POST['username'], $_POST['password']);
}
Even better OO would be to have the username/password checking baked into the User class. (Maybe User::checkLoginCredentials($u, $p); // boolean yup/nope)
You can use error suppression, like this:
$login->login(#$_POST['username'], #$_POST['password']);
If one or both values are not present in the $_POST variable, there won't be an error when calling the method, so you can do the error handling inside your class method.
For more info, check:
http://php.net/manual/en/language.operators.errorcontrol.php
Edit:
Another option is to do this:
$login->login((isset($_POST['username']) ? $_POST['username'] : null), (isset($_POST['password']) ? $_POST['password'] : null));

Categories