creating own form validation rule in codeigniter - codeigniter

I am using codeigniter to build a website. There is a "forgot password" link on the login page.When the user clicks on it ,he is asked to enter his email and then will further proceed.I want to set a rule on the email entered by user to check whether it exists in the database or not.In case the email does not exist in the database an error message should be displayed that the email does not exist and redirect the user to the same page. I am new to codeigniter.Please help me.Thanks in advance.This is what I have tried with no success.
view 'change password'
<!DOCTYPE html>
<html>
<head>
<title> Login</title>
<link rel="stylesheet" href="http://localhost/cinema/assets/css/form.css">
</head>
<body>
<form action="http://localhost/cinema/verifyque/sec_que" method="post" accept-charset="utf-8" class="username">
<br>
<p>
<label for="email_id">Email ID</label>
<input type="text" id="username" name="email_id"/>
</p>
<input type="submit" name="btnSubmit" class="styled-button-8" value="Submit"
/>
<font color="red" size="4"><b>
<?php echo validation_errors(); ?></b></font>
</form></body></html>
Controller
function sec_que(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email_id', 'Email', 'callback_email_available');
function email_available($str)
{
// You can access $_POST variable
$this->load->model('user');
$result = $this->user->emailAvailability($str);
if ($result)
{
return TRUE;
}else{
$this->form_validation->set_message('email_available', 'The %s does not exist');
return FALSE;
}
}
if($this->form_validation->run() === TRUE) {
$this->load->model('user');
$email['email_id'] = $this->input->post('email_id');
$this->session->set_userdata($email);
$data['que_id_1']= $this->user->display_que();
$data['que_id_2']= $this->user->display_que2();
$this->load->view('forgot_password_2', $data);
}
else{
$this->load->view('change_password');
}
}
Model
public function emailAvailability($email)
{
$this->db->where('user_email',$email);
$query = $this->db->get('users');
return $query->row();
}

Here is the code that you need to use..
Use the Callback method,
Form Validation:
$this->form_validation->set_rules('Email', 'Email', 'callback_emailAvailability');
Model:
public function emailAvailability($email)
{
$query = $this->db->get_where('user_email',$email);
if($query > 0){
return true;
}else{
return false;
}
}
Hope it helps.

Related

Error: page requested not found codeigniter

Controller
public function index()
{
//load session library
$this->load->library('session');
if($this->session->userdata('user')){
// redirect('home');
$this->load->view('heropage');
}
else{
$this->load->view('login_page');
}
}
public function login(){
$email = $_POST['email'];
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if($data)
{
$id=$data[0]->id;
$first_name=$data[0]->firstname;
$last_name=$data[0]->lastname;
$grade=$data[0]->grade;
$points=$data[0]->points;
$this->session->set_userdata('user_id',$id);
$this->session->set_userdata('lname',$last_name);
$this->session->set_userdata('user', $email);
$this->session->set_userdata('fname',$first_name);
$this->session->set_userdata('grade',$grade);
$this->session->set_userdata('pts',$points);
$this->getImg();
redirect('home');
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found'); }
}
View
<?php if(isset($_SESSION['success'])) :?>
<div class="alert alert-success"><?=$_SESSION['success'];?></div>
<?php endif; if(isset($_SESSION['error'])) :?>
<div class="alert alert-warning"><?=$_SESSION['error'];?></div>
<?php endif;?>
<!-- End alerts -->
<form action="<?php echo base_url();?>index.php/User/login" method="post" accept-charset="utf-8">
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="email" placeholder="Email">
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control"name="password" placeholder="Password">
<?php echo form_error('password'); ?>
</div>
<div class="form-group">
<button class="btn btn-sm btn-success" type="submit" align="center" name="login" class="submit">Log in</button>
</div>
</div>
</form>
model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email'=>$email));
if($query->num_rows() == 1 )
{
return $query->result();
}
}
Upon trying to log in, I got the error page cant be found. I want it to go to the home page if the session is correct. here is the error message:
404 Page Not Found
The page you requested was not found.
How can I solve the error because I have also set as needed in the routes
I think your form action should be <?php echo base_url(); ?>user/login
Also in your model you're not checking for password anywhere.
You're also not returning anything if the email is not found or more than 1 results are found -
($query->num_rows() == 1)
Model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email' => $email, 'password' => $password))->result(); // you should use row() here to return only 1 row.
return $query; // you should check the uniqueness of email on registration, not here -- not allow duplicate email on registration
}
Controller
public function login(){
$email = $_POST['email']; // $this->input->post('email');
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if( !empty($data) ) // if no result found it'll be empty
{
// your code
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found');
}
}
See, if this helps you.

(The POST method is not supported for this route. Supported methods: GET, HEAD.) laravel solution?

I'm new to laravel and I want to submit a registration user form that when clicked, data will be sent to my database (which is already configured) and the page will be directed to the login page but when I click submit button laravel, it says
"The POST method is not supported for this route. Supported methods: GET, HEAD."
I've searched a lot but i am clueless as i don't understand what to do.
My registration view
<?php
// Include config file
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: /");
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>
My Routes
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/','LoginController#login');
Route::get('registration','LoginController#registration');
Route::get('welcome','LoginController#welcome');
My Controller (Not sure if this could be the source of the problem but....)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
public function login()
{
return view('login');
}
public function registration()
{
return view('registration');
}
public function welcome()
{
return view('welcome');
}
}
And last but not least my login file which i don't think is necessary but I'll just share as well.
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: /welcome");
exit;
}
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: /welcome");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? Sign up now.</p>
</form>
</div>
</body>
</html>

How to validate a form in Kohana 3.3.1

I'm trying to validate a form but it doesn't show validation errors and if field is empty, it saves. How to validate form?
My code is:
public function action_upload()
{
if($_POST) {
$name = array(
'name' => Arr::get($_POST, 'name')
);
$validate = Validation::factory($name)
->rule('name', 'not_empty');
try {
$save = Model_Offers::Save($this->user['user_id'], $name);
}
catch (ORM_Validation_Exception $e)
{
$result = $e->errors('models');
echo '<pre>';
print_r($result);
exit;
}
}
}
My view is:
<form id="myForm" action="<?php echo URL::base()?>user/upload" method="post" enctype="multipart/form-data">
<div class="input-group">
<label for="file">Name: </label>
<input type="text" name="name" id="name"><br>
</div>
</form>
You created the validation object, but you forgot to actually apply the rules you assigned. Simply do this by calling
$validate->check()
It'd be best to put this in an if-else statement
if($validate->check()){
//Save object
}
else{
//Get errors (use $validate->errors())
}
Hope that helps! :)

"Unable to load the requested file: search_result.php" error

i want create a search box , where we input student name then show all records of that students.my controller code is
public function search_function_in_controller()
{
if ($this->session->userdata('admin_login') != 1)
redirect('login', 'refresh');
$keyword = $_POST['keyword']; // you can also use $this->input->post('keyword');
$data['search_result'] = $this->crud_model->search($keyword);
$this->load->view('search_result', $data);
}
my model is :
function search($keyword)
{
$this->db->like('name',$keyword);
$query = $this->db->get('student');
return $query->result();
}
my view is :
<body>
<form action="<?=site_url('admin/search_function_in_controller')?>" method="post">
search: <input type="text" name="keyword" />
<input type="submit" value="Submit" />
</form>
<div>
<?php
// List up all results.
foreach ($results as $val)
{
echo $val['username'];
}
?>
</div>
</div>
</body>
but when we give input on search box then it give "Unable to load the requested file: search_result.php" , can anyone help me??
Verify the path that you've called in your view.
I think you intended to call the view admin/search_result in your function search_function_in_controller;

CodeIgniter show errors individually next to form field with ajax callback

I'd made a form using CI and have a native form_validation() library to validate each fields input, I using jQuery post to callback the input to check whether each fields is valid, how if I want each error to populate into form_error() next to each field instead of validation_errors()?
Please refer to below:
view:
<script>
$("#btnregister").click(function() {
var parameters = $("#reg_form").serialize();
$.post(baseurl+'pages/registration', parameters, function(data) {
if(data == "ok") {
//show success message
}else{
$("#error").html(data);
}
}, "html");
});
</script>
<div id="error"></div>
<form id="reg_form" method="post">
<p>
<label for="reg_username">Username</label><br />
<input type="text" id="reg_username" name="reg_username" value="<?php echo set_value('reg_username'); ?>">
<?php echo form_error('reg_username'); ?>
</p>
<p>
<label for="reg_email">Email</label><br />
<input type="text" id="reg_email" name="reg_email" value="<?php echo set_value('reg_email'); ?>">
<?php echo form_error('reg_email'); ?>
</p>
<p><input type="button" id="btnregister" value="Register"></p>
</form>
</div>
Controller:
public function registration(){
$this->load->library('form_validation');
$this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
$this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
if($this->form_validation->run() == FALSE){
echo validation_errors();
}else{
// insert to db
echo "ok";
}
}
Thanks for help.
You'll have to build your own error array. It would be nice if we could access the
Form_validation's $_error_array but unfortunately it's protected and there's no access method for it.
I'm going to change your controller to output a json response to make this easier:
public function registration()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
$this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
if ($this->form_validation->run())
{
$response['status'] = TRUE;
}
else
{
$errors = array();
// Loop through $_POST and get the keys
foreach ($this->input->post() as $key => $value)
{
// Add the error message for this field
$errors[$key] = form_error($key);
}
$response['errors'] = array_filter($errors); // Some might be empty
$response['status'] = FALSE;
}
// You can use the Output class here too
header('Content-type: application/json');
exit(json_encode($response));
}
Now your ajax success callback can read the status and errors keys of the response. You can loop through data.errors and add each one to the input field:
$("#reg_form").submit(function() {
var form = $(this);
$.post(baseurl+'pages/registration', form.serialize(), function(data) {
if (data.status == true) {
//show success message
}else{
$.each(data.errors, function(key, val) {
$('[name="'+ key +'"]', form).after(val);
});​
}
}, "json");
});
Another easy way is to post the form to itself, and have your ajax response reload the entire form - that way the messages and validation filters will be taken care of server-side.

Resources