Codeigniter no data sent posted on form - php

My login system suddenly stopped working, I can't fix it, I've been looking into it and it seems that the data doesn't get posted back but I can't find the problem.
This is my view:
<?php if(! is_null($err)) echo "<div class=\"alert alert-danger\">".$err."</div>";?>
<form class="form-signin" action="<?php echo site_url("user/validate"); ?>" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="email" class="sr-only">Email address</label>
<input type="email" name="email" class="form-control" placeholder="Email address" required autofocus>
<br/>
<label for="password" class="sr-only">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<br/>
<button class="btn btn-lg btn-primary btn-block" name="submit" type="submit">Sign in</button>
</form>
</div>
This is my my validate function inside the user controller:
public function validate()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
// Load the model
echo "$email and $password sent";
print_r($this->input->post());
exit();
$this->load->model('User_model');
// Validate user's login details
$result = $this->User_model->validate($email, $password);
// Now we verify the result
if($result == 0){
// If user did not validate, then show them login page again
$err = 'Invalid email and/or password.';
$this->login($err);
}else{
// If user did validate send him to homepage after setting the credentials
$this->session->set_userdata($result);
redirect(site_url("/index/index"));
}
}
the echo and the print_r show that no data is posted.
After some research I found out that the problem should be the .htaccess file, this is my current .htaccess:
RewriteEngine On
RewriteRule ^(application) - [F,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
But it's not working.

you have an exit(); in validate function comment it
try : if(!empty( $err ))
try : base_url("index.php/user/validate");
try : load model inside
public function __construct()
not inside of
public function validate()

<form class="form-signin" action="<?php echo site_url("user/validate"); ?>" method="post">
Change this to the following:
<form class='form-signin' action="<?php echo base_url();?>user/validate" method="post" name="user_from">
Also don't use the submit button name as 'submit'. Just use sbt or other name, id too...

Related

Login session doesnt work "Hello, $_SESSION[name]" [duplicate]

This question already has answers here:
When do I have to declare session_start();?
(2 answers)
Closed 1 year ago.
I did the register part and everything went well. I have reached the part where the user must log in to the site. The problem is that if I enter the wrong data in the login page, I get a message that the data is wrong.
But if I add the correct data for login, it redirects me to index.php, but the header does not change. Normally instead of the login and registration button, something like this should appear: Hi, Andrew. And a logout button.
Index header with login and register buttons
<?php
if(isset($_SESSION['id'])){
echo "<a href='login.html' class='login-panel'><i class='fa fa-user'></i>Salut, $_SESSION[name]. </a>
<button type='button' class='btn btn-light'>Logout</button>";
}
else {
echo " <a href='login.html' class='login-panel'><i class='fa fa-user'></i>Login</a>
<a href='inregistrare.html' class='login-panel'><i class='fa fa-user-plus'></i>Înregistrare</a>";
}
?>
Login form from login.php
<form method="post" action="login.php">
<div class="form-group">
<label for="email">* Adresa de e-mail:</label>
<input type="text" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password">* Parola:</label>
<input type="password" id="password" name="password" class="form-control" required>>
</div>
<div class="form-group gi-check">
<div class="gi-more">
<label for="save-pass">
Salvează parola
<input type="checkbox" id="save-pass">
<span class="checkmark"></span>
</label>
Ai uitat parola?
</div>
</div>
<div class="form-group">
<button type="login" name="login" class="site-btn login-btn">Intră în cont!</button>
</div>
</form>
login.php
session_start();
include('config.php');
// Cod pentru logare
if(isset($_POST['login']))
{
$password=$_POST['password'];
$dec_password=$password;
$email=$_POST['email'];
$ret= mysqli_query($con,"SELECT * FROM utilizatori WHERE email='$email' and password='$dec_password'");
$num=mysqli_fetch_array($ret);
if($num>0)
{
$extra="index.php";
$_SESSION['login']=$_POST['email'];
$_SESSION['id']=$num['id'];
$_SESSION['name']=$num['nume'];
$host=$_SERVER['HTTP_HOST'];
$uri=rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("location:http://$host$uri/$extra");
exit();
}
else
{
echo "<script>alert('Nume sau parola invalide!');</script>";
$extra="index.php";
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
exit();
}
}
?>```
Kindly check that have you manage exception if condition not satisfied. also if you enter wrong data and once you logout you have to update code for session_destroy() . other wise same session has be called next time as well. I hope it will help to you.

redirect url to requested page after login codeigniter

I have an issue while login . when i click on a link and if i am not loggedin than it will redirect me to login page and after success login it should redirect me requested url but it redirect me to profile page.
here is my view file:
<!--Left cols-->
<?php error_reporting(0);?>
<div class="col-lg-8 col-sm-8 col-md-8">
<div class="reg-form">
<h2>Member's Login</h2>
<title>Login</title>
<form method="post" action="<?php echo base_url();?>index.php/register_step1/login">
<div class="row">
<label for="name">Email</label>
<span><i class="icon-name"></i><input type="email" placeholder="example#gmail.com" required id="name" name="email"/></span>
</div>
<div class="row">
<label for="pass">Your Password</label>
<span><i class="icon-pass"></i><input type="password" placeholder="*************" id="pass" required name="password"/></span>
</div>
<!--input type="hidden" name="redirurl" value="<?php echo $_SERVER['HTTP_REFERER']; ?>" /-->
<div class="row">
Forgot Password click here / Register new user
</div>
<div class="row">
<input type="submit" value="Login" name="submit"/>
</div>
</form>
</div>
</div>
<?php $this->load->view("home_template/rightbar");?>
And this is my controller :
public function login(){
$this->load->model("User_model");
$this->load->library('user_agent');
if(isset($_POST["submit"])){
//$url = $this->input->post("redirurl");
$data = $this->User_model->login();
if($data){
foreach($data as $dta){
$id = $dta->id;
$email = $dta->email;
}
$session_array = array("id"=>$id,"email"=>$email);
$this->session->set_userdata("logged_by_login",$session_array);
redirect("profile");
}
}
else{
}
$data["main_content"] = "login_view";
$this->load->view("home_template/template",$data);
}
for page redirection we used redirect() statement in codeigniter.
redirect() sends the user to the specified web page using a redirect
header statement.
redirect() statement resides in the URL helper so we need to load url helper:
$this->load->helper('url');
profile page redirection we write bellow statement and pass first parameter as "Profile" and second last parameter is "refresh/location".
redirect('profile','refresh');
The redirect function loads a local URI specified in the first
parameter of the function call and built using the options specified
in your config file.
The second parameter allows the developer to use different HTTP
commands to perform the redirect "location" or "refresh".
According to the Code Igniter documentation: "Location is faster, but
on Windows servers it can sometimes be a problem." so better to use "refresh" as second parameter
You can use redirect like this. Might be controller not get correct path,
$this->load->helper('url');
redirect(base_url('profile'));
Let me know if it not works.
change your code to
un comment your code
" /-->
change to
<!input type="hidden" name="redirurl" value="<?php echo $_SERVER['HTTP_REFERER']; ?>" />
and in your controler change code as shown below
if($data){
foreach($data as $dta){
$id = $dta->id;
$email = $dta->email;
}
$session_array = array("id"=>$id,"email"=>$email);
$this->session->set_userdata("logged_by_login",$session_array);
redirect("profile");
if(!empty($this->input->post('redirurl'))){
redirect($this->input->post('redirurl'),'refresh');
}else{
redirect('profile','refresh');
}
}

CodeIgniter htaccess redirect url issues

I want "nice urls" for my website. I'm looking at using .htaccess and I have tried many versions.
Now I have this:
IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
# !IMPORTANT! Set your RewriteBase here and don't forget trailing and leading
# slashes.
# If your page resides at
# http://www.example.com/mypage/test1
# then use
# RewriteBase /mysite
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
So this removes index.php from the URL. At first it was ok, but
Here is my config.php:
$config['base_url'] = 'localhost/mysite/';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
And my .htaccess file is in my app root.
folder img
I need a login for admin page, so localhost/mysite/admin is the my url for admin site.
public function index()
{
// $this->session->unset_userdata('logged_in'); session_destroy();
$data['sitename']="Varkocs Old Pub";
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('admin/home_view', $data);
}
else
{
//If no session, redirect to login page
//redirect('login', 'refresh');
$this->load->helper(array('form', 'url'));
$this->load->view('admin/login',$data);
}
}
public function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('', 'refresh');
}
This is my admin controller. I try here if logged in I load home_view, else the login view.
<div id="" class="container-fluid ">
<div id="" class="row">
<div id="" class="col-md-4 text-center admin_container">
<h2><?php echo $sitename;?><h4>belépés az admin felületre</h4></h2>
<?php echo validation_errors('<p class="bg-danger">','</p>');?>
<form action="verifylogin" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="username">Username:</label>
<input class="form-control" placeholder="" type="text" size="20" id="username" name="username"/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input class="form-control" placeholder="password" type="password" size="20" id="passowrd" name="password"/>
</div>
<input class="btn btn-warning btn-lg btn-block" type="submit" value="Login"/>
</form>
</div>
</div>
This is the login view. I can't use here:
echo form_open('verifylogin');
Because it's returning the wrong URL.
So I write HTML:
<form action="verifylogin" method="post" accept-charset="utf-8">
The form validation with CodeIgniter is working. But the redirect afterwards doesn't work.
$this->load->helper(array('form', 'url'));
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$data['sitename']="Varkocs Old Pub";
$this->load->view('admin/login',$data);
}
else
{
//Go to private area
redirect('admin', 'refresh');
}
I have tried many ways to fix this, but I failed.
The Codeigniter documentation says the following about the redirect function:
In order for this function to work it must be used before anything is outputted to the
browser since it utilizes server headers.
This rule can be tricky to follow. A space or line end before the opening PHP tag will already break it.

403 Forbidden You don't have permission to access /mytesting/< on this server. ERROR

I am trying to figure our what causing the error on my simple login localhost program.
My base_url = http://localhost/MYTESTING
I have this on my loginpage.php controller
public function login(){
$data['title'] = "TEST LOGIN";
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->view("loginheaderTest.php",$data);
$this->load->view("loginpage.php",$data);
$this->load->view("footerTest.php",$data);
if(isset($_POST['login']))
{
$data['authenticate'] = $this->AuthenticationTest->authenticate_acount($username,$password);
if(!empty($data['authenticate']))
{
echo"<script>
alert('Success');
</script>
";
}
else
{
echo"<script>
alert('Invalid Username or Password');
</script>
";
}
}
}
and I have this on my model
public function authenticate_account($username,$password){
$this->db->select("username");
$this->db->from("accounts");
$this->db->where("username",$username);
$this->db->where("password",$password);
$query = $this->db->get();
return $query->row_array();
and this on my view :
<div class="panel-body">
<form action = "<?base_url();?>" method = "POST">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="">
</div>
<input type = "submit" class="btn btn-lg btn-success btn-block" value = "Login" name = "login">
</fieldset>
</form>
</div>
I am pretty sure I am correct on my configurations in my database config when I visit localhost/mytesting and click login the error occurs.
Does your server config allow the use of PHP short tags?
You don't have permission to access /mytesting/< on this server.
It looks as though your form action is pointing towards "/mytesting/<" and the following "?" is being removed from the error message, as it's interpreted as a query string.
Change this:
<form action = "<?base_url();?>" method = "POST">
To this:
<form action="<?php echo base_url(); ?>" method="POST">
Or enable PHP short tags in your php.ini or .htaccess.

Displaying differnt border color if field is valid

So I have my form which I have supplied pictures of below. The left side picture is a normal border color but then the red outline on the right is when the form input is invalid.
How would I do this through PHP? Here's the corresponding code
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
exit($e->getMessage());
}
// Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
// Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)) {
echo "Complete all fields";
}
// Password match
if ($password != $password1) {
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
And my HTML form
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
So if the input satisfies the if statement how would I display the color?
When your form has errors, you need to re-display it. It's hard to give a recommendation without knowing your code structure, but I will assume that your HTML is rendered via a call to php. Generally, I have done something like
$error = false
//this $_GET['submit'] variable could be part of the URL of your submitted form.
//alternately, you could check the HTTP method of the page request
if ($_GET['submit']) {
//run your form logic
//if you have success, run your php query and then redirect
//to your "success" page using a 302 (using a header("Location:... sort of call)
//you would also want to call die() or something right here
}
//if you make it this far, display your page including the bits about errors
//your form's action goes right back to the same page that rendered it, but with
//some change to the url to let the script know that you want to process the form
With PHP5 and with warnings about undefined variables turned on, you would need to define all of your error message variables before checking whether or not the form is being submitted.
Asuming you are using twitter bootstrap since you have form-control all over the place, (assuming >= 3.0.0), you can use (for the graphical side of things) has-suceess, has-error, etc like shown here: http://getbootstrap.com/css/#forms-control-validation.
When you re-display the form due to bad data, pass along your error messages to whatever renders your html. An example with your thing would be (assuming your form has access to $passmatch, $emailvalid,$passlength):
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
</div>
<div class="form-group <?php if (!empty($emailvalid)) { echo 'has-error'; } ?>">
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
</div>
<div class="form-group <?php if (!empty($passmatch) || !empty($passlength)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group <?php if (!empty($passmatch)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
I would recommend using a templating engine or something to separate the view from the actual code.
As for the help text, you can use something like this after the elements with errors:
<div class="form-group <?php if (!empty($yourVariable)) { echo 'has-error'; }?>">
<input type="text" class="form-control" />
<span class="help-block"><?php echo $yourVariable; ?></span>
</div>
The fun part is, if you have no error message, the help block won't even be shown because that variable won't have anything in it.
EDIT
Example page: http://content.kevincuzner.com/register.php
Example source: https://gist.github.com/kcuzner/11323907
I would handle this on the client side with JavaScript. On submission of the form, you can check whether the input is valid or not and then just update the border color using JavaScript.
The <?php ?> you can fill in above (if you want to go this route) can just depend on some variable that checks validity:
echo "Complete all fields";
$fieldsValid = false;
border-color: <?php $fieldsValid ? 'blue' : 'red' ?>
But you need to do a full page reload for this to work. JavaScript is a better route:
document.forms[0].addEventListener("submit", function () {
var usernameInput = document.querySelector("[name=username]");
if (!usernameInput.value) {
usernameInput.style.borderColor = "red";
}
});

Categories