CodeIgniter + Wamp: Unable to locate the file error - php

I just installed a fresh installation of Wamp server and copied a working CodeIgniter project(not done by me) into it. I have changed the settings in config.php(base_url) and database.php(mysql credentials) and am sure that the database connection is ok.
i can see the login page but when i login, it returns me the "unable to locate the file error", i believe its some settings on the Wamp server i need to do. there is no .htaccess file in the root CI folder, should there be? any suggestions what might went wrong?
in the controllers folder there is an admin.php file
<?php
class Admin extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->lang->load($this->config->item('admin_language'), $this->config->item('admin_language'));
}
private $rules = array(
array(
'field' => 'username',
'label' => 'lang:username',
'rules' => 'trim|required',
),
array(
'field' => 'password',
'label' => 'lang:password',
'rules' => 'trim|required|min_length[8]',
)
);
function index()
{
$this->load->library('form_validation');
$redirect_to = $this->config->item('base_url') . 'index.php/admin/products/';
if ($this->auth->logged_in() == FALSE)
{
$data['error'] = FALSE;
$this->load->library('form_validation');
$this->form_validation->set_rules($this->rules);
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
//echo "1";die;
if ($this->form_validation->run() == FALSE)
{
//echo "if";die;
$this->load->view('admin/login', $data);
}
else
{
//echo "el";die;
$this->auth->login($this->input->post('username'), $this->input->post('password'), $redirect_to, 'index.php/admin/login');
}
}
else
{
//echo "asdadad";die;
redirect($redirect_to);
}
}
function logout()
{
$this->auth->logout($this->config->item('base_url') . 'index.php/admin');
}
}
?>

Please change you function name index to login.
If you are using function name index then url will we localhost/projectname/index.php/admin
If you change function name to login then this will we work.

Related

Codeigniter 3.x Login with Form Validation -Boiler plate

I have been reading couple of questions here from different newbies about Login and validation in codeigniter, some have mixed JavaScript and J-query. Codeigniter itself provide a robust form validation along with custom error setting support. I have decided to share with you the easiest way to kickstart in codeigniter with login boilerplate which I have created and I am sharing it with you. It has
Controller
Login
Model: Login_model
Views: Login and success
And basic configurations
Step-1
Download Codeigniter 3.x from Official Website
Step-2
Extract in a folder in your localhost root. (htdocs in xampp and www in wamp)
Step-3. Configuration
Open the folder you have extracted the codeigniter in go to
application->config->autoload.php. Go to line 55 and autoload these two libraries
$autoload['libraries'] = array('database', 'session');
Go to line 67 and load two helpers
$autoload['helper'] = array('url', 'file');
Save the file and now go the application->config->config.php
Set Base URL on line 19 as
$config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/folder_name/';
On line 31 remove the index.php from value and change it to
$config['index_page'] = '';
on line 49 set uri_protocol from AUTO to REQUEST_URI
$config['uri_protocol'] = 'REQUEST_URI';
on line 229 set an encryption key
$config['encryption_key'] = '!##$%^&*()ASDFGHJKL:ZXCVBNM<>QWERTYUIOP';
// I recommend you create a hash and place it here
Save the file
Step-4 .htaccess
On the root of codeigniter installation folder create an .htaccess file write following in it and save
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Step-5. Create Database
Open your phpmyadmin or mysql terminal create a database , create a table users in it , you can use following query
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`fullname` varchar(50) NOT NULL,
`status` enum('pending','approved') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step -6. Connecting Database to Codeigniter
Go to application->config->database.php. Assuming its a fresh install and you haven't created any environments. Go to line 52 and change the four lines to
$db['default']['username'] = 'username'; // will be root if you have xampp
$db['default']['password'] = 'password'; // will be empty if you haven't set
$db['default']['database'] = 'your_database_name';
$db['default']['dbdriver'] = 'mysqli'; // changed from mysql to mysqli
Step-7. The View
Source Code
Step-8. The Controller
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Login_model');
$this->load->library('form_validation');
}
public function index()
{
if($this->isLoggedin()){ redirect(base_url().'login/dashboard');}
$data['title']='Login Boiler Plate';
if($_POST)
{
$config=array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == false) {
// if validation has errors, save those errors in variable and send it to view
$data['errors'] = validation_errors();
$this->load->view('login',$data);
} else {
// if validation passes, check for user credentials from database
$user = $this->Login_model->checkUser($_POST);
if ($user) {
// if an record of user is returned from model, save it in session and send user to dashboard
$this->session->set_userdata($user);
redirect(base_url() . 'Login/dashboard');
} else {
// if nothing returns from model , show an error
$data['errors'] = 'Sorry! The credentials you have provided are not correct';
$this->load->view('login',$data);
}
}
}
else
{
$this->load->view('login',$data);
}
}
public function change_password()
{
if($this->isLoggedin()){
$data['title']='Change Password';
if($_POST)
{
$config=array(
array(
'field' => 'old_password',
'label' => 'Old Password',
'rules' => 'trim|required|callback_checkPassword'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
),
array(
'field' => 'conf_password',
'label' => 'Confirm Password',
'rules' => 'trim|required|matches[password]'
)
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == false)
{
// if validation has errors, save those errors in variable and send it to view
$data['errors'] = validation_errors();
$this->load->view('change_password',$data);
}
else
{
// if validation passes, check for user credentials from database
$this->Login_model->updatePassword($_POST['password'],$this->session->userdata['id']);
$this->session->set_flashdata('log_success','Congratulations! Password Changed');
redirect(base_url() . 'Login/dashboard');
}
}
else
{
$this->load->view('change_password',$data);
}
}
else
{
redirect(base_url().'Login');
}
}
public function dashboard()
{
if($this->isLoggedin())
{
$data['title']='Welcome! You are logged in';
$this->load->view('success',$data);
}
else
{
redirect(base_url().'Login');
}
}
public function logout()
{
$this->session->sess_destroy();
redirect(base_url().'Login');
}
public function isLoggedin()
{
if(!empty($this->session->userdata['id']))
{
return true;
}
else
{
return false;
}
}
}
Step-8. The Model
class Login_model extends CI_Model{
function __construct(){
parent::__construct();
}
public function checkUser($data)
{
$st=$this->db->SELECT('*')->from('users')
->WHERE('username',$data['username'])
->WHERE('password',sha1(md5($data['password'])))
->get()->result_array();
if(count($st)>0)
{
return $st[0];
}
else
{
return false;
}
}
public function checkPassword($str)
{
$st=$this->db->SELECT('*')->from('users')
->WHERE('id',$this->session->userdata['id'])
->WHERE('password',sha1(md5($str)))
->get()->result_array();
if(count($st)>0)
{
return true;
}
else
{
return false;
}
}
public function updatePassword($password,$id)
{
$pass=array(
'password' => sha1(md5($password))
);
$this->db->WHERE('id',$id)->update('users',$pass);
}
}
Step-9. Testing
Open Database in Phpmyadmin and insert sample data in to your table using following query
INSERT INTO `users` (`id`, `username`, `password`, `fullname`, `status`)
VALUES
(1, 'john', '56f5950b728849d0b97c1bccf1691c090ab6734c', 'John Vick',
'approved');
Test-1
Empty Submit
It will produce the error, which we are storing in an errors index in Controller, passing it to view and displaying it in the view if the value exists.
Test-2. Wrong Credentials
Provide any username and password (random)
Test-3. Correct Credentials
Username: john
Password: john
Success View Source Code
ALERTS!!
This is a basic code for kick starters and there is a lot more room for improvements like Security Features and Encryption
Complete Source Code
You can download the complete source code from Git at Boiler-Plates-Codeigniter-3.x-Login

CodeIgniter - A session had already been started - ignoring session_start()

I keep getting this error:
A PHP Error was encountered
Severity: Notice
Message: A session had already been started - ignoring session_start()
Filename: Session/Session.php
Line Number: 140
On a page with this code:
<body>
<p>LOGIN<p>
<?php echo $this->session->userdata('Username'); ?>
</body>
There is no session_start() on the page.
The only thing I can think has caused this is in autoload.php i have done this:
$autoload['libraries'] = array('database','session');
What is causing this error?
Edit: Login controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_controller extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('User_model','',TRUE);
}
function index() //Default function that is run when this controller is called.//
{
$this->load->helper(array('form'));
$this->load->view('Login_view');
}
function Login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('Username', 'Username', 'trim|required');
$this->form_validation->set_rules('Password', 'Password', 'trim|required|callback_CheckDatabase');
if($this->form_validation->run() == FALSE)
{
$this->load->view('Login_view'); //Reloads the login view with validation errors if the login attempt is unsuccessful.//
}
else
{
redirect('Home_controller'); //Redirect to the homepage on successful login attempt.//
}
}
function CheckDatabase($password) //This function is only run when password validation is correct.//
{
$username = $this->input->post('Username'); //Sets the username as a $username.//
$result = $this->User_model->Login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array( //Makes an array of the data to be stored in the session.//
'UserID' => $row->UserID,
'Username' => $row->Username
);
$this->session->set_userdata('logged_in', $sess_array); //Sets $sess_array as the session.//
}
return TRUE;
}
else //Ran if the username or password aren't matched in the CIUsers database. Returns error message.//
{
$this->form_validation->set_message('CheckDatabase', 'Invalid login details.');
return false;
}
}
}
?>
Change this to
$this->session->set_userdata('logged_in', $sess_array);
this
$this->session->set_userdata($sess_array);
Example of Adding Codeigniter Session
Method 01
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
//$newdata = array(
// 'UserID' => $row->UserID,
// 'Username' => $row->Username,
// 'logged_in' => TRUE
// );
$this->session->set_userdata($newdata);
Method 02
$this->session->set_userdata('some_name', 'some_value');
// $this->session->set_userdata('my_name', 'user3574766');
This problem occurs when your PHP.INI file has session.autostart turned on. You'll need to turn this off by:
Editing your PHP.INI file and setting it to off -- or contacting your web hosting provider to do this for you
Placing a .htaccess file in the root of your web directory with the following value:
php_flag session.auto_start 0
hope this helps.

CodeIgniter 3 - Callable Form Validation by Config file not working

I am unable to get the callable form validation feature of CodeIgniter 3 to work when the validation rules are placed in a separate config file.
I am getting the following error message:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: CI_Config::$form_validation_callback_library
The config file with the form validation rules are as follows (config/fvalidation.php):
$config['client_details'] = array(
array(
'field' => 'client_abn',
'label' => 'Client ABN',
'rules' => array('trim', 'required', array('abn_callable', array($this->form_validation_callback_library, 'abn_check'))),
'errors' => array('abn_callable' => 'Invalid ABN has been entered %s.')
)
);
The form validation class attempting to be called is (i.e. $this->form_validation_callback_library):
class Form_validation_callback_library
{
public function abn_check()
{
$this->load->library('abn_validator');
$abn = $this->input->post_get('abn', TRUE);
if (!$this->abn_validator->isValidAbn($abn)) {
return FALSE;
}
return TRUE;
}
}
The controller is:
$this->config->load('fvalidation');
$validation_rules = $this->config->item('client_details');
$this->form_validation->set_rules($validation_rules);
if ($this->form_validation->run() == FALSE) {
// show form
} else {
// process form data
}
Any help would be greatly appreciated.
Cheers,
VeeDee
I would use codeigniter callback example below callback
http://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods
<?php
class Example extends CI_Controller {
public function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('client_abn', 'ABN Number', 'required|callback_checkabn');
if ($this->form_validation->run() == FALSE) {
$this->load->view('something');
} else {
// Redirect to success page i.e login or dashboard or what ever
redirect('/'); // Currently would redirect to home '/'
}
}
public function checkabn() {
$this->load->library('abn_validator');
$abn = $this->input->post('abn');
if (!$this->abn_validator->isValidAbn($abn)) {
$this->form_validation->set_message('checkabn', 'Invalid ABN has been entered %s.');
return FALSE;
} else {
return TRUE;
}
}
}
And on your view in or above form add
<?php echo validation_errors('<div class="error">', '</div>'); ?>
<form action="<?php echo base_url('example');?>" method="post">
<input type="text" name="client_abn" placeholder="" value="" />
</form>
This is a most common problem we face when we run custom form validation in CI. Whether the callback function is in the same controller or it is in the a library of callback function we need to pass the accessible object of the class containing the callback function.
So when your run the
$callable_validations = new Form_validation_callback_library();
$this->form_validation->run($callable_validations)
Looks like this is not possible currently on CodeIgniter 3.
I have created a crude workaround.. so please go ahead an improve it because it doesn't look pretty :)
Update the config file like so (/config/fvalidation.php):
$config['client_details'] = = array(
array(
'field' => 'client_abn',
'label' => 'Client ABN',
'rules' => array('trim', 'required', array('abn_callable', array("library:form_validation_callback_library", 'abn_check'))),
'errors' => array('abn_callable' => 'Invalid %s has been entered .')
)
);
Note the following line in the config file above as we will be using them as flags in the controller code:
array('abn_callable', array("library:form_validation_callback_library", 'abn_check'))
The Library is pretty much the same except we load the instance (/libraries/Form_validation_callback_library.php):
class Form_validation_callback_library
{
private $_CI;
function Form_validation_callback_library() {
$this->_CI =& get_instance();
log_message('info', "Form_validation_callback_library Library Initialized");
}
public function abn_check($abn)
{
$this->_CI->load->library('abn_validator');
if (!$this->_CI->abn_validator->isValidAbn($abn)) {
return FALSE;
}
return TRUE;
}
}
In the controller we load the library (/controllers/Foo.php):
// load the config file and store
$this->config->load('fvalidation', TRUE);
$rule_dataset = $this->config->item('client_details', 'fvalidation');
// search and load the 'callable' library
foreach ($rule_dataset as $i => $rules) {
if (isset($rules['rules'])) {
foreach ($rules['rules'] as $k => $rule) {
if (is_array($rule) && preg_match("/_callable/",$rule[0]) && isset($rule[1][0])) {
list ($load_type, $load_name) = explode(":", $rule[1][0]);
// load the library
$this->load->$load_type($load_name);
$rule_dataset[$i]['rules'][$k][1][0] = $this->$load_name;
}
}
}
}
// set the rules
$this->form_validation->set_rules($rule_dataset);
// load the form
if ($this->form_validation->run() == FALSE) {
// show form
} else {
// process form data
}
I did something similar to Vidura, but extended the Form Validation library by adding MY_Form_validation.php with the following code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class GS_Form_validation extends CI_Form_validation {
public function set_rules($field, $label = '', $rules = array(), $errors = array())
{
if (is_array($rules))
{
foreach ($rules as &$rule)
{
if (is_array($rule))
{
if (is_array($rule[1]) and is_string($rule[1][0]))
{
// handles rule like ['password_check', ['library:passwords', 'check_valid_password']]
// You would set_message like $this->form_validation->set_message('password_check', 'Incorrect password');
// The advantage of defining the rule like this is you can override the callback functions error message
list ($load_type, $load_name) = explode(":", $rule[1][0]);
$CI =& get_instance();
$CI->load->$load_type($load_name);
$rule[1][0] = $CI->$load_name;
}
else if (is_string($rule[0]))
{
// handles rule like ['library:password', 'check_valid_password']
// You would set_message like $this->form_validation->set_message('check_valid_password', 'Incorrect password');
list ($load_type, $load_name) = explode(":", $rule[0]);
$CI =& get_instance();
$CI->load->$load_type($load_name);
$rule[0] = $rule[1];
$rule[1] = [$CI->$load_name, $rule[1]];
}
}
}
}
return parent::set_rules($field, $label, $rules, $errors);
}
}
Then you can define callbacks to library functions like:
$this->form_validation->set_rules(['library:passwords', 'check_valid_password']);
Where passwords is the library and check_valid_password is the method.
I've simply do (config/form_validation.php):
$CI =& get_instance();
$CI->load->model('form_validation_callback_library');
$config['client_details'] = array(
array(
'field' => 'client_abn',
'label' => 'Client ABN',
'rules' => array('trim', 'required', array('abn_callable', array($CI->form_validation_callback_library, 'abn_check'))),
'errors' => array('abn_callable' => 'Invalid ABN has been entered %s.')
)
And it works to me...
I'm running on Codeigniter 3.0.4

CodeIgniter: 404 Page Not Found ( In Hosting Server )

note : everything going well when I try in Localhost.
So I have a problem when I want to call my do_login controller in my login form.
this is my controller :
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Do_login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('login_model', '', TRUE);
}
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'trim|required');
$this->form_validation->set_rules('password', 'password', 'trim|required|callback_check_database');
if($this->form_validation->run() == FALSE)
{
$this->load->view('admin/login_view');
}
else
{
redirect('home', 'refresh');
}
}
public function check_database($password)
{
$email = $this->input->post('email', TRUE);
$result = $this->login_model->check_login($email, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'user_id' => $row->user_id,
'email' => $row->email
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Email / Password salah');
return FALSE;
}
}
}
?>
this is my view :
<?php
$attributes = array('class' => 'form-signin', 'id' => 'myform');
echo form_open('do_login', $attributes);
?>
When I try it in Localhost, everything going well and smooth.
But when I try in my web server, everytime I submit the login form, I directed into 404.
Thanks for your help :)
Check your file names Because it happens with me that different case file name was worked on localhost but not on server.
So check it once.

Add data to the database using codeigniter

I am currently trying to add data to the database using codeigniter. I have already set up a registration page using the active method and attempted to use the same method for the add news form but was unsuccessful.
When I click submit it is saying page cannot be found and the url shows the controller function name. This is the same when i purposely leave any fields blank. I have checked my database and no records have been added and no php log errors.
Here is my snippets of code:
View:
<?php echo form_open('add/add_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Add Article'); ?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
Controller:
class Add extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('admin/add');
}
public function add_article() {
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
$this->load->model('news_model');
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
}
}
}
Model:
public function __construct() {
parent::__construct();
}
function addArticle() {
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username'));
$insert = $this->db->insert('news', $data);
return $insert;
}
}
If it's the server that's throwing the page not found it's almost certainly a URL issue as opposed to a CI/PHP issue.
Is your base url defined properly in the config file? Is your .htaccess configured properly (an old configuration could be routing /add requests away from CI)?
Try adding the following action to the Add controller, and navigating to it directly at http://[base]/add/thetest
public function thetest() {
echo 'Controller accessed';
die;
}
If it still says page not found it's not your code, it's your config (either server config or CI).
Instead of insert use update in your model like:
$insert = $this->db->update('news', $data);
return $insert;
And I think that this part of your code in controller is wrong too (wrong if statement and no data send to model):
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
try this:
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username')
);
$query = $this->news_model->addArticle($data);
if($query)
{
// query ok
$this->load->view('news');
}
else {
// no query
$this->load->view('news');
}

Categories