3

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.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
iwj145
  • 261
  • 1
  • 6
  • 16

4 Answers4

4

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'); ?>
Hugo Delsing
  • 13,803
  • 5
  • 45
  • 72
  • A minor thought. Is this vulnerable to XSS? Can a user register itself with something like `HelloMyNameContainsAScript`? IDK cakePHP at all regarding this. But usually it is wise to filter 'user-created-content', which also involves user names. – Daan Timmer Dec 04 '12 at 16:15
  • dont use = - use Session->read('Auth.User.username'));?>` – mark Dec 04 '12 at 16:17
  • any reason for advising against = – Hugo Delsing Dec 04 '12 at 17:32
  • I'd advise in favor of using `=`... It's very convenient and the more people use it the less the chance they will take it away from us ;) – Stijn de Witt Oct 19 '14 at 19:34
  • @StijndeWitt > Considering it's always on as of PHP 5.4, you don't need to worry about them taking it away. – Hugo Delsing Oct 22 '14 at 10:12
3

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; ?>
Domingo C.
  • 789
  • 4
  • 15
0
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.

nIcO
  • 5,001
  • 24
  • 36
noslone
  • 1,301
  • 10
  • 14
0

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

mrq
  • 101
  • 1
  • 7