form validation issue with codeigniter - php

I'm trying to develop a simple login system, but i'm facing issue during data validation.
Everything works if I enter valid data.
but when i enter invalid data it like empty user or password, it gives me validation erorr, but after that if i enter the correct user data. it wont work, it will just reload the the same page.
The strange thing that i noticed is that the url on the address bar keeps getting longer.
My login url after clicking submit button the first time.
http://localhost/ci/login/validate
My login url after clicking submit button the second time.
http://localhost/ci/login/login/validate
Every time i click the submit button, it keeps adding an extra '/login' to url.
any idea what the problem is?
My main controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$this->load->view('login/header');
$this->load->view('login/login_view');
$this->load->view('login/footer');
}
public function validate()
{
$this->load->model('login_model');
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username', 'trim|required|min_length[6]|max_length[50]|valid_email|xss_clean');
$this->form_validation->set_rules('password','Password', 'trim|required|xss_clean');
//validation check
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login/header');
$this->load->view('login/login_view');
$this->load->view('login/footer');
}
else
{
$userdata['username'] = $_POST['username'];
$userdata['password'] = md5($_POST['password']);
//check whether user exist int the database or not
$result = $this->login_model->login_validation($userdata);
//in case user exists
if($result == 1)
{
$this->set_sessions_details();
}
//in case user doesnt exist
else
{
$data['flag'] = "Incorrect Username or Password!";
$this->load->view('login/header');
$this->load->view('login/login_view', $data);
$this->load->view('login/footer');
}
}
}
//load a view in case user exists in the db.
public function set_sessions_details()
{
$this->load->view('test');
}
}
My model to check user data in db.
login_model
class Login_model extends CI_Model
{
function login_validation($userdata)
{
$user=$userdata['username'];
$pass=$userdata['password'];
$result = $this->db->get_where('users', array('username' => $user, 'password' => $pass));
return $result->num_rows();
}
}
?>
My views:
login_view
<h3>Please Login</h3>
<form method='post' action='login/validate'>
<div class="form-group" >
<label for="username">Username</label>
<input type="email" class="form-control" name="username" id="username" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Enter Password">
</div>
<button type="submit" class="btn btn-success">Login</button>
<?php echo validation_errors('<p class"errors">');?>
</form>
<?php if (isset($flag)){ ?>
<p><?php echo $flag; ?> </p>
<?php } ?>
header
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WFD</title>
<link href="<?php echo base_url();?>assets/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class='container'>
<div class="header">
<center><img src="<?php echo base_url();?>assets/images/logo.png" alt="logo" style="margin-top: 10px; padding-bottom: 20px; opacity: 1;">
<h2>
Welfare Foundation Database
</h2>
</center>
</div>
Footer
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/ci/assets/js/bootstrap.min.js"></script>
</body>
</html>

try using the form open tag in Form Helper link : https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
echo form_open('email/send');
which in the backend will create
See if this solves your issue.

I believe that, besides #Abhijit answer, your problem is the logic itself. You aren't redirecting to anywhere, and you should be. Besides you're calling repeated code unnecessarily, such as:
$this->load->view('login/header');
$this->load->view('login/login_view');
$this->load->view('login/footer');
This should only be called in one function,
public function index(){
$this->load->view('login/header');
$this->load->view('login/login_view');
$this->load->view('login/footer');
}
public function validate(){
// your validation logic
if ($this->form_validation->run() == FALSE){
$this->session->set_flashdata('error', array('msg' => 'Upps, something went wrong..', 'anotherParam' => 'anotherText'));
// this will load again the views
redirect('login');
return;
}
}
You are now able to maintain the form as you have:
<form method="POST" action="login/validate">
</form>
<?php if($this->session->flashdata('error')){ ?>
<p><?php echo $this->session->flashdata('error')->msg; ?></p>
<?php } ?>

Use url library in controllers:
$this->load->helper('url');
Use it on view
<form action="<?php echo base_url('login/validate'); ?>" method="POST">
<!-- your input -->
</form>

Related

php redirect both roles to same page

There are two roles, the administrator role and the user role. each user must be redirected to a different page, but both are redirected to the page for the adminsitrador role.
index.php contains the login form
<?php
include('conexion.php');
?>
<!DOCTYPE html>
<html lang="zxx">
<head>
<title>Inicio de Sesion</title>
<!-- Meta-Tags -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<meta name="keywords" content="Core Login Form a Responsive Web Template, Bootstrap Web Templates, Flat Web Templates, Android Compatible Web Template, Smartphone Compatible Web Template, Free Webdesigns for Nokia, Samsung, LG, Sony Ericsson, Motorola Web Design">
<!-- //Meta-Tags -->
<!-- Index-Page-CSS -->
<link rel="stylesheet" href="css/style.css" type="text/css" media="all">
<!-- //Custom-Stylesheet-Links -->
<!--fonts -->
<link href="//fonts.googleapis.com/css?family=Mukta+Mahee:200,300,400,500,600,700,800" rel="stylesheet">
<!-- //fonts -->
<!-- Font-Awesome-File -->
<link rel="stylesheet" href="css/font-awesome.css" type="text/css" media="all">
</head>
<body>
<h1 class="title-agile text-center">Acceder al Sistema</h1>
<div class="content-w3ls">
<div class="agileits-grid">
<div class="content-top-agile">
<h2>Datos de Ingreso</h2>
</div>
<div class="content-bottom">
<form action="validacion.php" method="post">
<div class="field_w3ls">
<div class="field-group">
<input name="user" id="user" type="text" value="" placeholder="User" required>
</div>
<div class="field-group">
<input id="passw" type="passw" class="form-control" name="passw" value="" placeholder="Password">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
</div>
<div class="wthree-field">
<input id="saveForm" name="saveForm" type="submit" value="Login" />
</div>
</form>
</div>
<!-- //content bottom -->
</div>
</div>
<div class="copyright text-center">
<p>© 2020 Management documents
</p>
</div>
<!--//copyright-->
</body>
<!-- //Body -->
</html>
validation.php the users are validated and redirects to the page corresponding to the role.
<?php
include('conexion.php');
$user = addslashes($_POST['user']);
$passw = addslashes($_POST['passw']);
#
$query_user = mysqli_query($conexion,"SELECT * FROM login WHERE user = '".$user."'");
$query_role = mysqli_query($conexion,"SELECT role FROM login WHERE user = '".$user."' ");
if(mysqli_num_rows($query_user) < 1){
echo "<script> alert('Error en datos...');</script>";
echo "<script>document.location.href = 'index.php'; </script>";
}else{
$query_passw = mysqli_query($conexion,"SELECT * FROM login WHERE user = '".$user."' AND password = '".$passw."' ");
if (mysqli_num_rows($query_passw) < 1) {
echo "<script> alert('Date Error...');</script>";
echo "<script>document.location.href = 'index.php'; </script>";
}else{
echo "<script> alert('SucIngreso Exitoso...');</script>";
$role = mysqli_fetch_assoc($query_role);
if(strcmp($role,"admin") == 0){
header('Location: admin.php');
}
elseif(strcmp($role,"user") == 0){
header('Location: user.php');
}
}
}
?>
A query is made to know which is the role that corresponds to the user who started the session and verify the role to redirect it to the corresponding page, but both users are redirected to the page of the admin role.
i'm going to give you a general way for quick debugging in php
which is the use of var_dump() function,and its used to show the variable type and value, use it on variables that seems to behave wrongly.
in this case
since its always redirected to the page 'admin.php',
that means this statement is always true
strcmp($role,"admin") == 0
so check the variable value by using var_dump($role); to see what value it has on every run, it may be that the value in the database is always 'admin' so you need to check it.
And use if($role === "admin") instead of if(strcmp($role,"admin") == 0) its much clearer

PHP Form does not log in and move to next page

I ran into another problem with my website that I can't get around.
I'm trying to make it so when the admin logs in he will be taken to the admin page but for some reason when I enter the correct details into the log in and press the submit button it just brings me back to the admin log in page again.
Here is a Gyazo of my problem
https://gyazo.com/34f133fea4b20ec285ee7ff491053145
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<title>Login</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
<link href='https://fonts.googleapis.com/css?family=Ubuntu:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/148866/reset.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<body>
<main id="cd-main-content">
<section id="cd-intro">
<h1>Admin Log In</h1>
<header class="cd-header">
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$adminusername = stripslashes($_REQUEST['adminusername']);
//escapes special characters in a string
$adminusername = mysqli_real_escape_string($con,$adminusername);
$adminpassword = stripslashes($_REQUEST['adminpassword']);
$adminpassword = mysqli_real_escape_string($con,$adminpassword);
//Checking is user existing in the database or not
$query = "SELECT * FROM `admin` WHERE username='$adminusername'
and password='".md5($adminpassword)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $adminusername;
// Redirect user to admin page /////////////////////////////////////////////////////////////////////
header("Location: adminpage.php");
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='admin.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<form action="" method="post" name="login">
<input type="text" name="adminusername" placeholder="Username" required />
<input type="password" name="adminpassword" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
<a class="cd-menu-trigger" href="#main-nav">Menu<span></span></a>
</header>
<div class="cd-blurred-bg"></div>
</section> <!-- cd-intro -->
</main>
<div class="cd-shadow-layer"></div>
<nav id="main-nav">
<ul>
<li><span>Login</span></li>
<li><span>What's On</span></li>
<li><span>Favourites</span></li>
<li><span>About</span></li>
<li><span>Admin</span></li>
</ul>
Close<span></span>
</nav>
</body>
<script src='js/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
You are doing:
if (isset($_POST['username'])) {
//...
}
Try this
if (isset($_POST['adminusername'])) {
//...
}
As a note, I suggest you to try use a framework, like laravel.
first I would debug by var_dump($_POST) and see what you get. I would bet that since you dont have an ID set for the input value name it is not working. If anything checking for ISSET($_POST['username']) would never work because you do not have a vairable set for that name.
var_dump($_POST) and see what you get. If not add an ID='username' to the input
try this :-
if (isset($_POST['submit'])){
// rest of code...
}

Server redrict error

index.php
<?php
require 'linessystem/connection.php';
$msg = "";
if (isset($_SESSION['username']) && !empty($_SESSION['username'])) {
if ($_SESSION['level']=='admin' or $_SESSION['level']=='user') {
header("location:linessystem/administrative/index.php");
}
if ($_SESSION['level']=='agent' && !empty($_SESSION['lang'])) {
if ($_SESSION['lang']=='ar') {header("location:linessystem/agent/ar/index.php");}
if ($_SESSION['lang']=='hr') {header("location:linessystem/agent/hr/index.php");}
if ($_SESSION['lang']=='en') {header("location:linessystem/agent/en/index.php");}
}
}
if (isset($_POST['username']) && !empty($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query="select * from users where username='$username' AND password='$password'";
$result = mysqli_query($conn,$query) or die(mysql_error($conn));
$login = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
if($login>0){
$_SESSION['username'] = $username;
$_SESSION['lang']=$row['language'];
$_SESSION['agent_id']=$row['agent_id'];
$_SESSION['level']=$row['level'];
if (isset($_SESSION['username']) && !empty($_SESSION['username'])) {
if ($_SESSION['level']=='admin' or $_SESSION['level']=='user') {
header("location:linessystem/administrative/index.php");
}
if ($_SESSION['level']=='agent' && !empty($_SESSION['lang'])) {
if ($_SESSION['lang']=='ar') {header("location:linessystem/agent/ar/index.php");}
if ($_SESSION['lang']=='hr') {header("location:linessystem/agent/hr/index.php");}
if ($_SESSION['lang']=='en') {header("location:linessystem/agent/en/index.php");}
}
}
}else{$msg= ' <div align="center" style="color:red;font-weight: bold;font-size:15px;"> wrong username or password </div><br>';
}}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Bootstrap -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/login-style.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="login-page">
<div class="form" align="center" >
<form class="login-form" method="post" action="index.php" id="loginid" >
<input type="text" name="username" required="" placeholder="username"
autocomplete="off">
<input type="password" name="password" required="" placeholder="password"
autocomplete="off ">
<p class="message"><?php echo $msg; ?></p>
<button>login</button>
</form>
</div>
</div>
</body>
</html>
I have an error in the server code of above one. I bought adomain and hosting and wh web siter is run already in other server but in this new hosting isnt run when it reserve the value but don't redirect me to the main page and the url of new hosting is http://www.quicklineltd.com.
where is the problem that I could not make it ?
User name is 2 and pass is 2.
Do you even make it into the if statement? Try an echo instead of header.
And did you use a session_start(); at the beginning of your php file?
Or did you include the file above inside another file wich already echo'd some output, because then header wont work either.
Or you should have to put a slash in front of the path, or even use a full url as in http://
Please use session_start(); at the beginning of the file. Without starting the session, the sessions used in the file will not work.

How can i get PHP login script to log users in correctly?

I am new to PHP and I am trying to develop a simple login system where it echoes a success message and redirects to a secure page and when details are wrong, it echoes an error message and reloads the login form.
I have been trying to for a while now and cannot figure it out, even though I have some functionality in terms of it directing to the correct page.
My database on PhpMyAdmin is correctly configured. Also, any help on sessions would be greatly appreciated.
PHP CODE:
<?php
$servername = "localhost";
$username = "root";
$password = "cornwall";
$con=mysqli_connect('localhost','root','cornwall','ibill');
// This code creates a connection to the MySQL database in PHPMyAdmin named 'ibill':
$username = $_POST['username'];
$password = $_POST['password'];
//These are the different PHP variables that store my posted data.
$login="SELECT * FROM users WHERE username='$username' AND password='$password'";
$result=mysqli_query($con, $login);
$count=mysqli_num_rows($result);
//This is the query that will be sent to the MySQL server.
if($count==1)
{
header('Location: http://localhost/projects/ibill_v3/html/main.html#home');
exit();
}
//This checks the 'user_details' database for correct user registration details and if successful, directs to home page.
else {
header('Location: http://localhost/projects/ibill_v3/html/loginform.html');
echo "Wrong details";
exit();
}
//If login details are incorrect
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
?>
HMTL CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1; minimum-scale=1;">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<link href="/projects/ibill_v3/css/mainstyles.css" rel="StyleSheet"/>
<link href="/projects/ibill_v3/css/loginform.css" rel="StyleSheet"/>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="script.js"></script>
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script type='text/javascript'>
$(document).on('pageinit', function(){
$('.loginform').validate({ // initialize the plugin
// rules & options
});
});
</script>
</head>
<body>
<!--********************************LOGIN FORM PAGE**********************************************-->
<!--****************************************************************************************-->
<!--********************************HEADER**********************************************-->
<div data-role="page" id="loginform">
<div data-role="header" data-id="foo1" data-position="fixed">
<h1>Register</h1>
</div>
<!--********************************HEADER**********************************************-->
<!--********************************MAIN**********************************************-->
<div data-role="main" class="ui-content">
<img class="mainlogo" src="/projects/ibill_v3/img/ibill logo.png" alt="iBill Logo" width="250" height="190">
<h2>Sign in</h2>
<section class="loginform">
<form data-ajax="false" method="POST" action="loginform.php" >
<ul>
<li>
<label for="username">Username</label>
<input type="text" name="username" id="username" class="required" minlength="5" placeholder="enter username (min-5 characters)">
</li>
<li>
<label for="password">Password</label>
<input type="password" name="password" placeholder="enter password" minlength="6">
</li>
<div id="loginformbutton">
<button class='active' type='submit' value='submit'>Sign in</button>
</div>
<p>Don't have an account? Sign up!</p>
<div id="registerbutton">
Register
</div>
</ul>
</form>
</section>
</div>
<!--********************************MAIN**********************************************-->
<!--********************************FOOTER**********************************************-->
<div data-role="footer">
<footer class="footer">
<p>awilliams©</p>
</footer>
</div>
</div>
<!--********************************END OF LOGIN FORM PAGE**********************************************-->
<!--****************************************************************************************-->
</body>
...
else
{
header('Location: http://localhost/projects/ibill_v3/html/loginform.html');
echo "Wrong details";
exit();
}
The above is going to redirect before your echo statement is reached, so nothing will be displayed.
Secondly, the following line:
<form data-ajax="false" method="POST" action="loginform.php" > will not send any data back to your file containing the form if you're using echo statements. It is going to redirect to the loginform.php and will stay there if you do not explicitly redirect back the page with your form.
Instead, use:
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> as your form's action. And then include your loginform.php somewhere before the form in your HTML.
This is going to send data back to the form's file and replaces special characters to HTML entities (for security), it also allows you to use echo's or variables to return messages to the user.
loginform.php will need to check if specific inputs are posted:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($_POST['username'] && $_POST['password'])
{
//do work
}
}
Here is a basic php form tutorial to start you off: php tutorial
I think it's because your redirecting to the same page with no post. I didn't look through all the code, that is just my first stab at it
This will not appear on loginform.html:
echo "Wrong details";
Use something like:
$_SESSION['errorMessage'] = "Wrong details";
header('Location: http://localhost/projects/ibill_v3/html/loginform.html');
exit();
And then on loginform.html, add this code to display the error message:
if(isset( $_SESSION['errorMessage'])) echo $_SESSION['errorMessage'];

PHP CodeIgniter custom login form

I am trying to create a login form using CodeIgniter in PHP. I have implemented the functionality, working okay, however I cannot manage to style my for with a custom stylesheet.
Here is the code I have for the login view:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
DTI Manager
</title>
<link rel="stylesheet" type="text/css" href="/DTIManager/assets/css/style.css" />
</head>
<body>
<div id="wrapper">
<?php echo validation_errors();?>
<?php $attributes = array('class' => 'LoginController', 'id' => 'login-form');
echo form_open('LoginController/checkLogin', $attributes);?>
<form name="login-form" class="login-form" action="" method="post">
<div class="header">
<h1>Autentificare</h1>
<span>Pentru a accesa informatii despre comenzi transporturi trebuie sa fiti autentificat.</span>
</div>
<div class="content">
<input name="username" type="text" class="input username" placeholder="Utilizator" />
<div class="user-icon"></div>
<input name="password" type="password" class="input password" placeholder="Parola" />
<div class="pass-icon"></div>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button"/>
</div>
</form>
</div>
<div class="gradient"></div>
</body>
</html>
And this is my LoginController class:
class LoginController extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('login');
}
public function checkLogin() {
$this->form_validation->set_rules('username', 'Utilizator', 'required');
$this->form_validation->set_rules('password', 'Parola', 'required|callback_verifyUser');
if ($this->form_validation->run() == false) {
$this->load->view('login');
} else {
redirect('HomeController/index');
}
}
public function verifyUser() {
$name = $this->input->post('username');
$pass = $this->input->post('password');
$this->load->model('LoginModel');
if ($this->LoginModel->login($name, $pass)) {
return true;
} else {
$this->form_validation->set_message('verifyUser', 'Incorrect Email or Password. Please try again.');
return false;
}
}
}
I tried adding the attribute to the form_open function the ID of my form but it wasn't successful, the buttons and fields are still not styled accordingly.
Any hints are highly appreciated.
Try echoing the base_url() in front of your linked css files.
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>DTIManager/assets/css/style.css" />
Of course, if you use an .htaccess you should ignore the folder that has the assets in your project with a proper rewrite rule.
RewriteCond $1 !^(index\.php|DTIManager|assets|robots\.txt|error\.html)

Categories