Set and get global variable in php (ZendFramework) - php

I am using ZendFramework with PHP, and I want to set and get a variable as a global variable. I.E. I set it in the class of Zend Controller and access it any action in the class.
For example:
<?php
class SubscriptionController extends Zend_Controller_Action
{
private $EMAIL = false;
private $USERNAME = false;
First I am validating email addres with ajax call
public function checkusernameAction()
{
$email = //query to find email;
if($email){
$EMAIL = true;
}else{
$EMAIL = false;
}
}
then I want subscribe user on the basis of private variable again with ajax call
public function subscribeAction
{
if($EMAIL == true)
{
//some stuff
}
}
I am getting private var by $this->EMAIL, but not able to access it

You can use Zend_Registry to use the variable throughout application.
You can set a variable like this
Zend_Registry::set('email', $EMAIL);
and later can get it like this
$email= Zend_Registry::get('email');

Looks to me like you are making two distinct requests calling, respectively, checkusernameAction() and subscribeAction(). Since these are distinct requests, the email value you set in the controller during checkusernameAction() will be gone on the second request which calls subscribeAction(). It's the same controller class, but you are looking at two distinct instances, one in each request.
As I see it, you can either:
Pass the email address in each AJAX request, but this seems unlikely since you get the email address from the first call to checkusernameAction().
Save the email in the session during the first checkusernameAction() call and then pick it up during the second subscribeAction() call.
Extract the "get email from username" code into a separate class or method and then call it in both places. After all, you don't want to get bitten by a "race condition" in which the state of the system changes between the two AJAX requests (maybe the user's email changes via some other process or via another set of requests that occur after the first AJAX request containing the call to checkusernameAction().

You can also used a function for set and get a value.
// Setter function
public function setConsumerKey($key)
{
$this->_consumerKey = $key;
return $this;
}
// Getter function
public function getConsumerKey()
{
return $this->_consumerKey;
}

Related

How to redirect different page from same controller function in laravel 5.2

I want to redirect 2 different page from this controller function along with value.Here is my code. It works but both of time url become same.what shuld I do?
//in routes.php
Route::post('/','mycontroller#check');
// in controller.php
public function check(Request $request)
{
$c_email = $request->email;
$c_pass=$request->pass;
$c_type=$request->select;
$var=DB::select("SELECT * FROM reg where email = '$c_email' and Password = '$c_pass' and type = '$c_type'");
if ($var) {
return view('farmer')->with('user',$var);
// return redirect('farmer')->with('user',$var);
}
else {
$msg="Invalid login";
return view('index')->with('show',$msg);
}
}
If you want to actually redirect u can use the redirect() helper as statet in the official docs https://laravel.com/docs/5.3/redirects
You can also pass data
redirect('/my-route')->with(['user' => $var]);
The passed data can then be accesses through the session helper
$var = session('user')
HOWEVER, it seems like you have major issues in your code. Your password does not seem to be encrypted. Also there's no reason to use plain sql instead of eloquent here.
The route that is shown in the browser is defined in your
Route::post('/','mycontroller#check');
If you just return different views, the route does not change. You need to redirect to other views.
If you redirect to other routes you will ofcourse need to add / define them.
Route::get('/my-route', function() {}); // or post etc.

How to validate a parameter for a class within a method and prevent use if invalid?

I am building a small class to handle api requests and I am running into an issue with error handling (I am also a novice at OOP so please with me) I need to restrict or throw an error with any methods in my class that require the user parameter to be set and I also need to samething if token has not been retreived and I can't seem to wrap my head around it.
This is what I have so far...
$user array is set in a config file outside of class like so (empty by default):
$user = array(
'user_email' = '',
'user_pass' = ''
);
Class for handling API (simplified for question)
class eventAPI {
private $user
private $token
public function __construct($user) {
$this->user = $user;
// if possible assign token when instantiated
$this->retrieve_token($user);
}
private function retreive_token($user) {
// Check if user parameter has been set
if($this->validate_user_parameter()) {
// use credentials to make HTTP request for token
$token = 'somerandomtoken';
// assign token property retreived value
$this->token = $token;
} else {
echo 'User parameter has not been set.' // Not real message just for testing
return FALSE;
}
}
public function show_all_events() {
// Check if token has been retreived
if($this->validate_token_retreived()) {
// Use token to retreive events list via HTTP request
} else {
echo 'API not active. No valid token detected'; // for testing purposes
return FALSE
}
}
// reduntant code... Can't wrap my head around another way for checking for token.
public function show_single_event() {
// Check if token has been retreived
if($this->validate_token_retreived()) {
// Use token to retreive events list via HTTP request
} else {
echo 'API not active. No valid token detected'; // for testing purposes
return FALSE
}
}
// This is mostly where I am confused how to solve.
private function validate_user_parameter() {
foreach($this->user as $key => $value) {
// Remove whitespace from value
$value = trim($value);
if(empty($value)) {
echo 'User credentials have not been set'; // for testing purposes
return FALSE;
}
}
}
private function validate_token_retreived() {
$result = FALSE;
// Bool value not sure if this is the best way to do this
if(isset($this->$token)) {
$result = TRUE;
}
return $result;
}
}
First issue: I need to validate the user parameter which is in an array so I can use with a private method to retrieve the token. I chose to use a foreach loop to check each value but it seems a little archaic.
Second Issue: I have a redundant check in place for each public method to check if token is valid. Is there a better way to do this with OOP? I have many methods that require the token.
In short, how can I make sure that once the class is instantiated a public method that will be used by end user will not fire if any validation fails. The user info only needs to be valid once when instantiated and then the token needs to be valid for most remaining methods.
You don't need to pass $user parameter to retreive_token function. You got it in class scope. Just use $this->user in the function to access it. Also you didn't use it in that function, so why u passed it?
You didn't send true in any function.
There's nothing wrong with for-each but you want to check array_map too. Atleast you're applying a function to every item in array. It can be usefull. ps: seems for-each still faster then array_map
Also you would want to check empty function on which cases it returns false
You can use multiple returns in a function. You dont need to set a variable to do that.
Example
private function validate_token_retreived()
{
if(isset($this->token))
return true;
return false;
}
You couldn't use else in most cases.
Example
public function show_all_events()
{
if($this->validate_token_retreived()) {
// Use token to retreive events list via HTTP request
// and return here
}
echo 'API not active. No valid token detected'; // for testing purposes
return FALSE; // do you really return here? seems you are just generating an output
}

How to use a SOAP API with login and session codeigniter

I have a set of soap APIs which can perform actions like login,logout,keepalive,access other several resources.Inorder to access the other resources,I have to pass a session id which I got from the login api.The session gets time out in 5minutes.
I am confused on how to make this working.
I am using codeigniter for my project,and I have built one library with the set of soap api requests defined in it.
class Soap_api
{
function __construct()
{
define("UID", "myuser");
define("PWD", "34rf3a45575");
define("API_ENDPOINT", "http://uat-api.testingsoapapi.in/services/smp");
define("PRODUCT_CODE", "24");
$resp = $this->keepAliveLib();
if($resp['ResponseCode'] == '0')
{
define("SessionID",$resp['SessionID']);
}
}
function keepAliveLib()
{
$resp = $this->login();
return $resp;
}
function one
{
//This function needs the sessionID receieved from login function
}
function two
{
//This function needs the sessionID receieved from login function
}
So when ever any of the functions from this class is accessed,the constructor calls the keepAliveLib which calls the login function residing in this class and return the session id to the constructor function and set it as global constant sessionID .So the function which I called will be using the that session ID which is made as a constant.
Is this the standard way of calling APIs which relay on sessions?The login function is called when ever a function is called and creates a different session ID.There is a function keepAlive in the library which can be used to maintaining the session,but instead of using keepAlive , Im logging each time a function in this is accessed.
Is there anything wrong in this flow?Can this be done in some other ways?
ok i'm probably not understanding this fully but would this work?
$resp = $this->keepAliveLib();
if($resp['ResponseCode'] == '0') {
$this->sessionid = $resp['SessionID']); }
else { // fail gracefully }
$this->sessionid is now available to any method in the controller.

can i send variable from action to another action by request post?

I called my action from other controller by this code:
Yii::import('application.controllers.ProvinceCityController');
$obj =new ProvinceCityController($id); // preparing object
echo $obj->actiondynamiccities(20);
Can I send my data(20) by post request ? Because actiondynamiccities() get $_POST and do something...
If you need to send a POST variable to a controller you can only do it by using AJAX.
If you want, you can send it by GET with a key to protect its security
Yii::import('application.controllers.ProvinceCityController');
$obj =new ProvinceCityController($id); // preparing object
echo $obj->actiondynamiccities(20, /*SECRET*/);
And in the ProvinceCityController
public function actionDynamicCities($id = null, $key = null)
{
$id = isset($_POST['id']) ? $_POST['id'] : $id;
if(!isset($_POST['id'] && strcmp($key, /*SECRET*/) != 0)
{ throw Exception here... }
...continue with code
}
Also, think of getting this kind of secret even for POST ids.
When a function is useful in multiple times across the multiple controllers, you have to maintain a separate class which can supply this functionality vai it's methods.
Ex: Create a class SharedFuncs and keep that file in components folder
<?php
class SharedFuncs
{
public function hello($name) {
return "Helloo..!, ".ucfirst($name);
}
}
?>
And access the methods any where in your project.
<?php
$utils=new SharedFuncs();
echo $utils->hello('maryam');
?>

codeiginter no direct access to functions

I'm having this problem about direct access to functions: for example I have this code:
controller users
function index(){
//this is my users index view, user can add,edit,delete cars
}
function details($id){
//a function where 1 car can be viewed in detail..
function add(){
//function to add car
}
Now if I go to address bar and type. localhost/myapp/users/detail it will go to the url and echo an error since $id is null. What I want is only the index is directly accessible if a user would type in the address bar. I don't want the users to go directly to myapp/users/add, etc..
CI Controller functions always must be able to handle user input (i.e. url segments), which means anyone can type in whatever they wish and make a request. You can't stop that. The best practice is to either:
Always provide default arguments
Use the URI class to get your parameters, or func_get_args()
Always validate the presence of and integrity of arguments passed to the controller, as you would with any other user input
Since it's much more common, accepted, and easier to read - just make sure to always provide defaults and validate them.
An example with your controller:
function index() {
//this is my users index view
//user can add,edit,delete cars
}
function details($id = NULL) {
if ( ! $id) {
// No ID present, maybe redirect without message
redirect('users');
}
$user = $this->user_model->get($id);
if ( ! $user) {
// ID present but no user found, redirect with error message
$this->session->set_flashdata('error_message', 'User not found');
redirect('users');
}
// We found a user, load view here etc.
}
function add() {
// Check for the presence of a $_POST value
// You could also use the Form_validation lib here
if ( ! $this->input->post('add_car')
{
$this->session->set_flashdata('error_message', 'Invalid request');
redirect('users');
}
// Try to add the car here and always redirect from here
}
The only other way is to make the method private or use CI's _underscore() naming as suggested (making it inaccessible from the url). You can still call the function in other methods if you wish, as in:
function index() {
if ($this->input->post('add_car')
{
// Call the private "_add" method
$this->_add();
}
// Load index view
}
So to make a long story short: You can't stop the requests from being made, you can only decide what to do when the request is invalid.
Add an underscore before the names of functions you want to hide:
function _details($id){
//a function where 1 car can be viewed in detail..
}
function add(){
//function to add car
}

Categories