Captcha value different with session user data - php

I'm trying to create captcha, the image is shown as expected, but when i pass into controller why the string that i input is different with session user data that i set in earlier.
PFB my code.
View.
<?php echo $captcha_img;?>
<input type="text" id="captcha" name="captcha" placeholder="Input Code Above">
<?php echo form_error('captcha', '<p class="field_error">', '</p>');?>
Controller (config)
public function captcha_config() {
$vals = array(
'img_path' => './assets/files/captcha/',
'img_url' => base_url().'assets/files/captcha/',
'img_width' => 150,
'img_height' => 30
);
$cap = create_captcha($vals);
$image = $cap['image'];
$this->session->set_userdata('capt',$cap['word']);
//$data['captcha_img'] = $cap['image'];
return $image;
}
Controller (Index)
public function index() {
if ($this->session->userdata('login') == TRUE)
{
redirect('Buser');
}
else
{
$data['title'] = 'Dashboard';
$data['subtitle'] = 'Log In';
$this->captcha_config();
$data['captcha_img'] = $this->captcha_config();
$this->load->view('Backend/login', $data);
}
Controller (Process)
public function process_login() {
$data['title'] = 'Dashboard';
$data['subtitle'] = 'Log In';
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('captcha', 'Captcha', 'required' );
$this->captcha_config();
$data['captcha_img'] = $this->captcha_config();
if ($this->form_validation->run() == TRUE)
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$captcha = $this->input->post('captcha');
echo $captcha;
echo "<br>";
echo $this->session->userdata('capt');
}
}
result:
Drd27VZE <--- this one is the captcha
VzU90odU <--- this one is the session user data 'capt'
I've been trying using with separate code (example that i got from google) it works, but i don't know why it's not working with this code.

you can create a captcha function in helper
Helper
function generate_captcha()
{
$options = array(
'img_path' => 'img/captcha/',
'img_url' => base_url().'img/captcha/',
'img_width' => '150',
'img_height'=> '50',
'expiration'=> 3600,
'word' => generate_random_password(4)
);
return create_captcha($options);
}
function generate_random_password( $max_length = 8 )
{
$pass = '';
$dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$dict_size = strlen($dict);
for($i = 0;$i<$max_length;$i++){
$pass .= $dict[rand(0,$dict_size-1)];
}
return strtoupper($pass);
}
In your view, you call a generate_captcha if the user put a wrong user ou pass
<?php if( ! empty( $attempts_number ) && ((int)$attempts_number >= 3) ) { ?>
<?php $captcha = generate_captcha(); ?>
<?php $this->session->set_userdata(array(
'captchaword' => $captcha['word']
)); ?>
<?php echo $captcha['image']; ?>
<label><?php echo $this->lang->line('captcha_text'); ?>:</label>
<?php echo form_input(array('class'=>'required','maxlength'=>4,'name'=>'captcha'));?>
<?php } ?>

Finally i solve my problem,
problem when i create function for captcha i don't have to call again in the process function
public function process_login() {
$data['title'] = 'Dashboard';
$data['subtitle'] = 'Log In';
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('captcha', 'Captcha', 'required' );
**$this->captcha_config(); <---- I Remove this one
$data['captcha_img'] = $this->captcha_config(); <---- and also remove this one**
if ($this->form_validation->run() == TRUE)
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$captcha = $this->input->post('captcha');
echo $captcha;
echo "<br>";
echo $this->session->userdata('capt');
}
}

Related

codeigniter login page does not redirect to dashboard

i have a problem in a controller file called "pages.php". After login via login page with correct credentials pages.php does not open dashboard. I doubt that probably the source of this problem may be found in this pages.php
<?php
class Pages extends MY_Controller
{
public function view($page = 'login')
{
if (!file_exists(APPPATH.'views/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
if($page == 'section' || $page == 'subject' || $page == 'student' || $page == 'marksheet' || $page == 'accounting') {
$this->load->model('model_classes');
$data['classData'] = $this->model_classes->fetchClassData();
$this->load->model('model_teacher');
$data['teacherData'] = $this->model_teacher->fetchTeacherData();
$this->load->model('model_accounting');
$data['totalIncome'] = $this->model_accounting->totalIncome();
$data['totalExpenses'] = $this->model_accounting->totalExpenses();
$data['totalBudget'] = $this->model_accounting->totalBudget();
}
if($page == 'setting') {
$this->load->model('model_users');
$this->load->library('session');
$userId = $this->session->userdata('id');
$data['userData'] = $this->model_users->fetchUserData($userId);
}
if($page == 'dashboard') {
$this->load->model('model_student');
$this->load->model('model_teacher');
$this->load->model('model_classes');
$this->load->model('model_marksheet');
$this->load->model('model_accounting');
$data['countTotalStudent'] = $this->model_student->countTotalStudent();
$data['countTotalTeacher'] = $this->model_teacher->countTotalTeacher();
$data['countTotalClasses'] = $this->model_classes->countTotalClass();
$data['countTotalMarksheet'] = $this->model_marksheet->countTotalMarksheet();
$data['totalIncome'] = $this->model_accounting->totalIncome();
$data['totalExpenses'] = $this->model_accounting->totalExpenses();
$data['totalBudget'] = $this->model_accounting->totalBudget();
}
if($page == 'login') {
$this->isLoggedIn();
$this->load->view($page, $data);
}
else{
$this->isNotLoggedIn();
$this->load->view('templates/header', $data);
$this->load->view($page, $data);
$this->load->view('templates/footer', $data);
}
}
}
Please anyone who can edit this code just help. Or if you think the problem is not in pages.php (above page) please advice me how the problem can be solved. I have mentioned more pages:-
This is rootes.php.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
This is MY_Controller.php in core folder
<?php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function isLoggedIn()
{
$this->load->library('session');
if($this->session->userdata('logged_in') === true) {
redirect('../dashboard');
}
}
public function isNotLoggedIn()
{
$this->load->library('session');
if($this->session->userdata('logged_in') != true) {
redirect('../../');
}
}
}
This is Users.php in controllers folder
<?php
class Users extends MY_Controller
{
public function __construct()
{
parent::__construct();
// loading the users model
$this->load->model('model_users');
// loading the form validation library
$this->load->library('form_validation');
}
public function login()
{
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|callback_validate_username'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$login = $this->model_users->login($username, $password);
if($login) {
$this->load->library('session');
$user_data = array(
'id' => $login,
'logged_in' => true
);
$this->session->set_userdata($user_data);
$validator['success'] = true;
$validator['messages'] = "index.php/dashboard";
}
else {
$validator['success'] = false;
$validator['messages'] = "Incorrect username/password combination";
} // /else
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
} // /lgoin function
public function validate_username()
{
$validate = $this->model_users->validate_username($this->input->post('username'));
if($validate === true) {
return true;
}
else {
$this->form_validation->set_message('validate_username', 'The {field} does not exists');
return false;
} // /else
} // /validate username function
public function logout()
{
$this->load->library('session');
$this->session->sess_destroy();
redirect('../../');
}
public function updateProfile()
{
$this->load->library('session');
$userId = $this->session->userdata('id');
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'fname',
'label' => 'First Name',
'rules' => 'required'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$update = $this->model_users->updateProfile($userId);
if($update === true) {
$validator['success'] = true;
$validator['messages'] = "Successfully Update";
}
else {
$validator['success'] = false;
$validator['messages'] = "Error while inserting the information into the database";
}
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
}
public function changePassword()
{
$this->load->library('session');
$userId = $this->session->userdata('id');
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'currentPassword',
'label' => 'Current Password',
'rules' => 'required|callback_validate_current_password'
),
array(
'field' => 'newPassword',
'label' => 'Password',
'rules' => 'required|matches[confirmPassword]'
),
array(
'field' => 'confirmPassword',
'label' => 'Confirm Password',
'rules' => 'required'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$update = $this->model_users->changePassword($userId);
if($update === true) {
$validator['success'] = true;
$validator['messages'] = "Successfully Update";
}
else {
$validator['success'] = false;
$validator['messages'] = "Error while inserting the information into the database";
}
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
}
public function validate_current_password()
{
$this->load->library('session');
$userId = $this->session->userdata('id');
$validate = $this->model_users->validate_current_password($this->input->post('currentPassword'), $userId);
if($validate === true) {
return true;
}
else {
$this->form_validation->set_message('validate_current_password', 'The {field} is incorrect');
return false;
} // /else
}
}
This is login.php in views folder
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
<!-- bootstrap css -->
<link rel="stylesheet" type="text/css"
href="assets/bootstrap/css/bootstrap.min.css">
<!-- boostrap theme -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap-theme.min.css">
<!-- custom css -->
<link rel="stylesheet" type="text/css" href="custom/css/custom.css">
<!-- jquery -->
<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
<!-- boostrap js -->
<script type="text/javascript" src="assets/bootstrap/js/bootstrap.min.js">
</script>
</head>
<body>
<div class="col-md-6 col-md-offset-3 vertical-off-4">
<div class="panel panel-default login-form">
<div class="panel-body">
<form method="post" action="index.php/users/login" id="loginForm">
<fieldset>
<legend>
Login
</legend>
<div id="message"></div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autofocus>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<button type="submit" class="col-md-12 btn btn-primary login-button">Submit</button>
</fieldset>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="custom/js/login.js"></script>
</body>
</html>
login.js
$(document).ready(function(){
$("#loginForm").unbind('submit').bind('submit', function() {
var form = $(this);
var url = form.attr('action');
var type = form.attr('method');
$.ajax({
url : url,
type : type,
data : form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success === true) {
window.location = response.messages;
}
else {
if(response.messages instanceof Object) {
$("#message").html('');
$.each(response.messages, function(index, value) {
var key = $("#" + index);
key.closest('.form-group')
.removeClass('has-error')
.removeClass('has-success')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
key.after(value);
});
}
else {
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
$("#message").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
response.messages +
'</div>');
} // /else
} // /else
} // /if
});
return false;
});
});
Thanks to all, finally I have got a correct answer, the problem was due to the older version of codeignitor in php 7 server, for more info click
Codeigniter session data lost after redirect
Hi I was facing same issue. logs was showing nothing and my apache server got hanged. but in my case issue was with my controller. i did one mistake. i was printing array object in logs. instead of doing array to string conversion. i solved this and redirect function started working.
Just use refresh method, it works for me
$this->load->helper('url);
redirect('foo', 'refresh');

Codeigniter 3 issue with login goes directly to the page with no verification

I have an issue where every time I click on login it just takes me to my page it seems to not be checking to see if the username or password was entered. I am not sure what the issue is I changed the line if ($this->form_validation->run() == FALSE) to true and then I just get redirected back to the login when I enter correct password. I think it is something simple I am just missing. If anyone has an idea any direction would help in the mean time I will keep figuring it out.
Controllers
Verifylogin.php controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
if($this->form_validation->run() == false)
{
//Field validation failed. User redirected to login page
$this->load->view('person_view');
}
else
{
//Go to private area
redirect('Person', 'refresh');
}
}
public function check_database() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_view.php');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->admin_database->login($data);
if($result == TRUE){
$sess_array = array(
'username' => $this->input->post('username')
);
}
}
}
}
Person.php controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Person extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('person_model','callin_list');
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$this->load->view('person_view');
}else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function ajax_list()
{
$list = $this->callin_list->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $callin_list) {
$no++;
$row = array();
$row[] = $callin_list->Date_Scheduled;
$row[] = $callin_list->Employee_Name;
$row[] = $callin_list->Employee_Number;
$row[] = $callin_list->Time_Reported;
$row[] = $callin_list->Reason;
$row[] = $callin_list->Scheduled_Area;
$row[] = $callin_list->Contact;
$row[] = $callin_list->Comments;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void()" title="Edit" onclick="edit_person('."'".$callin_list->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm btn-danger" href="javascript:void()" title="Hapus" onclick="delete_person('."'".$callin_list->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->callin_list->count_all(),
"recordsFiltered" => $this->callin_list->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->callin_list->get_by_id($id);
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'Date_Scheduled' => $this->input->post('Date_Scheduled'),
'Employee_Name' => $this->input->post('Employee_Name'),
'Employee_Number' => $this->input->post('Employee_Number'),
'Time_Reported' => $this->input->post('Time_Reported'),
'Reason' => $this->input->post('Reason'),
'Scheduled_Area' => $this->input->post('Scheduled_Area'),
'Contact' => $this->input->post('Contact'),
'Comments' => $this->input->post('Comments'),
);
$insert = $this->callin_list->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'Date_Scheduled' => $this->input->post('Date_Scheduled'),
'Employee_Name' => $this->input->post('Employee_Name'),
'Employee_Number' => $this->input->post('Employee_Number'),
'Time_Reported' => $this->input->post('Time_Reported'),
'Reason' => $this->input->post('Reason'),
'Scheduled_Area' => $this->input->post('Scheduled_Area'),
'Contact' => $this->input->post('Contact'),
'Comments' => $this->input->post('Comments'),
);
$this->callin_list->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
$this->callin_list->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
//validation section were user must enter data in all fields
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('Date_Scheduled') == '')
{
$data['inputerror'][] = 'Date_Scheduled';
$data['error_string'][] = 'Date_Scheduled is required';
$data['status'] = FALSE;
}
if($this->input->post('Employee_Name') == '')
{
$data['inputerror'][] = 'Employee_Name';
$data['error_string'][] = 'Employee_Name is required';
$data['status'] = FALSE;
}
if($this->input->post('Employee_Number') == '')
{
$data['inputerror'][] = 'Employee_Number';
$data['error_string'][] = 'Employee_Number is required';
$data['status'] = FALSE;
}
if($this->input->post('Time_Reported') == '')
{
$data['inputerror'][] = 'Time_Reported';
$data['error_string'][] = 'Time_Reported is required';
$data['status'] = FALSE;
}
if($this->input->post('Reason') == '')
{
$data['inputerror'][] = 'Reason';
$data['error_string'][] = 'Reason is required';
$data['status'] = FALSE;
}
if($this->input->post('Scheduled_Area') == '')
{
$data['inputerror'][] = 'Scheduled_Area';
$data['error_string'][] = 'Scheduled_Area is required';
$data['status'] = FALSE;
}
if($this->input->post('Contact') == '')
{
$data['inputerror'][] = 'Contact';
$data['error_string'][] = 'contact is required';
$data['status'] = FALSE;
}
if($this->input->post('Comments') == '')
{
$data['inputerror'][] = 'Comments';
$data['error_string'][] = 'Comments is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
login_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
* Description: Login model class
*/
class Login_model extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate(){
// grab user input
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
// Prep the query
$this->db->where('username', $username);
$this->db->where('password', $password);
// Run the query
$query = $this->db->get('users');
// Let's check if there are any results
if($query->num_rows() == 1)
{
// If there is a user, then create session data
$row = $query->row();
$data = array(
'userid' => $row->userid,
'fname' => $row->fname,
'lname' => $row->lname,
'username' => $row->username,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
// If the previous process did not validate
// then return false.
return false;
}
}
?>
login_view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login Form</title>
<style type="text/css">
.content{
margin-left: 400px;
margin-top: 300px;
}
.btn{
width:242px;
height: 50px;
}
#label{
font-size: 24px;
font-weight: normal;
}
</style>
<link href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css')?>" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="content">
<h1>DC399 Callin Login Page</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('verifylogin'); ?>
<label id="label"for="username">Username:</label><br>
<input type="text" size="20" id="username"style="width: 239px; height: 40px; margin-right: 20px;"name="username"/>
<br/>
<label id="label" for="password">Password:</label><br>
<input type="password" size="20" id="passowrd" style="width: 239px; height: 40px; margin-right: 20px;"name="password"/>
<br/><br>
<input class="btn btn-success" type="submit" value="Login"/>
</form>
</div>
</div>
<script src="<?php echo base_url('assets/jquery/jquery-2.1.4.min.js')?>"></script>
<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>"></script>
</body>
</html>
Use $this->form_validation->run() === FALSE instead, with 3 = signs.
You are sending the data to verifylogin/index and any moment are loading the rules to check and validate neither are checking from the database. That's the problem.

PHP Help, not recognizing the different users

I have little knowledge with PHP and I was assigned to try to fix some of the things that don't work in a website. The website basically deals with two different users, a trader who can post articles and a blogger who can post blogs. When a user registers to become a trader and tries to submit an article,the page just redirects to base_url.user/blogger/ instead of base_url.user/trader/. I think this is because it isn't recognizing the user as a trader. Can you please look at the codes? If you have any ideas as to why it wouldn't work I'm open to ideas
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Index Page for this controller.
*
* Since this controller is set as the default controller in
* config/routes.php, it's displayed
*
*
* File Controller; location: application/controllers/admin.php
* Author : Pradeep
* Date : Sunday Feb 5th, 2012
**/
class Register extends CI_Controller {
private $user;
private $logData;
function _Register()
{
parent::controller();
$this->config->load('constants.php');
}
public function blogger()
{
//-------------------------SENDING ERROR MESSAGE FOR LOGIN-------------------
$data['captchaError'] = '';
$data['captcha'] = $this->getCaptcha();
$data['pageTitle']='Registration | Blogger';
$this->load->view('register-blogger',$data);
}
public function trader()
{
$data['captchaError'] = '';
$data['captcha'] = $this->getCaptcha();
$data['pageTitle']='Registration | Trader';
$this->load->view('register-trader',$data);
}
public function activate()
{
$data['pageTitle']='Registration | Succesfully registered';
$this->load->view('register-success',$data);
}
public function process()
{
$date = date('Y-m-d');
$userid = uniqid();
$captchaError = '';
if($this->input->post('Submit'))
{
//---------------------------------FORM VALIDATION STARTS HERE---------------------------------
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fname', 'Full name','required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[tbl_user.email]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[6]|matches[cpassword]');
$this->form_validation->set_rules('cpassword', 'Password confirmation', 'required');
$this->form_validation->set_rules('mycheck[]', 'Buyer or Supplier','required');
$this->form_validation->set_rules('material[]', 'materials','required');
$this->form_validation->set_rules('company', 'Company name', 'required');
$this->form_validation->set_rules('cname', 'Contact name','required');
$this->form_validation->set_rules('cemail', 'Contact email', 'required|valid_email');
$this->form_validation->set_rules('nation', 'Country', 'required');
$this->form_validation->set_rules('city', 'City','required');
$this->form_validation->set_rules('fax');
$this->form_validation->set_rules('mobile');
$this->form_validation->set_rules('phone');
$this->form_validation->set_rules('website');
$this->form_validation->set_rules('address');
$this->form_validation->set_rules('zip');
$this->form_validation->set_rules('content', 'Tell something about urself', 'required');
$this->form_validation->set_rules('captchaText', 'captcha text', 'required');
//-----------------------------------FORM VALIDATION ENDS HERE--------------------------------------
//------------------------------------CAPTCHA CHECK------------------------------------------
if($this->input->post('captchaText'))
{
$expiration = time()-7200; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($_POST['captchaText'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$captchaError = "You must submit the word that appears in the image";
}
}
//--------------------------------------CAPTCHA CHECK ENDS HERE----------------------------
//----------------------------------FORM VALIDATION RETURN ERRORS---------------------------
if ($this->form_validation->run() == FALSE || $captchaError!='')
{
$data['captcha'] = $this->getCaptcha();
$data['captchaError'] = $captchaError;
$data['pageTitle']='Registration | Error';
$this->load->view('register-trader',$data);
}
//-----------------------------------------------END---------------------------------------
//---------------------------------------INSERT DATA INTO DATABASE-----------------------
else
{
if($this->input->post('material'))
{
$material = '';
foreach($this->input->post('material') as $value)
{
$material.= $value.',';
}
$material = rtrim($material,',');
}
$mycheck = $this->input->post('mycheck');
$mycheckOne = '';
$mycheckTwo = '';
if(!empty($mycheck[0])){$mycheckOne = $mycheck[0];}
if(!empty($mycheck[1])){$mycheckTwo = $mycheck[1];}
$config['file_name'] = uniqid();
$config['upload_path'] = UP_PATH;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile1'))
{
$error = $this->upload->display_errors();
$data = array(
'supplier'=>$mycheckOne,
'buyer'=>$mycheckTwo,
'title'=>$this->input->post('company'),
'cname'=>$this->input->post('cname'),
'material'=>$material,
'email'=>$this->input->post('email'),
'phone'=>$this->input->post('phone'),
'fax'=>$this->input->post('name'),
'mobile'=>$this->input->post('mobile'),
'web'=>$this->input->post('website'),
'country'=>$this->input->post('nation'),
'city'=>$this->input->post('city'),
'address'=>$this->input->post('address'),
'zip'=>$this->input->post('zip'),
'content'=>$this->input->post('content'),
'date'=>$date,
'userid'=>$userid,
'status'=>0
);
}
else
{
$data = array('upload_data' => $this->upload->data());
$filepath = $data['upload_data']['file_name'];
$config['image_library'] = 'gd2';
$config['source_image'] = UP_PATH.$filepath;
$config['new_image'] = UP_PATH.'thumbs/';
$config['create_thumb'] = TRUE;
$config['thumb_marker'] = '';
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data = array(
'supplier'=>$mycheckOne,
'buyer'=>$mycheckTwo,
'title'=>$this->input->post('company'),
'cname'=>$this->input->post('cname'),
'material'=>$material,
'email'=>$this->input->post('email'),
'phone'=>$this->input->post('phone'),
'fax'=>$this->input->post('fax'),
'mobile'=>$this->input->post('mobile'),
'web'=>$this->input->post('website'),
'country'=>$this->input->post('nation'),
'city'=>$this->input->post('city'),
'address'=>$this->input->post('address'),
'zip'=>$this->input->post('zip'),
'content'=>$this->input->post('content'),
'image'=>$filepath,
'date'=>$date,
'userid'=>$userid,
'status'=>0
);
}
$this->db->insert(TBL_CLA,$data);
$log_type = 'trader';
$password = do_hash($this->input->post('password'));
$dataOne = array(
'password'=>$this->security->xss_clean($password),
'fname'=>$this->security->xss_clean($this->input->post('fname')),
'email'=>$this->security->xss_clean($this->input->post('email')),
'log_type'=>$log_type,
'userid'=>$userid,
'status'=>0,
'date'=>$date,
'active'=>1
);
$this->db->insert(TBL_USE,$dataOne);
$this->session->set_userdata('fname', $this->input->post('fname'));
redirect(base_url().'register/activate');
}
}
if($this->input->post('Login'))
{
//---------------------------------FORM VALIDATION STARTS HERE---------------------------------
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fname', 'Full name','required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[tbl_user.email]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[6]|matches[cpassword]');
$this->form_validation->set_rules('cpassword', 'Password confirmation', 'required');
$this->form_validation->set_rules('captchaText', 'captcha text', 'required');
//-----------------------------------FORM VALIDATION ENDS HERE--------------------------------------
//------------------------------------CAPTCHA CHECK------------------------------------------
if($this->input->post('captchaText'))
{
$expiration = time()-7200; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($_POST['captchaText'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$captchaError = "You must submit the word that appears in the image";
}
}
//--------------------------------------CAPTCHA CHECK ENDS HERE----------------------------
//----------------------------------FORM VALIDATION RETURN ERRORS---------------------------
if ($this->form_validation->run() == FALSE || $captchaError!='')
{
$data['captcha'] = $this->getCaptcha();
$data['captchaError'] = $captchaError;
$data['pageTitle']='Registration | Error';
$this->load->view('register-blogger',$data);
}
//-----------------------------------------------END---------------------------------------
//---------------------------------------INSERT DATA INTO DATABASE-----------------------
else
{
$date = date('Y-m-d');
$log_type = 'blogger';
$password = do_hash($this->input->post('password'));
$dataOne = array(
'password'=>$this->security->xss_clean($password),
'fname'=>$this->security->xss_clean($this->input->post('fname')),
'email'=>$this->security->xss_clean($this->input->post('email')),
'log_type'=>$log_type,
'userid'=>$userid,
'status'=>0,
'date'=>$date,
'active'=>0
);
$this->db->insert(TBL_USE,$dataOne);
$data['link'] = 'http://www.arabrecycling.org/activate/created/'.$userid;
$data['name'] = $this->input->post('fname');
$message = $this->load->view('includes/activate',$data, TRUE);
$subject = 'Account Activation';
$fromTest = 'The Arab Recycling Initiative';
$this->userRegEmail('info#arabrecycling.org',$this->input->post('email'),$message,$subject,$fromTest);
$this->session->set_userdata('fname', $this->input->post('fname'));
redirect(base_url().'register/activate');
}
}
}
//-------------------------------------------------------CAPTCHA CREATION STARTS HERE------------------------
public function getCaptcha(){
$this->load->library('common');
$this->common = new common();
$this->load->helper('captcha');
$vals = array(
'word' => $this->common->GetRandomCaptchaText(8),
'img_path' => './captcha/',
'img_url' => base_url().'captcha/',
'font_path' => base_url().'system/fonts/Candice.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
$data = array(
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
return $cap['image'];
}
//--------------------------------------------------------CAPTCHA CREATION ENDS HERE------------------------------------------------
//--------------------------------------------------------CONFIGURING EMAIL------------------------------------------------
public function userRegEmail($from,$to,$message,$subject,$fromTest){
$email_config['protocol'] = 'mail';
$email_config['mailtype'] = 'html';
$this->email->initialize($email_config);
$this->email->from($from, $fromTest);
$this->email->to($to);
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
}
//--------------------------------------------------------EMAIL CONFIGURATION ENDS HERE------------------------------------------------
Use SESSIONS:
On top of your page set:
<?php
//Check if session has not been started.
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
?>
In the code when defining a trader or blogger:
$_SESSION['USER'] = "trader";
or
$_SESSION['USER'] = "blogger";
Then you can execute the code you want:
//If it has not been set, do trader by default.
if (!ISSET($_SESSION['USER'])
{
$_SESSION['USER'] = "trader";
}
if ($_SESSION['USER'] == "blogger")
{
//Execute code for blogger
}
else if($_SESSION['USER'] == "trader")
{
//Execute code for trader
}
Sessions are stored in your browser as long as your "Page/Session" is open. Those "Variables" are user specific.
Hope this helps :)
You should identify if a user is a trader or a blogger, and then set appropriate session variables accordingly. A simple if statement to check which is logged in depending on which session variable is set should do the trick? If i'm understanding your question correctly.
What I would suggest (it will probably be easier) is
1. add an attribute to your user table in your database that is Account_Type enum('trader','blogger') not null.
2. Add radio buttons to your form when they sign up to choose if they are a trader or blogger
and obviously have this data sent back to your database
3. When they Login (i'm assuming all users have a unique username) do something like
-Set Session variables to 0
$_SESSION['trader'] = 0;
$_SESSION['blogger'] = 0;
-find username in database and for that username check if trader or blogger.
//A Query to find the Account_type that goes with the input account
$accquery = "SELECT Account_type FROM Account WHERE Account_Name =$_POST['account']";
//Running the query
$result = mysqli_query($connect,$accquery);
//Using an array to fetch the type and put it into a variables place
while($row = mysqli_fetch_array($connect,$result))
{
$acctype = $row['Account_Type'];
}
else {
die("Query failed");
}
And then do something like
if($acctype == "trader") {
$_SESSION['trader'] = 1;
elseif($acctype == "Blogger") {
$_SESSION['blogger'] =1;
else {
//error message
}
and then when you need to check which they are you can do something like
if((isset($_SESSION['trader'])) && ($_SESSION['trader'] == "1")){
//specific code for trader
}
and you can apply the same for blogger.
I would also advise you look into sanitizing your inputs, it's simple but very important.
Also note, do a thorough search through stackoverflow for answers to your questions because more than likely you will find something.
-Hope this helps, note its only rough so you will have to work around it but you should have some grasp of PHP anyways so that should do.

Is there a way to redirect to a specific page using Tank_auth in Codeigniter?

I'm wondering if there's a way to redirect to a specific page (like adminpanel_view) in Tank_auth.
I looked at the Auth.php controller but could not figure out how to redirect, if it's even possible..
I tried this:
(Auth.php)
public function login() //login functie
{
$this->breadcrumbs->page = array('link'=> base_url().'auth/login' ,'title' => 'Login');
$data['breadcrumbs'] = $this->breadcrumbs->get();
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('members/cpanel');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/auth/send_again/');
} else {
$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
$this->config->item('use_username', 'tank_auth'));
$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember me', 'integer');
// Get login for counting attempts to login
if ($this->config->item('login_count_attempts', 'tank_auth') AND
($login = $this->input->post('login'))) {
$login = $this->security->xss_clean($login);
} else {
$login = '';
}
$data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
if ($data['use_recaptcha'])
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
else
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
$data['errors'] = array();
if ($this->form_validation->run()) { // validation ok
if ($this->tank_auth->login(
$this->form_validation->set_value('login'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('remember'),
$data['login_by_username'],
$data['login_by_email'])) { // success
redirect('');
} else {
$errors = $this->tank_auth->get_error_message();
if (isset($errors['banned'])) { // banned user
$this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);
} elseif (isset($errors['not_activated'])) { // not activated user
redirect('/auth/send_again/');
} else { // fail
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
}
$data['show_captcha'] = FALSE;
if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
$data['show_captcha'] = TRUE;
if ($data['use_recaptcha']) {
$data['recaptcha_html'] = $this->_create_recaptcha();
} else {
$data['captcha_html'] = $this->_create_captcha();
}
}
$this->load->view('views/header');
$this->load->view('auth/login_form', $data);
$this->load->view('views/footer');
}
}
make sure you have loaded url_helper before using function base_url, site_url or redirect. and your code could not run, because you missed a brace. it should be
public function login() //login functie
{
$this->load->helper('url');
$this->breadcrumbs->page = array('link'=> site_url('auth/login') ,'title' => 'Login');
$data['breadcrumbs'] = $this->breadcrumbs->get();
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('members/cpanel');
}
}

Simple Codeigniter form validation

I am having some problem in my login form like this
I want to display an individually error beside of each field
here is the controller
function index()
{
$this->form_validation->set_rules('username','Username','trim|required|exact_length[4]|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]|max_length[40]|xss_clean|callback_login');
$this->form_validation->set_rules('jabatan','Jabatan','trim|required|xss_clean');
if($this->form_validation->run() == false)
{
$this->load->view('login');
}
else
{
$this->load->view('welcome_message');
}
}
function login()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$jabatan = $this->input->post('jabatan');
$value = $this->m_login->login($username,$password,$jabatan);
if($value)
{
return true;
}
else
{
$this->form_validation->set_message('login', 'password salah');
//delete redirect() and showing blank white screen
return false;
}
I made the <?php echo form_error(); ?> beside each field
<?php echo form_open('c_login/login'); ?>
<table>
<tr>
<td>Username</td>
<td><?php $inusername=array('name' => 'username', 'class' => 'GUI'); echo form_input($inusername); ?></td>
<td class="error"><?php echo form_error('username'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php $inpassword=array('name' => 'password', 'class' => 'GUI', 'type' =>'password'); echo form_input($inpassword); ?></td>
<td class="error"><?php echo form_error('password'); echo $this->session->flashdata('login'); ?></td>
</tr>
<tr>
<td>Jabatan</td>
<td><?php $injabatan=array('keuangan' => 'keuangan', 'admin' => 'admin', 'hd' => 'head divisi', 'direktur' => 'direktur'); echo form_dropdown('jabatan',$injabatan,'keuangan','class = "gui"'); ?></td>
<td class="error"><?php echo form_error('jabatan'); ?></td>
</tr>
<tr>
<td></td>
<td><?php $insubmit=array('name' =>'login','class' =>'button','value' => 'Login'); echo form_submit($insubmit); echo nbs(); $inreset=array('name' =>'reset','class' =>'button','value' => 'Hapus'); echo form_reset($inreset); ?></td>
<td class="error"><?php echo form_error(); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
How come the form_error() function is not echoing anything when I click login with the username and password field left blank?
you know problem in your validation you're checking validation in index method of your class not in login method of your class and in your form you have given action to ci_login/login method which is redirecting if login is failed and its clearing form validation validate your fields on login method also and put all error message in session and display, i have made some changes in script have look here on this link Code modified
for this changes you have to use url helper
function index()
{
$this->form_validation->set_rules('username','Username','trim|required|exact_length[4]|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]|max_length[40]|xss_clean|callback_login');
$this->form_validation->set_rules('jabatan','Jabatan','trim|required|xss_clean');
if($this->form_validation->run() == false)
{
$this->load->view('login');
}
else
{
//to check if the validation run correctly
//$this->load->view('welcome_message');
$username = $this->input->post('username');
$password = $this->input->post('password');
$jabatan = $this->input->post('jabatan');
$value = $this->m_login->login($username,$password,$jabatan);
if($value)
{
redirect('welcome_message');
//return true;
}
else
{
$this->form_validation->set_message('login', 'password salah');
redirect('c_login',$login); //i want to pass $login into login form, then print
return false; //them as a form_error
}
}
}
<?php echo form_open(uri_string()); ?>
<table>
<tr>
<td>Username</td>
<td><?php $inusername=array('name' => 'username', 'class' => 'GUI'); echo form_input($inusername); ?></td>
<td class="error"><?php echo form_error('username'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php $inpassword=array('name' => 'password', 'class' => 'GUI', 'type' =>'password'); echo form_input($inpassword); ?></td>
<td class="error"><?php echo form_error('password'); echo $this->session->flashdata('login'); ?></td>
</tr>
<tr>
<td>Jabatan</td>
<td><?php $injabatan=array('keuangan' => 'keuangan', 'admin' => 'admin', 'hd' => 'head divisi', 'direktur' => 'direktur'); echo form_dropdown('jabatan',$injabatan,'keuangan','class = "gui"'); ?></td>
<td class="error"><?php echo form_error('jabatan'); ?></td>
</tr>
<tr>
<td></td>
<td><?php $insubmit=array('name' =>'login','class' =>'button','value' => 'Login'); echo form_submit($insubmit); echo nbs(); $inreset=array('name' =>'reset','class' =>'button','value' => 'Hapus'); echo form_reset($inreset); ?></td>
<td class="error"><?php echo form_error(); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
index will not execute when login does.
If appears that maybe you think the set_rules() functions will execute when you submit the form. They won't. The form will submit to 'c_login/login', which is the login() function inside your c_login controller.
You need to move your form validation logic into login(), and have index() just echo the view for the first time.
Your Controller
function index(){
$this->load->view('login');
}
function login(){
$this->form_validation->set_rules('username','Username','trim|required|exact_length[4]|xss_clean');
$this->form_validation->set_rules('password','Password','required|xss_clean|correct');
$this->form_validation->set_rules('jabatan','Jabatan','trim|required|xss_clean');
if($this->form_validation->run() == false){
//your validation messages will be taken care of.
$this->load->view('login');
}
else{
$p = $this->input->post();
if($this->m_login->login($p['username'],$p['password'],$p['jabatan'])){
//redirect() user to logged in area.
}
else{
$this->form_validation->set_message('login', 'password salah');
$this->load->view('login');
}
}
}
Also, you shouldn't be trimming passwords. The space character is a perfectly valid suffix or prefix in a password. I've removed trim for you. I've also removed the min_length and max_length. This is something you'd want to enforce on a signup page, are you sure it really adds any value on a login page?
You need to supply form_error() with the field:
<?php echo form_error('username'); ?>
See more details here
It looks to me that you have a big misunderstanding on how these things work. First of all, you don't need that redirect() call in login(). The redirect() functions will redirect the user to another page, and since neither CodeIgniter nor PHP keep an object between page requests, you'd lose everything (e.g. The form validation object and its error messages).
Also, you might want to prefix that login() method with an underscore (_), so that no one can access it through an HTTP request.
You should probably submit the form to the index() method instead of login(). Then, make sure you only run the validation on a POST request.
function index()
{
if ($_POST)
{
// run validation here
}
// ...
}
**Simple form validation, image upload and captcha using codeigniter libraries**
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Loginmodel');
}
public function index()
{
$config = array(
'img_path' => 'uploadss/',
'img_url' => base_url().'uploadss/',
'font_path' => base_url().'system/fonts/texb.ttf',
'img_width' => '200',
'img_height' => 90,
'word_length' => 3,
'font_size' => 25
);
$captcha = create_captcha($config);
// Unset previous captcha and set new captcha word
$this->session->unset_userdata('captchaCode');
$this->session->set_userdata('captchaCode', $captcha['word']);
// Pass captcha image to view
$fetch['captchaImg'] = $captcha['image'];
$fetch['data'] = $this->Loginmodel->alldata();
$this->load->view('login',$fetch);
}
public function loginerror()
{
$this->form_validation->set_rules('fname','first name','required|alpha');
$this->form_validation->set_rules('lname','last name', 'required');
$this->form_validation->set_rules('mobile', 'Mobile', 'required|numeric');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('companyname', 'Companyname', 'required');
$this->form_validation->set_rules('designation', 'Designation', 'required');
$this->form_validation->set_rules('companysize', 'Companysize', 'required|numeric');
if($this->form_validation->run())
{
$inputCaptcha = $this->input->post('captcha');
$sessCaptcha = $this->session->userdata('captchaCode');
if($inputCaptcha === $sessCaptcha)
{
echo 'Captcha code matched.';
$fname = $this->input->post('fname');
$lname = $this->input->post('lname');
$mobile = $this->input->post('mobile');
$email = $this->input->post('email');
$password = $this->input->post('password');
$companyname = $this->input->post('companyname');
$designation = $this->input->post('designation');
$companysize = $this->input->post('companysize');
$checkmobile = $this->Loginmodel->checkmobile($mobile,$email);
if($checkmobile)
{
$this->session->set_flashdata("danger","Mobile Number or Email exist.....");
return redirect('Login/index');
}
else
{
$insertdata = $this->Loginmodel->insert($fname,$lname,$mobile,$email,$password,$companyname,$designation,$companysize);
$this->session->set_flashdata("success","Record Inserted");
return redirect('Home/indexhome');
}
// }
// else
// {
// $this->session->set_flashdata("danger","Please fill all the values properly");
// $this->index();
// }
}
else
{
echo 'Captcha code does not match, please try again.';
$this->index();
}
}
else
{
$this->session->set_flashdata("danger","Please fill all the values properly");
$this->index();
}
}
public function refresh(){
// Captcha configuration
$config = array(
'img_path' => 'uploadss/',
'img_url' => base_url().'uploadss/',
'font_path' => base_url().'system/fonts/texb.ttf',
'img_width' => '200',
'img_height' => 90,
'word_length' => 3,
'font_size' => 25
);
$captcha = create_captcha($config);
$this->session->unset_userdata('captchaCode');
$this->session->set_userdata('captchaCode',$captcha['word']);
echo $captcha['image'];
}
public function upload($id)
{
if(!empty($_FILES['imagename']['name']))
{
$config['upload_path'] = 'uploadss/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['imagename']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('imagename'))
{
$uploadData = $this->upload->data();
$imagename = $uploadData['file_name'];
}
else
{
echo "not upload";
}
}
else
{
echo "error";
}
$this->load->view('uploadimage');
}
public function uploadimageerror()
{
if(!empty($_FILES['imagename']['name']))
{
$config['upload_path'] = 'uploadss/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['imagename']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('imagename'))
{
$uploadData = $this->upload->data();
$imagename = $uploadData['file_name'];
}
else
{
echo "not upload";
}
}
else
{
echo "error";
}
}
public function deletedata($id)
{
$dele = $this->Loginmodel->delete($id);
return redirect('Login/index');
}
}
?>

Categories