I have coded a internal messenger system for the company I work for and I am trying to make things easier for myself by making a admin panel for this so it can control the usernames, passwords and groups.
Basically I am trying to select a user from the array using a url ?user=username which will then return the user information and allow it to be changed. The problem I am having is to get the url to select the username in the array.
The array is basic:
$users = array(
'0' => array(
'username' => 'test',
'password' => 'test123',
'group' => 'office',
),
Like this?:
<?php
// get username from URL (GET METHOD)
$username=$_GET["username"];
// $users has all the info
foreach ($users as $u) {
// find the target user
if ($u["username"] == $username) {
// do something with $u
var_dump($u);
}
}
?>
Did you tried to do this:
$user_name = $users[0]["username"];
Try this (not tested)
$u = null;
foreach($user as $user) {
if(isset($_GET['user']) && $user['username'] == $_GET['user']) {
$u = $user;
}
}
$u variable should contains yours user record.
Since it's an array i assume you have multiple indexes. I guess a simple 'find' function might work.
function findUser($searchData, $users, $searchField) {
$retObj = array();
foreach ($users as $user) {
if (isset($user[$searchField]) && $user[$searchField] == $searchData) {
$retObj['username'] = $user['username'];
$retObj['password'] = $user['password'];
$retObj['group'] = $user['group'];
break;
}
}
return $retObj;
}
EDIT: Added searchField so u can do same for password and group. Searchdata is the value u are searching
Related
I'm working on a website project (PHP, Fat-Free and mongodb) and I have a problem with only one user.
When the user does login, I call this function:
function login() {
$user = F3::get('POST.user');
$pass = F3::get('POST.pass');
if($user!=""&&$pass!=""){
$bcrypt = new Bcrypt(12);
$ismail = strrpos($user, "#");
$loginUser = new HT('user');
if($ismail===false){
$loginUser->load(array('nick' => $user));
}else{
$loginUser->load(array('email' => strtolower($user)));
}
if(!$loginUser->dry()){
if($loginUser->isActive == true){
$isValid = $bcrypt->verify($pass, $loginUser->password);
if($isValid){
$final_token = StringHelper::rand_str(30);
$tmp = $loginUser->token;
if(!is_array($tmp))
$tmp = array();
$cli_id = md5($_SERVER['HTTP_USER_AGENT']);
$tmp[$cli_id] = $final_token;
$loginUser->token = $tmp;
$user_id = $loginUser->_id."";
$loginUser->loginDate = new MongoDate();
$loginUser->updateFromId();
$isPremium = $loginUser->isPremium;
F3::set('user_id', $user_id);
if(isset($loginUser->preferences) && isset($loginUser->preferences['langPref'])){
$lang = $loginUser->preferences['langPref'];
echo json_encode(array("status"=>"OK","id"=>"$user_id","token"=>"$final_token","langPref"=>"$lang","schema"=>"$schema","isPremium"=>$isPremium));
}else{
echo json_encode(array("status"=>"OK","id"=>"$user_id","token"=>"$final_token","langPref"=>"en","schema"=>"$schema","isPremium"=>$isPremium));
}
}else{
echo json_encode(array("status"=>self::NOT_EXIST));
}
}else{
echo json_encode(array("status"=>self::NOT_ACTIVE));
}
}else{
echo json_encode(array("status"=>self::NOT_EXIST));
}
}
}
NOTE: dry() function checks if user is null in mongodb.
The user says that in his office computer can't do login, and he gets and "Invalid password" error. But he can login in the website in any other computer.
Sometimes, if he deletes cache or reset his password can access to the website.
I'm saving in the 'User' mongodb collection an array of tokens like this:
{
........ (Other params),
"token" : {
"d222b6a854d35c9c9584e695b623c468" : "nX0CuAraUQMGm5UsUWhUqZzgXZnapN",
"8c27b0d66a7ea6cec5dda9979cc92bd3" : "swdYhSQN5el0x9Pmn2YXZuwckpmuHP",
"28b825f204e7ebd320756bd6294a29c1" : "UFGd18db8W9gq1WDXgx4F9BZRVRY3K"
}
}
This token array contains:
key: MD5 encrypted User-Agent
value: Random string
This keeps session for different devices and browsers.
Everytime the user wants to do something in the web I put in the route the user id and the token (value), and I check if values are correct:
....
$uid = md5($_SERVER['HTTP_USER_AGENT']);
if(isset($user->token[$uid]) && $user->token[$uid]==$token){
....
return true;
}else{
return false;
}
I thought that the problem was with the User-Agent. Any solution?
Thanks!
I'm trying to prevent the user to create the same username. well my real problem is how to loop a list of data from model in controller. Maybe we know how to loop it in view by using this -> data['user'] and in view we can call $user. but how can we do that in controller layer.
here's my code
Controller
$username = strtolower($this->input->post('name'));
$fixUsername = str_replace(" ",".",$username);
$counter = 1;
$list[] = $this->addusermodel->getAllUsername();
for($i=0;$i<sizeof($list);$i++) {
if($list[$i] == $fixUsername) {
$counter = 0;
}
}
if($counter == 0) {
$data['result'] = "The username has already been taken";
$this->load->view('adduserview',$data);
} else {
$data = array(
'Nama' => $this->input->post('name'),
'Username' => $fixUsername."#praba",
'Password' => md5($this->input->post('password')),
'created' => date("Y-m-d h:i:sa"),
'createdBy' => $createdBy,
'lastModified' => date("Y-m-d h:i:sa"),
'lastModifiedBy' => $lastModifiedBy
);
$this->addusermodel->saveUser($data);
//$data['Username'] = $listName;
$data['message'] = "New user successfully added.";
$data['messageContent'] = "The username: ".$fixUsername."#praba". $counter;
$this->load->view('successpageview',$data);
//redirect('successpageview','refresh');
}
my model (is like usual)
function getAllUsername() {
$this->db->select('Username');
$this->db->from('tbluser');
$query = $this->db->get();
return $query->result_array();
}
I think a better approach would be to create another function in your model, which searches your database by ID, or by email, or by another unique field. If the function returns a row - then the user exists. If it returns nothing - then add a new user.
I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)
Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
How to print certain properties in the model while returning data to user
I have Users model , which has Username, Password, Email
I can get all users username, email
Now i need to send Username and email to user
while trying to send data to the user as json from the following code
$models = Users::model()->findAll($criteria);
if(is_null($models)) {
$this->_sendResponse(200, sprintf('No users found'));
} else {
$rows = array();
foreach($models as $model)
{
$Users[] = $model->attributes;
}
$SandboxObj->_sendResponse(200, CJSON::encode($Users));
}
It shows like [{"Username":"foo","Email":"foo#foo.com","Password":"null"}]
I need to send like [{"Username":"foo","Email":"foo#foo.com"}]
How to do this in yii?
I know this question is already been answered and accepted but i do not like to teach people the lazy way of coding. there for, as a correction on Alireza Fallah's answer:
$models = Users::model()->findAll($criteria);
if(is_null($models)) {
$this->_sendResponse(200, sprintf('No users found'));
} else {
$userData = array();
foreach($models as $model)
{
$tempData = new StdClass;
$tempData->Username = $model->Username;
$tempData->Email= $model->Email;
$userData[] = $tempData;
}
$SandboxObj->_sendResponse(200, CJSON::encode($userData));
}
or as said before only query what you need in the first place, then you can be lazy all you want in the rest of your code.
Edit: another way of doing the foreach with less resources is :
foreach($models as &$model)
{
$tempData = new StdClass;
$tempData->Username = $model->Username;
$tempData->Email= $model->Email;
$model = $tempData;
}
and then you can use $models in stead of $userData
Do this :
$models = Users::model()->findAll($criteria);
if(is_null($models)) {
$this->_sendResponse(200, sprintf('No users found'));
} else {
$rows = array();
foreach($models as $model)
{
unset($model->attributes['Password']); //add this line
$Users[] = $model->attributes;
}
$SandboxObj->_sendResponse(200, CJSON::encode($Users));
}
Or simply don't select Password field in your query if you don't need it .
I am using Codeigniter to create an Autocomplete for user names:
Using the parameter : search-user?term=s I get the following data back as Json :
{"id":"1","value":"Stuart Blackett"}{"id":"2","value":"Simon Wilton"}
However when I am running the auto select, On the search for say "St" it brings back by name in the options, But also the ID as well.
How do I prevent this from happening? I suspect my loop could be the issue.
My PHP Function is as follows :
function search_user()
{
$term = $this->input->get('term');
$user_search = $this->vendor_model->search_user($term);
$user['response'] = 'false';
if(count($user_search) > 0)
{
$user['response'] = 'true';
$user = array();
foreach($user_search as $user)
{
$user = array(
'id' => $user->user_id,
'value' => $user->user_firstname .' '. $user->user_surname
);
echo json_encode($user);
}
}
}
{"id":"1","value":"Stuart Blackett"}{"id":"2","value":"Simon Wilton"} isn't valid JSON.
Try not echoing each $user's information separately - instead, build a new array of users and json_encode() that array. Example:
foreach($user_search as $user) {
$users[] = array(
'id' => $user->user_id,
'value' => $user->user_firstname .' '. $user->user_surname
);
}
echo json_encode($users);