PHP variable scoping - php

I'm having some trouble with variable scoping in PHP. Here's the structure of my code--
<?php
$loader = new ELLoad();
$sessionid = '';
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
global $loader;
$loader->load($file['text']);
global $sessionid;
$sessionid = $loader->getSessionId();
}
if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
global $sessionid;
$extractor->extract($sessionid); //$session id for some reason is still ' ' here
}
The sequence of the requests from the client is always load followed by extract. Can anyone tell me why my $sessionid variable may not be getting updated right?

$sessionid is still '', because It's not change if first condition == false
Improvement of your code:
$loader = new ELLoad();
$sessionid = $loader->getSessionId();
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
$loader->load($file['text']);
// do more stuff
}
else if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
$extractor->extract($sessionid);
// do more stuff
}
Also It's better to use $_GET or $_POST depend on your case, instead of $_REQUEST and finally using else if in separate and repeated conditions.

You don't have to declared global $... unless you're in a function. A block (if, while, ...) have the same scope than the line just before.
I don't know what you want to do, but you have to keep you $sessionid content in a real session, like:
<?php
session_start();
$loader = new ELLoad();
$_SESSION['id'] = '';
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
$loader->load($file['text']);
$_SESSION['id'] = $loader->getSessionId();
}
if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
$extractor->extract($_SESSION['id']); //$session id for some reason is still ' ' here
}

Related

Concrete5 8.3 implement Ajax other view

I have a problem recovering a variable in a view.
I followed this tutorial:
Once I have the other view, I can not send a variable so that I can get it back in the view.
Controller.php
public function action_like($token = false, $bID = false)
{
if ($this->bID != $bID) {
return false;
}
if (Core::make('token')->validate('like_page', $token)) {
$page = Page::getCurrentPage();
$u = new User();
$this->markLike($page->getCollectionID(), $page->getCollectionTypeID(), $u->getUserID());
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$b = $this->getBlockObject();
//Normaly we set a variable for get in the view
// $this->set('test', 'test');
$bv = new BlockView($b);
$bv->render('view/view');
} else {
Redirect::page($page)->send();
}
}
exit;
}
view/view.php
<?php echo $test; ?>
<p> Title <p/>
thanks for answers
Sessions provide a way to store information across multiple
requests/pages.
You may use :
//...
$_SESSION["test"] = "test";
//...

Pass custom values from parentOrderController to order-payment.tpl

I had modified some part of reorder in parentOrderController, created a variable. Now I want to pass that variable into the order-payment.tpl so that I can check a condition with that. Can someone please help me?
ParentOrderContoller.php(Added Part)
if (Tools::isSubmit('submitPay') && $id_order = (int)Tools::getValue('id_order')) {
//To check the order is in print ready state
$order = new Order((int)$id_order);
$current_order_state = $order->getCurrentOrderState();
$current_order_state_id = $current_order_state->id;
//ends here
//d($current_order_state_id);
// $this->context->cookie->current_order_state_id = $current_order_state->id;
$oldCart = new Cart(Order::getCartIdStatic($id_order, $this->context->customer->id));
$duplication = $oldCart->duplicate();
if (!$duplication || !Validate::isLoadedObject($duplication['cart'])) {
$this->errors[] = Tools::displayError('Sorry. We cannot renew your order.');
} elseif (!$duplication['success']) {
$this->errors[] = Tools::displayError('Some items are no longer available, and we are unable to renew your order.');
} else {
$this->context->cookie->id_cart = $duplication['cart']->id;
$context = $this->context;
$context->cart = $duplication['cart'];
CartRule::autoAddToCart($context);
$this->context->cookie->write();
d(Configuration::get('PS_ORDER_PROCESS_TYPE'));
if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
Tools::redirect('index.php?controller=order-opc');
}
Tools::redirect('index.php?controller=order');
}
}
I want $current_order_state_id to be passed to order-payment.tpl. How to do it?
You should be able to do it with:
$this->context->smarty->assign(array(
'current_order_state_id' => $current_order_state_id
));
Just a side note. If the variable is not always set, in your template check using the:
{if isset($current_order_state_id)}
code
{/if}

A better way to check if GET isset and set variable?

Hello I'm having trouble thinking of a way to set custom variables with there $_GET counterpart in a cleaner way than below, this is a post-back for the url http://example.com/postback.php?id={offer_id}&offer={offer_name}&session={session_ip}&payout={payout} after running I get all $_GET with either their data or nil for all variables: $id, $offer, $session, $payout obviously i am a php newbie, please go easy on me! Thanks, any help would be great.
if (s('id')) {
$id = $_GET["id"];
} else {
$id = 'nil';
}
if (s('offer')) {
$offer = $_GET["offer"];
} else {
$offer = 'nil';
}
if (s('session')) {
$session = $_GET["session"];
} else {
$session = 'nil';
}
if (s('payout')) {
$payout = $_GET["payout"];
} else {
$payout = 'nil';
}
function s($name) {
if(isset($_GET["$name"]) && !empty($_GET["$name"])) {
return true;
}
return false;
}
Use extract: http://php.net/manual/de/function.extract.php
// Assuming $_GET = array('id' => 123, etc.)
extract($_GET);
var_dump($id);
// And later in your code
if (isset($id)) {
// Do what you need
}
maybe you can use a universal wrapper
<?php
function getValue($key, $fallback='nil') {
if(isset($_GET[$key]) $val = trim($_GET[$key]);
else $val = null;
return ($val) ? $val : $fallback;
}
and then you can handle it easyer by
<?php
$id = getValue('id'); ...
isset is not needed, and maybe you can use the ternary operator.
$id = !empty($_GET["id"]) ? $_GET["id"] : null;
$offer = !empty($_GET["offer"]) ? $_GET["offer"] : null;
$session = !empty($_GET["session"]) ? $_GET["session"] : null;
$payout = !empty($_GET["payout"]) ? $_GET["payout"] : null;

variable scope in php function

Here is my script.
I declared few variable outside function. I want to use it in function, would it be available?
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('follow.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$userid = $content->{'id'};
$temp = "1";
$tweets1 = $connection->get("https://api.twitter.com/1.1/statuses/retweets_of_me.json?count=200");
$tweets3 = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?trim_user=true&include_rts=true");
$tweets4 = $connection->get("https://api.twitter.com/1.1/statuses/home_timeline.json?include_rts=true&trim_use=true");
foreach ($tweets1 as $item)
{
$text = $item->text;
$follow_count = getfollow($m[1]);
echo "followe count is $follow_count <br>";
lookup($item->user->id_str);
}
function lookup($userid)
{
//echo "userid : $userid temp : $temp";
$tweets5 = $connection->get("https://api.twitter.com/1.1/users/lookup.json?user_id='.$userid.' ");
$CONNECTION IS not availabl here? WHY?
foreach ($tweets5 as $item)
{
$text = $item->name;
}
return;
}
?>
A function has its own scope. You have to provide all variables you want to use in arguments except if they are in the $_SESSION, $_SERVER etc. variables.
Hand it over via parameter:
function lookup($userid, $connection) {
//code here
}
Only Superglobals are availible inside functions. Everything else is handed over via parameters.
You can use outside variable by defining them as global or you can pass them to functions as a parameters.
$str= 'str';
function test()
{
global $str;
echo $str;
}
or
function test($str)
{
echo $str;
}
using the global keyword should do the trick:
$foo = '123';
function bar() {
global $foo;
echo $foo;
}
but the way I see it, you could just pass the variable to that function instead.

How to combine two internal PHP functions?

I have two code blocks that are PHP functions that do two different things. They are:
<?php
if (!function_exists('UserPhotoDefaultUrl')) {
function UserPhotoDefaultUrl($User) {
$Email = GetValue('Email', $User);
$HTTPS = GetValue('HTTPS', $_SERVER, '');
$Protocol = (strlen($HTTPS) || GetValue('SERVER_PORT', $_SERVER) == 443) ? 'https://secure.' : 'http://www.';
$Url = $Protocol.'gravatar.com/avatar.php?'
.'gravatar_id='.md5(strtolower($Email))
.'&size='.C('Garden.Thumbnail.Width', 50);
if (C('Plugins.Gravatar.UseVanillicon', FALSE))
$Url .= '&default='.urlencode(Asset('http://vanillicon.com/'.md5($Email).'.png'));
else
$Url .= '&default='.urlencode(Asset(C('Plugins.Gravatar.DefaultAvatar', 'plugins/Gravatar/default.gif'), TRUE));
return $Url;
}
}
and...
<?php
class GravatarPlugin extends Gdn_Plugin {
public function ProfileController_AfterAddSideMenu_Handler($Sender, $Args) {
if (!$Sender->User->Photo) {
$Email = GetValue('Email', $Sender->User);
$Hash = md5($Email);
$Sender->User->Photo = 'http://w'.substr($Hash, 0, 1).'.vanillicon.com/'.$Hash.'_200.png';
}
}
}
The first shows the Gravatar image for User avatar in post content of my script (Vanilla forums), and the second one shows the Vanillicons (Vanillicon is similar to Gravatar) of all the users participating in a discussion in the sidebar (under 'In This Discussion'). I hope you get the idea as to what the two code blocks do now?
Using the how-it's-done code in the first code block, I need to modify the second code block to show Gravatar icons of all users participating in a discussion instead of Vanillicons. Can someone who knows PHP help?
<?php
if (!function_exists('UserPhotoDefaultUrl')) {
function UserPhotoDefaultUrl($User) {
$Email = GetValue('Email', $User);
$HTTPS = GetValue('HTTPS', $_SERVER, '');
$Protocol = (strlen($HTTPS) || GetValue('SERVER_PORT', $_SERVER) == 443) ? 'https://secure.' : 'http://www.';
$Url = $Protocol.'gravatar.com/avatar.php?'
.'gravatar_id='.md5(strtolower($Email))
.'&size='.C('Garden.Thumbnail.Width', 50)
.'&default='.urlencode(Asset(C('Plugins.Gravatar.DefaultAvatar', 'plugins/Gravatar/default.gif'), TRUE));
return $Url;
}
}
you class:
<?php
class GravatarPlugin extends Gdn_Plugin {
public function ProfileController_AfterAddSideMenu_Handler($Sender, $Args) {
if (!$Sender->User->Photo) {
$Sender->User->Photo = UserPhotoDefaultUrl($Sender->User); // not sure about the $Sender->User part because it is not displayed
}
}
}

Categories