Check if session users is admin or simple - php

i want to make if clause for button. If admin is logged in it will shown otherwise not.
if($this->Session->User['role'] == 'admin') {
echo
'<li> <ul class="pull-right">Admin skiltis</ul></li>';
}
I can't get that role from session and compare if it admin or not..

Using $_SESSION['Auth']['User'] directly is a bad practice, as depending how the AuthComponent is configured, it may not be available.
You should better pass the authenticated user from the controller to the views and then only check his properties:
AppController:
$authenticated_user = $this->Auth->user();
if(isset($authenticated_user))
{
$this->set(compact('authenticated_user'));
}
Views:
if(isset($authenticated_user) && $authenticated_user['role'] == 'admin'){
...
}
By the way you should also use the HtmlHelper in your views to generate links instead of printing <a> tags manually with hardcoded urls to benefit from many Cake features.

Try to make a little debug on your code.
First check if your session was started.
You can do this by executing the command "session_status()" if the result is "PHP_SESSION_NONE" your session isnt started. You can fix it by putting a "session_start()" before any print was made by your page.

If value of print_r($_SESSION); is something like,
Array ( [Config] => Array ( [userAgent] => 4df452d8263aa05ef9324f37499322b0 [time] => 1401090120 [countdown] => 10 ) [Message] => Array ( ) [Auth] => Array ( [User] => Array ( [id] => 8 [username] => aaaaa [email] => aaa#gmail.com [role] => admin [created] => 2014-05-26 02:43:20 [modified] => 2014-05-26 02:43:20 [status] => 1 ) ) )
Thae try this code, I think it will work,
if($_SESSION['Auth']['User']['role'] == 'admin') {
echo
'<li> <ul class="pull-right">Admin skiltis</ul></li>';
}

Related

Saving Multiple Select in input

I have model for
user(id,name)
section(id,name)
section_users(id,user_id,section_id)
The admin adds all the users and sections separately. Once theses are added I want the admin to selects the section and add all the users in it in section_users
I have a select input with multiple set to true. How do i save this data the cakephp way along with validation.
<?php echo $this->Form->input("section_id"); ?>
<?php echo $this->Form->input("user_id", array('multiple'=>'checkbox')); ?>
This generates
Array
(
[section_id] => 1
[user_id] => Array
(
[0] => 3
[1] => 4
)
)
I know i can loop and convert to this and use saveAll or saveMany but what is the cakephp way/right way to do it.
Array
(
[0] => Array
(
[section_id] => 1
[user_id] => 3
)
[1] => Array
(
[section_id] => 1
[user_id] => 4
)
)
As already mentioned, this is exaplained in the docs, please read them, and in case you don't understand them (which would be understandable as the HABTM section is a little confusing and requires some trial & error), tell us what exactly you are having problems with.
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm
Based on the examples shown, the format for saving multiple X to Y should be
Array
(
[Section] => Array
(
[id] => 1
)
[User] => Array
(
[User] => Array(3, 4)
)
)
The corresponding form could look like this:
<?php echo $this->Form->create('User'); ?>
<?php echo $this->Form->input('Section.id'); ?>
<?php echo $this->Form->input('User', array('multiple' => 'checkbox')); ?>
<?php echo $this->Form->end('Add Users'); ?>
And the data would be saved via the Section model, that way its modified column is being updated properly.
public function addUsersToSection($id) {
// ...
if($this->request->is('post')) {
if($this->Section->save($this->request->data)) {
// ...
} else {
// ...
}
} else {
$options = array(
'conditions' => array(
'Section.' . $this->Section->primaryKey => $id
)
);
$this->request->data = $this->Section->find('first', $options);
}
$users = $this->Section->User->find('list');
$this->set(compact('users'));
}
Another way would be to restructure the array as shown by Vinay Aggarwal, that works fine, the only difference is that it requires saving through the join model, and consequently it doesn't update the Section models modified column.
CakePHP has the saveMany function, as mentioned in the documentation:
Model::saveMany(array $data = null, array $options = array())¶
This is HABTM relation, first of all you need have relation setup in SectionUser model. Then you can use saveAll() method to save all records at once.
Array
(
[0] => Array
(
[user_id] => 33
[section_id] => 9
)
[1] => Array
(
[user_id] => 33
[section_id] => 10
)
)
Make sure your data array is in above given format.
$this->SectionUser->saveAll($data);

how to get session variable value in php?

Inside my code i can see one session and once i printed that session i got following things in view source
Array
(
[Config] => Array
(
[time] => 1406983421
[timeout] => 10
)
[loggedIn] => 1
[user] => Array
(
[User] => Array
(
[id] => 424
[correspondence_email] =>
[terms] => Y
[old_facebook] =>
[[old_twitter] =>
[gmail_email] =>
[login_count] => 9
[last_secdeg_updated] => 2014-08-01 08:47:35
)
)
)
then i tried this line to get the value of "login_count"
echo "value".$this->Session->read("login_count");
but am not able to see this the "login_count" in echo.
am getting only this result in viewsource
value
How do i get "login_count" vale to a variable.?
echo $this->Session->read('user.User.login_count');
I hope this helps you.
Without seeing the code that writes the session, I am suspecting that this is what you're looking for:
echo $this->Session->read('user.User.login_count');
You dont have to create any codes to perfom session operations.They are already built in the cake php api.You just need to read and write the sessions from the link i given below.
http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html Used in Controllers
http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html Used in Views

Getting information out of a PHP object

I am trying to make my way through an inherited Yii Framework site. Very little Object Oriented knowledge previously.
I'm printing some user information to see what is there like this...
print_r(Yii::app()->user);
And that's printing out this...
CWebUser Object (
[allowAutoLogin] => 1
[guestName] => Guest
[loginUrl] => Array
(
[0] => /site/login
)
[identityCookie] =>
[authTimeout] => 7200
[autoRenewCookie] =>
[autoUpdateFlash] => 1
[loginRequiredAjaxResponse] =>
[_keyPrefix:CWebUser:private] => 7c6285462394c9a141b5d66dce54e8f2
[_access:CWebUser:private] => Array
(
[Admin] =>
[Judge] =>
[Student] => 1
)
[behaviors] => Array
(
)
[_initialized:CApplicationComponent:private] => 1
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
I'm trying to get out the information that this user is a Student. I see it! It's ]there!
[Student] => 1
But how would I get that information out?
UPDATE:
Here's the parts of CWebUser that appear to have something to do with _access
private $_access=array();
public function checkAccess($operation,$params=array(),$allowCaching=true)
{
if($allowCaching && $params===array() && isset($this->_access[$operation]))
return $this->_access[$operation];
$access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
if($allowCaching && $params===array())
$this->_access[$operation]=$access;
return $access;
}
The following should tell you whether the user has 'Student' access:
$isStudent = Yii::app()->user->checkAccess('Student') == 1;
'student' is part of the $_access array. But $_access is private so you can not access it directly.
But there must be a method (function) to get it!
look in the CWebUser class there should be a method like
getStudent();
isStudent();
or may be
$access = getAccess();
$access['student'];
Edit:
checkAccess
seems to be used someting like this checkAccess('student');

If user has no profile show 404

On my app a user may or may not have a profile. An example would be:
Array
(
[User] => Array
(
[id] => 7
[username] => noprofile
[password] => 3b8cdb0c849f00f3634d9b29def1dac4e9235795
[email] => noprofile#noprofile.com
[status] => 0
[code] => 114a10ebb6ffe364805aa70cd44bee7c
)
[Profile] => Array
(
[id] =>
[firstname] =>
[lastname] =>
[gender] =>
[dob] =>
[user_id] =>
)
)
Here the user noprofile has no matching content in the profiles table.
How do I show a 404 for when this happens? I've tried:
public function view ( $username )
{
$this->Profile->User->recursive = 2;
$profile = $this->Profile->User->find('first', array(
'conditions' => array('User.username' => $username)
));
if (empty($profile))
{
echo 'echo1';
throw new NotFoundException('No profile');
}
else {
echo 'echo2';
}
$this->set(compact('profile'));
}
But it doesn't show the 404! I'm using CakePHP 2.0.
It's because it finds the user so therefore profile is not empty! How do I check for the profile being empty then?
cakephp 2.0 has changed the way to display errors. Now you have to throw an exception. In your case, instead of :
$this->cakeError('error404');
you have to do:
throw new NotFoundException();
Edited:
On the other hand, you migth want to do a JOIN in your find query (and recursive -1), to foce the query to retreive the user's info ONLY if he has a profile.
Hope this helps
if (empty($profile['Profile']['id'])) {
throw new NotFoundException();
}
I expect there are better ways to do it but that's a quick fix. $profile, as you said, will not be empty as the user is found.

CakePHP 1.2.6 / PHP5.2.12 Error in Array Loop in Assignment by Reference

I'm working on retrieving a stack of data and for some reason some of the data gets corrupted. For instance, I've got some Post models that each are related to Comment models (hasMany), and each of the Comment models belongsTo a User. When retrieving the data, here's what I get from the database for the comments:
[Post] => Array
(
)
[Comments] => Array
(
[0] => Array
(
[content] => "2010 has definitely been a busy year!"
[created] => 2010-02-10 13:47:15
[user_id] => 18
[post_id] => 1
[User] => Array
(
[id] => U8
[username] => Uace
[first_name] => Uace
)
[_explicitType] => Comment
)
[0] => Array
(
[content] => "I can't wait..."
[created] => 2009-12-10 13:57:36
[user_id] => 18
[post_id] => 1
[User] => Array
(
[id] => U8
[username] => Uace
[first_name] => Uace
)
[_explicitType] => Comment
)
)
The first character of each of the Comments[i][User] arrays has been replaced with a capital U, though in each case it should be different (such as ID of 18, username of Jace, etc).
I traced it back to an array manipulation I was working with to assign an _explicitType field for Flex interaction (Thanks, Paweł Mysior!) in the afterFind() function. Here's the loop where I stuck in the _explicitType:
if (is_array($results)) {
foreach ( $results as &$item )
{
$item['_explicitType'] = $this->name;
}
} else {
$item[$this->name]['_explicitType'] = $this->name;
}
I assume it has to do with the assignment by reference, but I can't think of why it is happening.
It is very strange.
Set debug to 2 in core.php and look in the sql log at the bottom of the page, maybe you'll find something there. Also look through all models (app, post, user, comment). There might be some beforeFind() that are causing this to happen. Does it also happen when you do a simple User->find()?
Btw. how do you retrieve data here?
I think found the issue. I moved the check for the array inside the foreach() and that seems to be working correctly now. I assume this is because on non-array items, it actually broke things. Here's my altered loop with logging on the test cases:
foreach ( $results as &$item )
{
if(is_array($item)) {
$item['_explicitType'] = $this->name;
} else {
$copy = $item;
$copy['_explicitType'] = $this->name;
$this->log($copy, LOG_DEBUG);
}
}
And sure enough, it logged the data with capital U's replacing the first letter.

Categories