<?php
class Admin extends MY_Controller
{
public function dashboard()
{
/*
if(! $this->session->userdata('user_id')) // This condition is check condition which will show dashboard only if person is logged in else will redirect to login page.
return redirect('login');
*/
$this->load->model('articlesmodel','articles'); // This "articles" is the secondary name which we have given here and will be refering to.
$articles = $this->articles->articles_list(); // If we have given the secondary name then we need to use that seconary name here too.
// In above line, we will get the titles/title which will get stored in $articles.
$this->load->view('admin/dashboard.php',['articles'=>$articles]); // we are passing the received articles in here.
// The above 'articles' will be received by "dashboard.php" in the form of "$articles".
}
public function add_article()
{
$this->load->helper('form');
$this->load->view('admin/add_article.php');
}
public function store_article()
{
// Previously we use to form validate from the same file. But, now we have set the rules and all in config's form_validation file.
// We just need to pass the rule in the run like below.
$this->load->library('form_validation');
if($this->form_validation->run('add_articles_rules'))
{
// If we pass the parameter inside post then we will get that value only else it will give all the inputs in the array.
$post = $this->input->post();
unset($post['submit']); // this is to remove submit value received in $post array else it will give error.
$this->load->model('articlesmodel','articles');
if($this->articles->add_article($post))
{
echo "Insert sucessful";
}
else
{
echo "Insert uncessful";
}
}
else
{
return redirect('admin/add_article');
}
}
public function edit_article()
{
}
public function delete_article()
{
}
public function __construct()
{
parent::__construct();
if(! $this->session->userdata('user_id'))
return redirect('login');
}
// Above constructor can be placed in MY_Controller but then we need to undo the "login extends My_Controller" or make it as
// "login extends CI_Controller" as in this "admin" file we can have more methods.
}
?>
Related
I am creating eCommerce in Codeigniter. Here is the controller file for registration:
class Register extends CI_Controller {
public function index()
{
$this->load->view('common/header');
$this->load->view('register');
$this->load->view('common/footer');
}
public function home(){
$this->load->view('common/header');
$this->load->view('common/slider');
$this->load->view('home');
$this->load->view('common/footer');
}
public function signup(){
$username = $this->input->post("username");
$password = $this->input->post("password");
$email = $this->input->post("email");
$this->form_validation->set_rules('username','User Name','required|is_unique[user.name]|min_length[4]');
$this->form_validation->set_rules('password','Password','required|min_length[5]');
$this->form_validation->set_rules('email','Email address','required|valid_email');
$this->form_validation->set_error_delimiters('<div class="text-danger">', '</div>');
if($this->form_validation->run() == true){
$this->load->model('register_model');
if($this->register_model->register_user($username,$password,$email)){
$this->home();
}else{
$this->index();
}
}else{
$this->index();
}
}
}
On form submit the page is redirecting to the home page but the URL on the browser is (http://localhost:8080/codignitor_projects/shophere/register/signup) But I want to change the URL to this (http://localhost:8080/codignitor_projects/shophere/)
I got your problem. I don't know your CI version. I hope you are using the latest one and I am also giving my answer according to the latest version CI-4.
Please Write
return redirect()->to('index');
or
return $this->response->redirect(base_url('YourControllerName/index'));
instead of
$this->index();
To clearify this problem I would like to give you an example. Let, I have a Test controller and there are two functions such as abc() and def()
class Test extends Controller
{
function abc()
{
echo "Hi ! I am ABC";
}
function def()
{
$this->abc();//URL will be: http://localhost/your_project_name/public/test/def
//return redirect()->to('abc'); //URL will be: http://localhost/your_project_name/public/test/abc
//return $this->response->redirect(base_url('Test/abc')); //URL will be:http://localhost/your_project_name/public/Test/abc
}
}
There are three lines inside the def() function that give you the same result but the URL from first one to others will be different which is commented.
I was to update my database but I get the error, "no data to update". Here is my script;
I have created a simple toggle to up update the database. The toggle makes the user active (is_active=1) or inactive (is_active=0). The problem I am encountering is that although the object is change from 1 to 0 or 0 to 1, when I pass it to the model, it comes back with the error, "There is no data to update". The method is as follows;
namespace App\Controllers\Admin;
use App\Entities\User;
class Users extends \App\Controllers\BaseController
{
private $model;
public function __construct()
{
$this->model = new \App\Models\UserModel;
}
public function toggle_user_is_active($id)
{
$users = $this->model->where('id', $id)->first(); // get the record
// if the current user is ACTIVE, then set it to DEACTIVE
if ($users->is_active == 1) {
$users->is_active = 0;
$this->model->save($users)); // gives an error, nothing to update
return redirect()->to('/Admin/Users/index')
->with('info', 'Success - User deactivated');
} else {
// if the current used is ACTIVE(1), change to INACTIVE(0)
$users->is_active = 1;
$this->model->save($users); // same error as above
return redirect()->to('/Admin/Users/index')
->with('info', 'Success - User Activated');
}
} // end method
}
The really strange thing is this is a copy of another method that works perfectly as follows;
namespace App\Controllers\Admin;
use App\Entities\CategoryEntity;
use App\Entities\PostEntity;
class Post extends \App\Controllers\BaseController
{
private $model;
public function __construct()
{
$this->model = new \App\Models\PostModel;
$this->CategoryModel = new \App\Models\CategoryModel;
$auth = new \App\Libraries\Authentication;
$this->current_user = $auth->getCurrentUser();
}
public function toggle_post_is_published($post_id)
{
$post = $this->model->where('post_id', $post_id)->first();
// if the current post is PUBLISHED, then set it to UNPUBLISHED
if ($post->post_is_published == 1) {
echo
$post->post_is_published = 0;
$this->model->save($post);
return redirect()->to('/admin/post/post_index')
->with('info', 'Success - Post unpublished');
} else {
// if the current post is UNPUBLISHED, then set it to PUBLISHED
$post->post_is_published = 1;
$this->model->save($post);
return redirect()->to('/admin/post/post_index')
->with('info', 'Success - Post published');
}
}
} // end class
I finally figured it out. In my UserModel I did not add 'is_active' to protected $allowedFields . I have not added 'is_active' to the allowedFields and it works.
Have you declare your model, because look like you use $this- >model but not setup your model in your constructor or other method.
i have a problem, i have login page, it will direct to the profile if we input the correct email & password, but the problem is when i change the url to the login, it still move to the login page, how can i block the login page if I'm already logged in so that will be dirrect to the profile although the url i change to the login page it's still direct to the profile page.
below is the code :
class Profile extends CI_Controller {
public function index()
{
if($this->session->userdata('logged_in')){
$session_data = $this->session->userdata('logged_in');
$data['email'] = $session_data['email'];
$this->load->view('view_profile', $data);
}else{
redirect('login','refresh');
}
}
public function logout(){
$this->session->unset_userdata('logged_in');
$this->session->sess_destroy();
redirect(site_url('home'),'refresh');
}
}
this is the userdata('logged_in')
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
$this->form_validation->set_rules('email','Email','trim|required');
$this->form_validation->set_rules('password','Password','trim|required|callback_basisdata_cek');
if($this->form_validation->run()==false){
$this->load->view('view_home');
}else{
redirect(base_url('index.php/profile'),'refresh');
}
}
function basisdata_cek($password){
$email = $this->input->post('email');
$result = $this->login->login($email,$password);
if($result){
$sess_array = array();
foreach($result as $row){
$sess_array = $arrayName = array('email'=>$row->email, 'password'=>$row->password);
$this->session->set_userdata('logged_in',$sess_array);
}
return true;
}else{
$this->session->set_flashdata('basisdata_cek', 'Invalid email or password');
redirect(base_url('index.php/login'),'refresh');
return false;
}
}
}
BEST Practice
Always create User / Login Controller separate, you will have more space to create functionalities like user role check and redirecting the user to their role specific dashboards / profiles.
Keep Login / Logout check functions in a parent controller and extend your controller from that controller. For example, create a controller named My_Controller and put your isLoggedin check and logout functions in it.
class My_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function isLoggedIn()
{
if(!empty($this->session->userdata['id'])&& $this->session->userdata['type']=='admin')
{
return true;
}
else
{
return false;
}
}
public function logout()
{
$this->session->sess_destroy();
redirect(base_url());
}
}
Then create your user or login controller to render the login page and implementing login functionality
class Login extends My_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
$this->load->library("security");
}
public function index()
{
if(!$this->isLoggedin()) // if the user is not logged in render login screen
{
if($_POST) // or if($this->input->post)
{
$data=$this->security->xss_clean($_POST);
$user=$this->user_model->checkUser($data);
if(!empty($user))
{
$this->session->set_userdata($user);
redirect(base_url().'profile');
}
else
{
$data['errors']='Wrong Credentials';
$this->load->view('login',$data);
}
}
else
{
$this->load->view('login');
}
}
else // but if the user is logged in , take him to profile.
{
redirect(base_url().'profile');
}
}
And in your profile Controller
class Profile extends My_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function index()
{
// if user is not logged in , redirect him back to login screen.
if(!$this->isLoggedin()){ redirect(base_url().'login');}
$userId=$this->session->userdata['id']; // this index depends on the field name
$data['user']=$this->user_model->getUserDataById($userId);
$this->load->view('profile',$data);
}
}
model
This is my model.using last query I get value in the model,but I don't get the value in the controller
class Login_model extends CI_Model {
function __construct()
{
parent::__construct();
}
public function email()
{
$this->db->select('email');
$this->db->from('change_password');
$result=$this->db->get();
return $result;
}
}
controller
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
}
function checking()
{
$email=$this->input->post('email');
$this->load->model('login_model');
$dbemail=$this->login_model->email();
echo $dbemail;
}
}
CI is a MVC Framework. So you need to Command from Controller and get data from the models and finely you need to pass them to view. This is a best Practice
Controller
function checking()
{
$email=$this->input->post('email');
$this->load->model('login_model');
$data['dbemail']=$this->login_model->email();// assign your value to CI variable
$this->load->view('home', $data); //passing your value to view
}
Model
public function email()
{
$query = $this->db->query("SELECT email FROM change_password");
$result = $query->result_array();
return $result;
}
View
Extra Knowledge
View will be create under View folder/ Ex im using view name
as home.php
you can use your own stylings(its also created as normal html page.)
foreach ( $dbemail as $new_dbemail )
{
echo $new_dbemail['database_field'];//in here you can get your table header.
//Ex if your table has name field and you need to sho it you can use $new_dbemail['name']
}
Hi on my website I have profile with username parameter root/user/{username}. I was planning to add button to block the user. My problem is that when other user click block button, the button do stuffs in the Check.php controller but it doesn't pass the user/{username} parameter that I need in if statements. My question is how I can pass the {username} parameter from my user.blade.php to the Check.php controller?
As we are not seeing any code here, it seems that to do what you need, you just have to create a route pointing to your controller method and eventually a route to redirect your users when successufully blocked:
Route::get('user/block/{username}', 'BlockUserController#block');
Route::get('userBlocked', 'BlockUserController#blocked');
And the controller itself:
class BlockUserController extends Controller {
public function block($username)
{
$user = User::where('username', $username);
$user->blocked = true;
$user->save();
return Redirect::to('userBlocked');
}
public function blocked($username)
{
return View::make('user.blocked');
}
}
And then if you click the button pointing to the route:
http://application.com/user/block/user3398940
It will be blocked.
If you want to go a little more advanced in Laravel, you can use dependency injection and remove some code from your controller:
class BlockUserController extends Controller {
private $user;
public function __construct(User $user)
$this->user = $user;
}
public function block($username)
{
if ($user->block($username))
{
return Redirect::to('userBlocked');
}
return Redirect::back()->with('message', 'User not found');
}
public function blocked($username)
{
return View::make('user.blocked');
}
}
And your user model would have to have a block method:
class User extends Eloquent {
public function block($username)
{
if ($user = $this->newQuery()->where('username', $username))
{
$user->blocked = true;
return $user->save();
}
return false;
}
}