PHP array to json with key/index specification - php

I'm trying to add a array to a json file using php.
How I want it to look (formatting does not matter):
{
// Already stored in json file
"swagg_ma_blue":{
"user":"swagg_ma_blue",
"admin":true,
"user_id":"000"
},
// Should be added using php
"dnl":{
"user":"dnl",
"admin":"true",
"user_id":"000"
}
}
How my outcome actually looks like:
{"swagg_ma_blue":{"user":"swagg_ma_blue","admin":true,"user_id":"000"},"0":{"user":"d4ne","admin":true,"user_id":"000"}}
As you see the array index/key of the second element is called "0" but I need it to have the user value.
My code:
<?php
class add_mod_class {
function __construct($username, $status){
$this->username = $username;
$this->status = $status;
$this->user_id = '000';
$this->json_file = 'includes/json/mods.json';
}
function get_json(){
$json_content = file_get_contents($this->json_file);
$json = json_decode($json_content, true);
return $json;
}
function mod_handler(){
if($this->status == 'admin'){
return true;
}else{
return false;
}
}
function add_mod(){
$mods = $this->get_json();
$data = array(
'user' => $this->username,
'admin' => $this->mod_handler(),
'user_id' => $this->user_id
);
array_push($mods, $data);
$new_json_string = json_encode($mods);
return $new_json_string;
}
}
?>
First idea was to use was:
$data[$this->username] = array(
'user' => $this->username,
'admin' => $this->mod_handler(),
'user_id' => $this->user_id
);
But this would still return "0": in it. I Would appreciate every kind of help.

Your first approach was fine, except you should assign to $mods array instead of $data. Here is the corrected function:
function add_mod(){
$mods = $this->get_json();
$mods[$this->username] = array(
'user' => $this->username,
'admin' => $this->mod_handler(),
'user_id' => $this->user_id
);
$new_json_string = json_encode($mods);
return $new_json_string;
}

Related

How to pass calculated/final value of one function to other functions in a controller of Codeigniter application

Using sessions we can achieve this, but need this without sessions or cookies.
<?php
class Employees extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew()
{
$response = array();
$this->auth(); // this value is always null returned by auth() method
}
}
?>
This is more of a OOP programming basics question. If you want to re-use a variable in another function of the same controller object, you have to set the variable globally for the Employees class and then set/get its value in your functions by using $this->yourVariableName. But the set value of the object instance can only be reused in that instance only. Which means that after the auth() function, another function should be called subsequently to "access" the $this->yourVariableName.
Another way is to pass the $jwtoken as a parameter to a function.
But the following code answers your question "How to pass calculated/final value of one function to other functions in a controller of Codeigniter application", if it doesn't, then your question should be corrected I guess.
Edit:
Ow ok, first the auth() function is being called, then you would like to pass the $jwtoken value to another function, am I right? Well once a function is finished executing, the variable "disappears" if not passed to another function. If you would like to process the $jwtoken value immediately within the auth() function, then the answer is to pass the $jwtoken value to another function from within the auth() function:
<?php
class Employees extends CI_Controller
{
public function __construct() {
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
// this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
$this->addNew($jwtoken);
// What is the addNew() supposed to do?
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew($jwtoken = "default_value_if_not_set") {
echo $jwtoken;
}
}
Since you are creating an API, I assume the API is a REST api and stateless, so there is no interference of sessions and cookies.
I assume your process works like this:
User does a login request from the app to the api and the api returns a token when the credentials check is valid
The token is stored in the app (in a local database for example) and used for other requests
So the only thing you need to do is (I assume you have a route to addNew):
public function addNew() {
$token = $this->input->get('token');
$loginData = $this->validateToken($token);
//... add new process
}
And from your app you need to pass the token with the request to the api.
How do you validate the token?
To obtain the data you have set in the token, you have to decode the token:
/**
* throws SignatureInvalidException
*/
function validateToken($token)
{
$jwt = new JWT();
return $jwt->decode($token, jwtSecretKey, 'HS256');
}
Code improvement
Avoid using sessions and cookies
Since your api is stateless, you have to avoid settings cookies or sessions. So in your controller you can remove the flash data helper:
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
# REMOVE THIS LINE
# $this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => "Wrong email or password", //CHANGE THIS LINE
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
# REMOVE THIS LINE
# $this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => "Scucessfully login!", //CHANGE THIS LINE
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
Return the output response instead of $jwtoken
In your response you have already set the the token, so you can simply return the response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($response));
Your query is vulnerable to sql injections
Use escape method around you variables or bind the params:
$sql = "select * from admin_tbl where email=? and password = ?";
$query = $this->db->query($sql, array($adminEmail, $adminPassword));

Laravel get data out of foreach loop

The below code shows the error (on the line if ($response) {):
Undefined variable: response
I am checking the if condition inside the foreach because I wanted to check whether each id in the UserEnabledNotifications table exists in notifications table. Also dump($response); inside the if condition of foreach shows data.
Can I get the data in $response outside the foreach loop? What shall I try?
$notificationData = UserEnabledNotifications::all();
foreach ($notificationData->where('status', 'true') as $user => $value) {
if (Notifications::where('userEnabledNotificationsId', $value['id'])->exists() == false) {
$notificationTypeName = NotificationTypes::where('id', $value['notificationTypesId'])
->value('notificationTypeName');
$userData = User::where('id', $value['userId'])
->get()
->toArray();
$data = [];
$data['notificationTypesId'] = $value['notificationTypesId'];
$data['notificationTypeName'] = $notificationTypeName;
$data['userId'] = $value['userId'];
$data['email'] = $userData[0]['email'];
$data['recipientName'] = $userData[0]['FullName'];
$data['userEnabledNotificationsId'] = $value['id'];
$response = Notifications::create($data);
//dump($response);
$tags[] = $response;
}
}
if ($response) {
return response()->json([
'message' => 'success',
'data' => $tags,
'statusCode' => 200,
'status' => 'success'
], 200);
}
You define $response in first if body but you need $response = null above that.
You might create a private or protected variable, and put it outside, and then access it directly or via functions
$notificationData = UserEnabledNotifications::all();
private $reponse = null;
foreach ($notificationData->where('status', 'true') as $user => $value) {
if(Notifications::where('userEnabledNotificationsId',$value['id'])->exists()==false){
$notificationTypeName = NotificationTypes::where('id', $value['notificationTypesId'])->value('notificationTypeName');
$userData = User::where('id', $value['userId'])->get()->toArray();
$data = [];
$data['notificationTypesId'] = $value['notificationTypesId'];
$data['notificationTypeName'] = $notificationTypeName;
$data['userId'] = $value['userId'];
$data['email'] = $userData[0]['email'];
$data['recipientName'] = $userData[0]['FullName'];
$data['userEnabledNotificationsId'] = $value['id'];
$response = Notifications::create($data);
$tags[] = $response;
}
}
if ($response) {
return response()->json([
'message' => 'success',
'data' => $tags,
'statusCode' => 200,
'status' => 'success'
], 200);
}
But now each place you would need to check whether responses are null or not.
Why private or protected or public?
Check this answer : What is the difference between public, private, and protected?
I quote
public scope to make that property/method available from anywhere, other classes, and instances of the object.
private scope when you want your property/method to be visible in its own class only.
protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.
Simply declare a null or an empty array in a $response variable and you will be able to get the data out of the loop!

inside if() cant call another function

public function addcategory() {
$this->load->model('product_model');
$new_category = $this->product_model->add_category($this->input->post());
if ($new_category) {
$info = array(
'message' => 'Data Saved sucess',
'value' => TRUE
);
$this->index($info);//not working
}
$this->index($info);//working without $info
}
here i need to call $this->index($info); within the if(){} but it is not working... however when i put this code outside if() it works but i cant pass $info variable via $this->index($info);
I call the function($this->index($info);) in side if then function not working at all. But if i used function outside if its get call but giving an error 'Undefined index: info'.
How to call the index() function??
Declare $info outside the if statement should work.
Then use the index function outside the statement.
public function addcategory() {
$info = null;
$this->load->model('product_model');
$new_category = $this->product_model->add_category($this->input->post());
if ($new_category) {
$info = array(
'message' => 'Data Saved sucess',
'value' => TRUE
);
}
$this->index($info);//working without $info
}
Solution1:
You can use Redirect method to redirect on index :
$this->session->set_flashdata('info', $info);
redirect('/controller_name/index');
And get the info on index method :
$info = $this->session->flashdata('info');
Solution2:
Add this Remap Function to your controller :
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->index();
}
}
Your if statement is not doing anything with the variable $new_category
try.
if (isset($new_category) && !empty($new_category)) // check for the existence and value
{
$info = array(
'message' => 'Data Saved sucess',
'value' => TRUE
);
$this->index($info);
}
else
{
$info = array(
'message' => 'unsuccessful data entry',
'value' => FALSE
);
}

Laravel 4.2 session::get() method not returning session data in controllers

Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}

CakePHP change DATABASE_CONFIG variables, based on user input for custom datasource

I am looking for a way to access and change the DATABASE_CONFIG variables, based on user input. Using CakePHP I created a custom datasource, based on the one provided in the docs, to access an external API. The API returns a JSON string containing the 12 most recent objects. I need to be able to change the page number in the API request to get the next 12 results, as well as accept a free text query entered by the user.
app/Config/Database.php
class DATABASE_CONFIG {
public $behance = array(
'datasource' => 'BehanceDatasource',
'api_key' => '123456789',
'page' => '1',
'text_query' => 'foo'
);
}
app/Model/Datasource/BehanceDataSource.php
App::uses('HttpSocket', 'Network/Http');
class BehanceDatasource extends DataSource {
public $description = 'Beehance datasource';
public $config = array(
'api_key' => '',
'page' => '',
'text_query' => ''
);
public function __construct($config) {
parent::__construct($config);
$this->Http = new HttpSocket();
}
public function listSources($data = null) {
return null;
}
public function describe($model) {
return $this->_schema;
}
public function calculate(Model $model, $func, $params = array()) {
return 'COUNT';
}
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] === 'COUNT') {
return array(array(array('count' => 1)));
}
$queryData['conditions']['api_key'] = $this->config['api_key'];
$queryData['conditions']['page'] = $this->config['page'];
$queryData['conditions']['page'] = $this->config['text_query'];
$json = $this->Http->get('http://www.behance.net/v2/projects', $queryData['conditions']);
$res = json_decode($json, true);
if (is_null($res)) {
$error = json_last_error();
throw new CakeException($error);
}
return array($model->alias => $res);
}
}
Is there anyway to access and change the $behance array, or is there another way to go about accessing an external API with cakePHP that I am totally missing?

Categories