Error: page requested not found codeigniter - 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.

Related

Redirect customer to product page from where customer logged in to website Magento 2

In Magento 2, I have a custom login form in Header.
If a customer is on the product page for eg :
http://www.testwebsite.com/catalog/product/view/id/10
and login from header form then customer should redirect to the same product page instead of Customer Dashboard.
I have tried plugin code from this link.
Below is my custom header form code -
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl = $urlInterface->getCurrentUrl();
if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
<form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
<input name="form_key" value="" type="hidden">
<div class="header-login" style="">
<span>Email</span>
<input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
</div>
<div class="header-login">
<span>Password</span>
<input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">
</div>
<div class="header-login1">
<button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
</div>
</form>
Reset Your Password?
</div>
<?php } ?>
Plugin Code -
<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{
/**
* Change redirect after login to home instead of dashboard.
*
* #param \Magento\Customer\Controller\Account\LoginPost $subject
* #param \Magento\Framework\Controller\Result\Redirect $result
*/
public function afterExecute(
\Magento\Customer\Controller\Account\LoginPost $subject,
$result)
{
$result->setPath('/'); // Change this to what you want
return $result;
}
}
I want to redirect the customer to $currenturl. Link tutorial can be able to redirect to the home page. Please suggest what needs to be done to achieve to redirect the customer to the current page.
Try the below:
Header Login Form :-
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl = $urlInterface->getCurrentUrl();
if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
<form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
<input name="form_key" value="" type="hidden">
<input type="hidden" name='referer' value="<?php echo $currenturl ?>">
<div class="header-login" style="">
<span>Email</span>
<input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
</div>
<div class="header-login">
<span>Password</span>
<input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">
</div>
<div class="header-login1">
<button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
</div>
</form>
Reset Your Password?
</div>
<?php } ?>
Plugin Code : -
<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{
protected $request;
public function __construct(
\Magento\Framework\App\RequestInterface $request
) {
$this->request = $request;
}
public function getPostReferer()
{
return $this->request->getPostValue('referer');
}
/**
* Change redirect after login to home instead of dashboard.
*
* #param \Magento\Customer\Controller\Account\LoginPost $subject
* #param \Magento\Framework\Controller\Result\Redirect $result
*/
public function afterExecute(
\Magento\Customer\Controller\Account\LoginPost $subject,
$result)
{
$result->setPath($this->getPostReferer());
return $result;
}
}
Please try with the following code I have set the current url to the instant of $resultRedirect like this : $resultRedirect->setUrl($currenturl);
<?php
namespace Vendor\Module\Controller\Account;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Catalog\Api\ProductRepositoryInterface;
class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {
public function execute() {
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$sku = '24-MB01'; //Edit as per your product sku
$_product = $this->productRepository->get($sku);
$currenturl = $_product->getProductUrl();
if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
/** #var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
//$resultRedirect->setPath('home');
$resultRedirect->setUrl($currenturl);
return $resultRedirect;
}
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
$this->session->setCustomerDataAsLoggedIn($customer);
$this->session->regenerateId();
} catch (EmailNotConfirmedException $e) {
$value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
$message = __(
'This account is not confirmed.' .
' Click here to resend confirmation email.', $value
);
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (AuthenticationException $e) {
$message = __('Invalid login or password.');
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (\Exception $e) {
$this->messageManager->addError(__('Invalid login or password.'));
}
} else {
$this->messageManager->addError(__('A login and a password are required.'));
}
}
$resultRedirect = $this->resultRedirectFactory->create();
//$resultRedirect->setPath('home');
$resultRedirect->setUrl($currenturl);
return $resultRedirect;
}
}
If you have a plugin that receives the Magento\Customer\Controller\Account\LoginPost object you could get the referer URL like : $subject->_redirect->getRefererUrl(). Then return this URL
$productURL = $subject->_url->getUrl($subject->_redirect->getRefererUrl());
return $subject->_redirect($productURL);
I'm not 100% sure if this URL will actually be the URL you want but worth a try.

Can't log in to admin dashboard

My password and username are correct, but I can't login to admin. Is there anything wrong with my controller?
This is my model:
class login_model extends CI_Model{
function cek($username, $password){
$this->db->where("username", $username);
$this->db->where("password", $password);
return $this->db->get("user_admin");
}
function getLoginData($usr, $psw){
$u = $usr;
$p = md5($psw);
$q_cek_login = $this->db->get_where('user_admin', array('username' => $u, 'password' => $p));
if(count($q_cek_login->result()) > 0){
foreach($q_cek_login->result() as $qck){
foreach($q_cek_login->result() as $qad){
$sess_data['logged_in'] = TRUE;
$sess_data['id'] = $qad->id;
$sess_data['username'] = $qad->username;
$sess_data['password'] = $qad->password;
$sess_data['email'] = $qad->email;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
redirect('welcome_message');
}
}else{
$this->session->set_flashdata('result_login'. 'username dan password salah');
header('location: '. base_url(). 'login');
}
}
}
This is my controller:
class login extends CI_Controller {
function _construct(){
parent::_construct();
if($this->session->userdata('username')){
redirect(base_url('welcome_message'));
}
$this->load->model(array('login_model'));
}
function index(){
$this->load->view('login');
}
function proses(){
$this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if($this->form_validation->run() == FALSE){
$this->load->view('login');
}else{
$usr = $this->input->post('username');
$psw = $this->input->post('password');
$u = $usr;
$p = md5($psw);
$cek = $this->login_model->cek($u, $p);
if($cek->num_rows() > 0 ){
foreach($cek->result() as $qad){
$sess_data['id'] = $qad->id;
$sess_data['email'] = $qad->email;
$sess_data['username'] = $qad->username;
$sess_data['level']=$qad->level;
$this->session->set_userdata($sess_data);
}
$this->session->set_flashdata('success', 'login berhasil');
redirect(base_url('/'));
}else{
$this->session->set_flashdata('result_login', 'username dan password yang anda masukkan salah');
redirect(base_url('login'));
}
}
}
My view:
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="<?php echo base_url('login/proses'); ?>" method="post">
<?php if (validation_errors() || $this->session->flashdata('result_login')) { ?>
<div class="alert alert-danger animated fadeInDown" role="alert">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Peringatan!</strong>
<?php echo validation_errors(); ?>
<?php echo $this->session->flashdata('result_login'); ?>
</div>
<?php } ?>
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Username" id="username" name="username">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" id="password" name="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
Register a new admin
</div>
When I try to log in, I always get this error:
I don't see anything strikingly wrong with your code.
Well you are obviously hitting your last nested else which means for some reason this statement $cek->num_rows() > 0 is evaluating to false.
I assume that you are entering a proper and existing username + password combination. But to troubleshoot you can after $p = md5($psw); do:
echo 'hashed password: ' . $p . '<br>username: ' . $u; exit;
and see if the username and hashed password match something in the database, if not, you have your answer. My best guess is that you perhaps didn't store a hashed password and only plain-text one.
As a side note you should move all of your redirects and flashdata out of your model. Models should only return or throw Exceptions.

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! :)

Search is not working in codeigniter

i did search like this but it is not taking passed value in text box,can any one help me to solve this issue..thanks in advances........my model query is correct or any error is there......
if i enter in search term it is redirecting to search results page but it is showing blank results.......and it is saying invalid argument supplied for foreach()
if i print last_query() in that it is showing Like below.....
SELECT * FROM (`clients`) WHERE `clientName` LIKE '%%'
This is My Controller:
class Client extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model("client_model");
$this->load->model("interview_model");
$this->load->model("candidate_model");
$this->load->model("requirement_model");
}
function search()
{
$search_term = $this->input->post('search');
$data['query'] = $this->client_model->search_client($search_term);
echo "<pre>"; print_R($this->db->last_query()); exit;
$data['page_title'] = "Search Results";
$this->layout->view("client/search",$data);
}
}
Model:
function search_client($search_term)
{
$this->db->select('*');
$this->db->from('clients');
$this->db->like('clientName',$search_term);
// Execute the query.
$query = $this->db->get();
// Return the results.
return $query->result_array();
}
This is form in index.php(View):
<form action="<?php base_url();?>client/search">
<input type="text" name="search" id="search" style="width:180px" placeholder="Search here..." />
<input type="submit" value="Search" name="submit" class="btn btn-primary btn-sm" /></form>
This is search.php(view):
<?php foreach($query as $client){ ?>
<tr>
<td><?php echo $client->clientName;?></td>
<td><?php echo $client->clientSName; ?></td></td>
<td>
<?php } ?>
change this line:
<form method="POST" action="<?php base_url();?>client/search">
to this:
<form action="<?php echo base_url();?>client/search">
and try the following approch:
function search_client($search_term){
$this->db->select('*');
$this->db->from('clients');
$this->db->like('clientName',$search_term);
// Execute the query.
$query = $this->db->get();
if($query->num_rows()>0)
return $query->result();
else
return false;
}

Joomla Component not saving data

I have a component that used to work (Without setting HTML tags to the description) and now after trying to get the HTML formatting to work it won't save.
com_lot\views\lot\tmpl\form.php:
<?php defined('_JEXEC') or die('Restricted access');
$document =& JFactory::getDocument();
$document->addScript('includes/js/joomla.javascript.js');
require_once(JPATH_ADMINISTRATOR .DS. 'components' .DS. 'com_jce' .DS. 'helpers' .DS. 'browser.php');
?>
<form action="index.php" method="post" name="adminForm" id="adminForm">
<script language="javascript" type="text/javascript">
function submitbutton(pressbutton) {
var form = document.adminForm;
if (pressbutton == 'cancel') {
submitform( pressbutton );
return;
}
<?php
$editor =& JFactory::getEditor();
echo $editor->save( 'description' );
?>
submitform(pressbutton);
}
</script>
...
<tr>
<td width="100" align="right" class="key">
<label for="description">
<?php echo JText::_( 'Description' ); ?>:
</label>
</td>
<td>
<?php
$editor =& JFactory::getEditor();
echo $editor->display('description', $this->lotdata->description, '550', '400', '60', '20', false);
?>
</td>
</tr>
...
<input type="hidden" name="option" value="com_lot" />
<input type="hidden" name="lotid" value="<?php echo $this->lotdata->lotid; ?>" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="controller" value="lot" />
<?php echo JHTML::_( 'form.token' ); ?>
<button type="button" onclick="submitbutton('save')"><?php echo JText::_('Save') ?></button>
<button type="button" onclick="submitbutton('cancel')"><?php echo JText::_('Cancel') ?></button>
</form>
com_lot\models\lot.php:
function store($data)
{
// get the table
$row =& $this->getTable();
// Bind the form fields to the hello table
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Make sure the hello record is valid
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Store the web link table to the database
if (!$row->store()) {
$this->setError( $row->getErrorMsg() );
return false;
}
return true;
}
function save()
{
// Check for request forgeries
JRequest::checkToken() or jexit( 'Invalid Token' );
// get the model
$model =& $this->getModel();
//get data from request
$post = JRequest::get('post');
$post['description'] = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
// let the model save it
if ($model->store($post)) {
$message = JText::_('Success');
} else {
$message = JText::_('Error while saving');
$message .= ' ['.$model->getError().'] ';
}
$this->setRedirect('index.php?option=com_lot', $message);
}
Any help appreciated.
Edit: I have seen stuff about JForms and having XML files... is this applicable? I haven't found anywhere that says what they're used for, just what types there are...
I found the problem (once I'd cleaned up the code a bit) was that in the article I was following (http://docs.joomla.org/How_to_use_the_editor_in_a_component) missed changing store() to store($data).
Because the pages redirect etc it doesn't die and error out. Thanks to for Jan for your help.

Resources