Reputation: 1805
I have written my cake app to log in registered users and it works great on view pages where there is a db model associated with a User. However, on my main pages that aren't necessarily accessing some model (the PagesController where pages are things like upcoming events, contact us, about, etc), AuthComponent is not available, or at the least, the array returns empty---so i cannot retrieve, say, the username of the person logged in.
I tried creating a model called Page that belongsTo User but that didn't fix my problem.
To explain a little further, my app shows lists of certain lodgings, nightclubs, restaurants and things to do for a given city, all of which is shown whether a user is logged in or not. I don't understand where I am going wrong and why.
Here is my AppController:
<?php
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'view'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'index')
)
);
function beforeFilter() {
$this->Auth->allow('login', 'logout','index', 'view', 'condos', 'houses', 'hotels_and_motels', 'print_all_coupons', 'print_coupon', 'search', 'golf', 'charters', 'events', 'nightlife', 'shopping', 'visitors_info', 'contact_us');
}
}
?>
here is where I access my username in my default page layout:
<?php if(AuthComponent::user('id')) {
echo '<span style="font-variant:small-caps">Hello, '.AuthComponent::user('username').'</span> | ';
?>
Upvotes: 0
Views: 567
Reputation: 1805
I have found the answer, after weeks of beating my head on the wall about this. And oh, you're gonna laugh. For any of you out there up against this problem, the answer is.....make sure there is no white space before or after your tags. That is all. Seriously. Since PHP prints out everything that isn't in a PHP tag, if it finds something to send, it will send out headers before everything else. Once headers are sent, a PHP session cannot be created. So chalk this one up to the head-smacking file!
Upvotes: 3
Reputation: 11575
Without seeing any code my first instinct is to say that you are not loading the component in AppController but in the UsersController only. Are you loading the Auth component in AppController?
UPDATE:
Here is how I would suggest accessing the User information.
$this->Session->read('Auth.User.username');
UPDATE 2
Remove the $components
declaration from the Pages Controller. It could be overriding the session.
UPDATE 3
If you have a custom Pages controller, it is probably conflicting with the Core Pages controller. Remove your Pages controller and see if it works correctly. The Core Pages controller will still route to the Views/Pages/
directory for displaying content.
Upvotes: 0