I am having trouble trying to pass an valuable after the user fail the authorization. I would like to pass $error to the welcome controller but not sure how. Please help. Thank you.
private function _user_check()
{
//after form validation, I pass username and password to the model
$this->load->model('user_query');
$result=$this->user_query->query($this->input->post('username'),$this->
input->post('password'));
if($result)
{
redirect('main');
}else{
// I am not sure how to pass this error message to my welcome controller
$data['error']='Please check your username or password';
redirect('welcome');
}
}
In the redirect function, you aren't providing a full URL, so CI is going to treat the parameter as an URI segments to the controller.
Knowing this, you could have something like:
redirect('welcome/error/error_user_pass');
and have your "error_user_pass" that is being passed reference error constants defined in your CI project.
Maybe something like this in your application/config/constants.php file:
define('error_user_pass', 'incorrect user or password, please check yo self!');
Then in your 'welcome' controller having something like this:
class Welcome extends CI_Controller {
public function error(){
$errors = func_get_args();
foreach( $errors as $error ){
//echo error, or save it, or whatev
}
}
}
Related
I have something like website.com/profile/nameofuser that is working.
But if I have website.com/profile/_nameofuser I get 404 error also website.com/profile/nameofuser_ or website.com/profile/nameof_user is working. It's not something related to accepted characters, but what's the problem?
class Profile extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->model('Profile_model');
$this->load->helper(array('url', 'form', 'htmlpurifier'));
}
public function index() {
$this->load->library('form_validation');
if(getUserData($this->uri->segment(2), "ID") < 0) {
$this->session->set_flashdata('error', 'Profil inexistent.');
redirect(base_url());
}
if (!is_cache_valid(md5('profile' . $this->uri->segment(2) . ''), 300)){
$this->db->cache_delete('profile', $this->uri->segment(2));
}
if(getUserData($this->uri->segment(2), "ID") > 0) {
/* some mysql queries.. */
}
$data["main_content"] = 'profile/profile_view';
$this->load->view('includes/template.php', $data);
} else {
$this->session->set_flashdata('error', 'Profil inexistent.');
redirect(base_url());
}
}
function _remap($method,$args)
{
if (method_exists($this, $method))
{
$this->$method($args);
}
else
{
$this->index($method,$args);
}
}
}
Here is my profile controller. I really don't know what's the problem. If I enter an invalid profile redirects with error flashdata so ti's ok. Maybe it's a remap problem?
1) Check the fie format in your view file.. if it is html file that mean you cannot call it without its format
for example
if your file is php format have name home-view.php
you can call it as
$this->load->view('home-view');
but if it is html file then the name in home-view.html
so you have to call it with its exstention as
$this->load->view('home-view.html');
your call to /profile/nameofuser is missing a fundamental from the MVC architecture.
You need to call a controller/method combination (in CI, your basic url is domain.com/controller/method)...
since you don't have a specific method for each user within the profile controller, which is actually a good thing, you need a method within the controller that handles your users. You already have it, it's called index
If you point your URL to /profile/index/nameofuser and change $this->uri->segment(2) to $this->uri->segment(3) you should get it to work
give it a try and let me know
I am new to CakePHP, and follow the tutorial of CakePHP to try login function, however there is no error message appear after I use the wrong username/password. Please help.
public function login()
{
if ($this->request->is('post')) {
$user=$this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'bookmarks']);
}
$this->Flash->error('Your username or password is incorrect');
}
}
By using FlashComponent's magic method __call() an element is required to exist under src/Template/Element/Flash.
In your case you called error(), therefore it uses src/Template/Element/Flash/error.ctp. Make sure element exists.
Either that or you are not calling $this->Flash->render() in your view (where you want the error message to be shown).
Well I have set validationErrors for login in my UsersController:
public function login() {
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates() && $this->Auth->login()) {
$this->set('ui', $this->Auth->user('id'));
$this->Session->setFlash(__('Loged in!'), 'flash_success');
$this->redirect($this->Auth->redirect());
} else {
$errors = $this->User->validationErrors;
}
}
}
Now how can I use $error in my view or as an element to be listed above my form?
Plz help I have searched a lot, but the answers were for old CakePHP, and I am using CakePHP 2.3.8.
Validation errors are available in the view automatically
There is no action required to get validation errors in the view, as they are a property of the view class. They can be inspected simply with:
debug($this->validationErrors);
In the view.
But you probably don't need to access them
Note however that it's not normal to need to look at this property directly. Using the form helper errors are displayed automatically, or you can generate errors individually
if ($this->Form->isFieldError('email')) {
echo $this->Form->error('email');
}
I'm having this problem about direct access to functions: for example I have this code:
controller users
function index(){
//this is my users index view, user can add,edit,delete cars
}
function details($id){
//a function where 1 car can be viewed in detail..
function add(){
//function to add car
}
Now if I go to address bar and type. localhost/myapp/users/detail it will go to the url and echo an error since $id is null. What I want is only the index is directly accessible if a user would type in the address bar. I don't want the users to go directly to myapp/users/add, etc..
CI Controller functions always must be able to handle user input (i.e. url segments), which means anyone can type in whatever they wish and make a request. You can't stop that. The best practice is to either:
Always provide default arguments
Use the URI class to get your parameters, or func_get_args()
Always validate the presence of and integrity of arguments passed to the controller, as you would with any other user input
Since it's much more common, accepted, and easier to read - just make sure to always provide defaults and validate them.
An example with your controller:
function index() {
//this is my users index view
//user can add,edit,delete cars
}
function details($id = NULL) {
if ( ! $id) {
// No ID present, maybe redirect without message
redirect('users');
}
$user = $this->user_model->get($id);
if ( ! $user) {
// ID present but no user found, redirect with error message
$this->session->set_flashdata('error_message', 'User not found');
redirect('users');
}
// We found a user, load view here etc.
}
function add() {
// Check for the presence of a $_POST value
// You could also use the Form_validation lib here
if ( ! $this->input->post('add_car')
{
$this->session->set_flashdata('error_message', 'Invalid request');
redirect('users');
}
// Try to add the car here and always redirect from here
}
The only other way is to make the method private or use CI's _underscore() naming as suggested (making it inaccessible from the url). You can still call the function in other methods if you wish, as in:
function index() {
if ($this->input->post('add_car')
{
// Call the private "_add" method
$this->_add();
}
// Load index view
}
So to make a long story short: You can't stop the requests from being made, you can only decide what to do when the request is invalid.
Add an underscore before the names of functions you want to hide:
function _details($id){
//a function where 1 car can be viewed in detail..
}
function add(){
//function to add car
}
I'm trying to create a universal header for a website built on CodeIgniter, and I'm having trouble figuring out the code that will switch the 'Login' link for the user's name (with a link to the profile page) after the user logs in.
In the controller functions, I've tried the following code:
if(!$this->session->userdata($userSessionVar))
{
$data['header_output'] = "<li><a href='" . base_url() . "index.php/main/login'>Login</a></li>";
} else
{
$data['header_output'] = $this->session->data('userFirstName');
}
(I realize this is incomplete, based on my designs, but it's just to test.) $userSessionVar holds the value "logged in" once logged in. Probably not the best way to do that. And that doesn't seem to work (and I pass the $data to the view). I've also tried making a custom function:
function check_login()
{
$CI =& get_instance();
$userSessionVar = 'logged_in';
if( ! $CI->session->userdata($userSessionVar))
{
return false;
} return true;
}
And then use the true/false return to structure the $header_output variable. None of these seem to work. I'm new to CodeIgniter and have some intermediate level of PHP/HTML/CSS, etc. I'm sure I'm missing something obvious and would appreciate any help, as well as a heads-up on how to avoid including the code in every controller function.
The variable $userSessionVar is only available within the function check_login(), so when you try to use it outside of the function, it will be blank (and therefore useless).
I recommend that you simply use $this->session->userdata('logged_in') and $CI->session->userdata('logged_in') rather than using the variable $userSessionVar to store what appears to be a constant value.
Also, you have an error in your code. You need to replace $this->session->data('userFirstName') with $this->session->userdata('userFirstName')
Here's how I typically deal with user data. First, add auth.php to the models folder:
<?php
class Auth extends Model {
private $user_data = false;
function Auth() {
parent::Model();
if ($this->input->post('action') == 'login') $this->login();
else if ($auth_id = $this->session->userdata('auth_id')) {
$user = // load user data from the database into the variable $user
if ($user) {
$this->user_data = $user;
} else $this->session->unset_userdata('auth_id');
}
}
function login() {
// process POST, check with database, and then store user_id using
// $this->session->set_userdata('auth_id', $user_id_here)
}
function me() {
return $this->user_data? (object)$this->user_data : false;
}
}
?>
Then, auto-load the model. To do this, edit config/autoload.php like so:
$autoload['model'] = array('auth');
Now your IF statement could look like this:
if ($me = $this->me()) $data['header_output'] = $me->userFirstName;
else $data['header_output'] = '<li>Login</li>';
in your model auth.php you've got the statements
class Auth extends Model
and
parent::Model();
With CodeIgniter, should these not be "CI_Model"...?