iwj145
iwj145

Reputation: 261

How do I print the username using session in cakephp?

I cannot get my username to show on the website when I call it form the session.

The code on the index page is:

<h1>Users Home</h1>
Welcome <?php $user = $this->Session->read('Users.username');?>

What am I doing wrong?

I've also tried various other ways of calling it and then getting different error messages.

Upvotes: 3

Views: 7690

Answers (4)

Domingo C.
Domingo C.

Reputation: 799

As Hugo said you should do the following:

<h1>Users Home</h1>
Welcome <?php echo $this->Session->read('Auth.User.username'); ?>

If you are going to use it on more than one view, I would suggest you to add the following on AppController.

public function beforeFilter() {
    $this->set('username', AuthComponent::user('username'));
    // OR $this->set('username', $this->Session->read('Auth.User.username'));
}

And then on any of your view just use the variable $username to print the current username.

<?php echo $username; ?>

Upvotes: 3

noslone
noslone

Reputation: 1289

echo $this->Session->read('Auth.User.username');

Or if you are using Cakephp 2.x you can use AuthComponent::user('username') anywhere in your code.

Upvotes: 0

mrq
mrq

Reputation: 101

After getting $user, you should do a echo $user or print_r($user) and you'll get the username printed.

Upvotes: 0

Hugo Delsing
Hugo Delsing

Reputation: 14173

In your code you are setting $user with the content of the username. But you are not printing it.

<h1>Users Home</h1>
Welcome <?=$this->Session->read('Auth.User.username')?>

which is short for

<h1>Users Home</h1>
Welcome <?php print $this->Session->read('Auth.User.username'); ?>

Upvotes: 4

Related Questions