I want to do a page, and this page can open only one user. I want to do something like this: If user id = 1 then its opening else its throwing error.
I already tried this :
if (in_array($this->action, array('controller' => 'users', 'action' => 'admin'))) {
$postId = (int) $this->request->params['pass'][0];
if ($this->User->isOwnedBy($postId, $users['id'] = 1)) {
return true;
}else{echo "You are not admin!";}
}
Then I thinked, maybe this is a little bit easier ?
public function admin($id = null) {
$this->User->id = $id;
if ($id == 1) {
echo 'You are admin';
}
else {
throw new NotFoundException(__('You are not admin !'));
}
}
But its not working, How I get this user id in to this if. This second solution throwing only this error, but I dont want it, I want access if user id is 1.
Here is users picture
Thank you for any clue or solution.
Try this-
public function admin($id = null) {
$currentUserId = $this->Auth->user(id);
//$isAdmin = $this->User->hasAny(
//array('User.id' => $currentUserId)
//);
//if ($isAdmin) {
if ($currentUserId == 1)
echo 'You are admin';
} else {
throw new NotFoundException(__('You are not admin !'));
}
}
For logged in users.
The recommended approach for getting logged in user data is via the AuthComponent itself:
// in any controller
$userId = $this->Auth->user('id');
See Accessing the logged in userAccessing the logged in user in the Auth section of the CakePHP Book.
Better Option:-
use role id for admins, this will help you for multiple admins. and give negative id to admin:-
like add role_id column in user table and give value to -1
public function admin($id = null) {
$role = $this->Session->read('Auth.User.role_id');
if ($role < 0)
echo 'You are admin';
} else {
throw new NotFoundException(__('You are not admin !'));
}
}
so you want to check if the user ID is 1 ??
//Fetch the user informations from database and stock it into $user
if(is_admin($user[id])){
echo 'You are admin';
}
else{
echo 'You are not admin';
}
function is_admin($id = NULL){
if($id == 1){
return true;
}
else{
return false;
}
}
tell me if I misunderstood
Edit :
According to our chat, try this :
//Fetch the ID of the user and stock it in $user_id
if($user_id == 1){
echo 'You are admin';
}
else{
echo 'You are not admin';
}
Related
I have a login form on RedBean PHP. I need to implement redirection to profile if user was logged and just closed page, but when I open my start page I need to type email and password again and again. How to redirect user immediately to profile page if he did not log out.
I tried to use if($_SESSION['logged_user'] = $user) {header('Location: /profile');, but it did not work. Please assist. I use OpenServer Panel.
Code:
$data = $_POST;
if(isset($data['do_login'])) {
$user = R::findOne('users', 'email = ?', array($data['email']));
if($user) {
// var_dump($user);
if(password_verify($data['password'], $user->password)) {
$_SESSION['logged_user'] = $user;
header('Location: /profile');
// echo '<div style="color: green;">You are authorized! Go to Profile page</div>';
}else {
$errors[] = 'Password is not correct!';
}
} else {
$errors[] = "User with such email doesn't exist!";
}
if(!empty($errors)) {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
}
if($_SESSION['logged_user'] = $user) {
header('Location: /profile');
}
You incorrectly write your condition.== instead of =
if($_SESSION['logged_user'] == $user) {
header('Location: /profile');
}
Let me know,if this solve your problem
I solved it by add this code:
if(isset($_SESSION['logged_user'])) {
header('Location: /profile');
}
I have 2 users in a table, for example Vesna and Silvija, Vesna is first, Silvija second and if I type Silvija in postman he will return me "User does not exist and than Id of a user Silvija. This should be working on a way that Postman return just an Id of a User and if I type user that doesnt exist he should return that user doesnt exist. But when I type a users that doesnt actually exist he will return 2 times that users doesnt exist instead one time because table have 2 users that doesnt match entered user. Hope I have explained it understandably and that someone can help me.
foreach($oUsers as $oUser)
{
if($oUser->USERNAME == $sUsername)
{
$_SESSION['user_id'] = $oUser->USER_ID;
$_SESSION['username'] = $oUser->USERNAME;
echo $_SESSION['user_id'];
break;
}
else
{
echo ' User does not exist';
}
}
You can not use echo '...' inside the foreach loop because echo is executed in every iteration.
$found = false;
foreach($oUsers as $oUser){
if($oUser->USERNAME == $sUsername){
$_SESSION['user_id'] = $oUser->USER_ID;
$_SESSION['username'] = $oUser->USERNAME;
$found = true;
break;
}
}
if($found === true){
echo $_SESSION['user_id'];
}else{
echo ' User does not exist';
}
I need to control a session in a REST API. My REST API is implemented with slim and doctrine and within the routes.php file I have defined the POST request of the login:
session_start();
$app->post('/login', function ($request, $response) {
$em = getEntityManager();
$args = $request->getParsedBody() ?? json_decode($request->getBody(), true);
$user = $em->getRepository(Usuario::class)->findOneByUsername($args['username']);
if (null == $user) {
echo "<script language='javascript'>alert('User not found'); window.location='App.php'</script>" ;
} else {
if ($user->getPassword() == $args['password']){
$_SESSION['id'] = $user->getId();
$_SESSION['username'] = $user->getUsername();
if($user->getAdmin() && $user->getEnabled()){
echo "<script language='javascript'>window.location='Admin.php'</script>" ;
} else if($user->getEnabled()){
echo "<script language='javascript'>window.location='Comparator.php'</script>" ;
} else {
echo "<script language='javascript'>alert('Account
inabilited'); window.location='App.php'</script>" ;
}
} else {
echo "<script language='javascript'>alert('Incorrect Password'); window.location='App.php'</script>" ;
}
}
});
I have 3 page .php. In page App.php I have an access form. I want to do is that when any user wants to enter the Admin or Comparator page, he can not enter without logging in previously.
For this I have added the following code to the pages previously named:
<?php if (session_status() != "PHP_SESSION_ACTIVE" && session_status() != 2) { ?>
<script>window.location='App.php'</script>
<?php }?>
But when entering a valid username and password I get the following error:
It's very weird because the field username in the class Usuario exists.
Any solutions?
I use CI 2.2 to build a simple login system. But I get problem when I try to generate session. Of course I have properly set up libraries (database, session) and User_M. When I retrieve data from database (without session), that's work fine. This is my Controller code:
public function verify()
{
// Define variable
$user = $this->input->post('username');
$pass = $this->input->post('password');
// Check input data
if (!empty($user) AND !empty($pass))
{
// Check match data from db
$checks = $this->User_M->check_user($user, $pass);
if($checks->num_rows() == 1)
{
foreach ($checks->result() as $check)
{
$sess = array (
'username' => $check->username,
'logged_in' => TRUE
);
$rest = $this->session->set_userdata($sess);
if ($rest)
{
echo "working";
} else {
echo "not working";
}
}
} else {
echo "Not found";
}
} else {
echo "You've empty field";
}
}
Additional explain, I check the result with if ($rest)...bla..bla..bla, that's echoing Not Working. Please let me know where's my mistakes?
Thank in advance
I think the problem is with this statement
$rest = $this->session->set_userdata($sess);
the set_userdata() does not return anything, so according to your condition it will always execute the else part.
Try to change your condition like this
if (!empty($this->session->userdata("username"))){
echo "Working";
}else{
echo "Not Working";
}
I was wondering if anyone could help me - I have successfully created a log in system allowing a user (student) to log in. My system also requires an admin log in, with the admin having privileges to view pages that the student does not. Both the admin and student information comes from two different tables. Below is the code I have used for the student log in (there are two different pages - users and login). I am stuck as to how to implement the admin log in. Any help is appreciated!
(Admin will log in using 'adminnum' and 'adminpassword'.
login.php
<?php
include "core/init.php";
include "includes/content.php";
if (empty($_POST) === false) {
$studentemail = $_POST ['studentemail'];
$studentpassword = $_POST ['studentpassword'];
if (empty($studentemail) === true || empty($studentpassword) === true) {
$errors[] = "You need to enter an email address and password";
} else if (user_exists($studentemail) === false) {
$errors[] = "We can't find that email address. Have you registered?";
} else {
if (strlen($studentpassword) > 32) {
$errors[] = 'Password too long';
}
$login = login($studentemail, $studentpassword);
if ($login === false) {
$errors[] = 'That email/password combination is incorrect';
} else {
$_SESSION['studentid'] = $login;
header('Location: index.php');
exit();
}
}
} else {
$errors[] = 'No data received';
}
include "includes/overall/overall_header.php";
if (empty($errors) === false) {
?>
<h2> We tried to log you in, but...</h2>
<?php
echo output_errors($errors);
}
?>
<center><input id="submit" type="submit" value="Back" onclick="location.href='Login2.php'"></center>
<?php
include "includes/overall/overall_footerloggedout.php";
?>
users.php
<?php
function logged_in() {
return (isset($_SESSION['studentid'])) ? true : false;
}
function user_exists($studentemail) {
$studentemail = sanitize($studentemail);
$query = mysql_query("SELECT COUNT(`studentid`) FROM `student` WHERE `studentemail`
= '$studentemail'");
return (mysql_result($query, 0) == 1) ? true : false;
}
function studentid_from_student ($studentemail) {
$studentemail = sanitize($studentemail);
return mysql_result(mysql_query("SELECT `studentid` FROM `student` WHERE `studentemail` = '$studentemail'"), 0, 'studentid');
}
`function login($studentemail, $studentpassword) {
$studentid = studentid_from_student($studentemail);
$studentemail = sanitize($studentemail);
$studentpassword = md5($studentpassword);
return (mysql_result(mysql_query("SELECT COUNT(`studentid`) FROM `student` WHERE `studentemail` = '$studentemail' AND `studentpassword` = '$studentpassword'"), 0) == 1) ? $studentid : false;
}
?>
I suggest to change your logic, extracting users and admins from two different table. Make them in only one table, but all users should contain column flag for example, where flag=1 is ADMIN and flag=0 is USER.
all i can suggest as i am not a php coder but have done some in the past is to add another field in your database where you will set levels of privileges for users (0 for normal members, 1 for admin). After you have done that just add it to your users script through php coding which i barely know. Hope that helps a little bit.