How do I prepend the $ sign to a string to make it a variable?
Eg:
$consumer = array()
$industrial = array()//These 2 are in a separate include file.
$var = $_GET['val'] // value here is 'consumer'
function ('$'.$var,$bar) //I'm trying to make consumer -> $consumer
Not the best way to reach that value, but PHP supports: $$var :)
$$var
will be what you want. The second $ means that the value of the variable should be used as the name of the variable.
http://php.net/manual/en/language.variables.variable.php has more details.
$consumer = array()
$industrial = array()//These 2 are in a separate include file.
$var = $_GET['val'] // value here is 'consumer'
function ($$var,$bar) //I'm trying to make consumer -> $consumer
Don't forget to check that the value of $_GET['val'] is a value you (the programmer) expect and nothing else.
Why not just:
if ($_GET['val'] == 'customer') {
function($bar);
}
Just do the following:
$var = 'myString';
${$var} = 'output';
echo $myString;
Ok, here's that whitelisting you should definitely include.
$whitelist = array('customer', 'consumer');
$fallback = $whitelist[0];
$var = in_array($whitelist, $_GET['val'] ? $_GET['val'] : $fallback;
Related
We are using CleverReach to redirect people to our website after they have double opt-in their mail account. We redirect the email as a query parameter to our website, like: example.com/thanks?email=foo#bar.com (by setting up a redirect in the CleverReach backend like example.com/thanks?email={EMAIL}). Apparently, the email parameter doesnt get urlencoded by cleverreach.
Now, in Drupal, if the URL is like so: example.com/thanks?email=hello+world#bar.com and using this code:
$request = \Drupal::request();
$email = $request->query->get('email');
$email is hello world#bar.com. Now, I dont know what the correct processing is here. Obviously, I cant tell CleverReach to urlencode their redirects beforehand. I dont even know if that would be best practice or if I need to imlement something...
The only thing I found out is that $_SERVER['QUERY_STRING'] contains the "real" string, which I can urlencode and then redirect, and then, by reading the query params, urldecode them. But I feel like I am missing some crucial inbuilt functionality.
TL;DR
If a website redirects to my website using not urlencoded query params, how do I read them?
My current approach:
<?php
public function redirectIfIllegalUri() {
$request = \Drupal::request();
$email = $request->query->get('email', '');
$needsRedirect = (false !== strpos($email, ' ') || false !== strpos($email, '#'));
if ($needsRedirect && isset($_SERVER['QUERY_STRING']) && false !== strpos($_SERVER['QUERY_STRING'], 'email=')) {
$sqs = $_SERVER['QUERY_STRING'];
$sqs = htmlspecialchars($sqs);
$sqs = filter_var($sqs, FILTER_SANITIZE_STRING);
$sqs = filter_var($sqs, FILTER_SANITIZE_ENCODED);
$sqs = urldecode($sqs);
$sqs = explode('&', $sqs);
foreach ($sqs as $queryParam) {
if (false === strpos($queryParam, 'email=')) continue;
$values = explode('=', $queryParam);
$email = $values[1];
}
$emailEncoded = urlencode($email);
$query = $request->query->all();
$query['email'] = $emailEncoded;
$refreshUrl = Url::fromRoute('<current>');
$refreshUrl->setOptions([
'query' => $query,
]);
$response = new RedirectResponse($refreshUrl->toString(), 301);
$response->send();
return;
}
}
$request = \Drupal::request();
$email = urldecode($request->query->get('email', false));
drupal request() docs
The problem you are facing is that the + will be treated as a space when you get the value from $_GET global variable.
Currently in PHP doesn't exist a method that returns these values without urldecoding and you need to build a custom function to achieve what you are asking:
A simple function will return not encoded input is by using this function:
function get_params() {
$getData = $_SERVER['QUERY_STRING'];
$getParams = explode('&', $getData);
$getParameters = [];
foreach ($getParams as $getParam) {
$parsed = explode('=', $getParam);
$getParameters[$parsed[0]] = $parsed[1];
}
return $getParameters;
}
This solution can be used if you do not have any other option. By using this function you will always get the data encoded.
If you can encode the value from cleverreach then the best approach is to encode it there.
Encoding the value in cleverreach for email hello+world#bar.com will give you this url example.com/thanks?email=hello%2Bworld%40bar.com and in $_GET you will have the email containing the + sign.
look at this syntax of variable name modifying:
${'a' . 'b'} = 'hello there';
echo $ab;
this returns "hello there"
But i want do declare defined variables dynamical.
$error_code = $_GET[error_code]; //for example: 404
define(E404, 'Not found');
echo E{$error_code};
It return error, i want to generate E404 dynamical on php codes and get its value.
I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research.
You need to call constant() to retrieve the value of a constant from a string. Your example should look like:
$error_code = 404;
define('E404', 'Not found');
echo constant("E{$error_code}");
and it will display Not found.
<?php
$ErrorCode = $_GET['error_code']; // Where error_code = 404
$Errors = array(); // here we are creating a new array.
$Errors[$ErrorCode] = "Whatever"; // here we are setting a key of the new array, with the keys name being equal to the $ErrorCode Variable
print_r($Errors); // Would return Array( [404] => Whatever);
echo $Errors["404"]; // Would return Whatever
?>
Well Php has a feature called variable variables. See this link: http://php.net/manual/en/language.variables.variable.php. It allows a variable name to be assigned to a variable.
I was using variables in my php file without declaring them. It was working perfect in old version of localhost (i.e vertrigoServ 2.22).
But when I moved to latest version of localhost (i.e xampp 3.2.1), I encountered variables declaration warnings and errors something like this:
Notice: Undefined variable: att_troops_qty in D:\Installed
Programs\htdocs\dashboard\WarLord\PHP_Code\MyAjax.php on line 1247
So I declared all the variables at the top of php file like this:
$page = "";
$att_troops_qty = "";
$def_troops_qty = "";
$ca_level = "";
$b_level = "";
$pre_buildings = "";
$created_pre_b = "";
$building_id = "";
$building_loc = "";
$ca_1_b_loc = "";
$ca_1_b_level = "";
$ca_2_b_loc = "";
$ca_2_b_level = "";
It solved the problem But I have confusion that this is not the proper way to declare variables.
Is there some more better way for variables declaration?
How you are declaring is perfectly alright and proper way.
$test = "";
or
$test = null;
these both are proper ways for declaring empty variables.
for more info please visit http://php.net/manual/en/language.types.null.php
You need to declare variables before echoing them out. An example is here:
<?php
$var = "test";
echo $var; // it will echo out test
?>
And trying to echo out a variable this way will generate an error:
<?php
echo $var; // it will generate error
$var = "test";
?>
In addition, you can declare variables in another file and can include that file to echo out the variable somewhere. Remember to include the file first and then call it.
Example vars.php:
<?php
// define vars
$var1 = "Test 1";
$var2 = "Test 2";
?>
Now in another file, include vars.php first and then call the variable:
<?php
require_once"vars.php";
echo $var1;
?>
You cannot use undeclared variables but
you can declare them on the go.
Inside functions you can do something like that:
function abc() {
return $newVar or null; // without variable declaration
}
If $newVar is not declared before function will return null;
Or better way:
function abc($newVar = null) {
return $newVar; // with variable declaration
}
The best way to check whether the variable is declare or not, is to use the isset() function, which checks whether the variable is set or not like:
<?php
if(isset($a)){
// execute when $a is set ( already declare ) or have some value
}
else {
// execute when $a not set
}
?>
You can declare variables in php as
<?php
$test = "xyz" //for String datatype
$test1 = 10 //for integer datatype
?>
Name of a variable declared must be alphanumeric and you don't need to specify the type.
I'm building a simple JS terminal shell emulator which posts its commands via AJAX to PHP.
Please leave security aside, this is only for learning and demo purposes.
Now my problem is, str_replace() won't work as expected, in fact, it returns the unchanged input string. It should work like this:
The name of this host is $hostname --> Yes, this string contains a variable --> Replace $hostname with testserver --> return The name of this host is testserver
What am I doing wrong?
This is my respond script for echo and export:
<?
// get environment variables from JSON
$vars = json_decode(file_get_contents('environment.json'), true);
// get request params
$method = $_SERVER['REQUEST_METHOD'];
$action = $_POST['action'];
$data = $_POST['data'];
switch ($action) {
case 'echo':
$cmd = $data;
// if the string in question contains a variable, eg. "the time is $time"
if (strpos($cmd,'$')) {
$output = '';
// for each environment variable as variable => value
foreach ($vars as $var => $val) {
// replace every variable in the string with its value in the command
$output = str_replace($var,$val,$cmd);
}
echo $output;
} else {
// if it does not contain a variable, answer back the query string
// ("echo " gets stripped off in JS)
echo $cmd;
}
break;
case 'export':
// separate a variable declaration by delimiter "="
$cmd = explode('=',$data);
// add a $-sign to the first word which will be our new variable
$var = '$' . array_shift($cmd);
// grab our variable value from the array
$val = array_shift($cmd);
// now append everything to the $vars-array and save it to the JSON-file
$vars[$var] = $val;
file_put_contents("environment.json",json_encode($vars));
break;
}
Better using :
if (strpos($cmd,'$') !== false) {
Then, every single replace will take the "first" data as its input data. You should proceed like this :
$output = $cmd;
// for each environment variable as variable => value
foreach ($vars as $var => $val) {
// replace every variable in the string with its value in the command
$output = str_replace($var, $val, $output);
}
If you are calling php page from web, you can give as
../../somepage.php?myid=1&trackno=2&anotherparam=3
and then you can use $_REQUEST or $_GET to retrieve the information
In command line, you can use
$options = getopt("a:b:c:"); to get the options that are passed through arguments
How to make sure, same source works either in web or in command line?
Let say your requests are like following;
WEB: http://domain.com/somepage.php?myid=1&trackno=2&anotherparam=3
CLI: php /path/to/this/php/file/somepage.php 1 2 3
You can use following php code;
<?php
if (!empty($_REQUEST)) {
$myid = $_REQUEST["myid"];
$trackno = $_REQUEST["trackno"];
$anotherparam = $_REQUEST["anotherparam"];
} else if (!empty($argv)) {
$myid = $argv[1];
$trackno = $argv[2];
$anotherparam = $argv[3];
} else {
die("Invalid request!");
}
You have already know how to handle web requests, you can refer here for more detail about $argv. Simply,
$argv[0] => scriptname(somepage.php),
$argv[1] => first param, ...,
$argv[n] => (n-1)th param
Edit:
In order to not miss order of commandline arguments, you can use naming conventions like;
php somepage.php myid_1 anotherparam_2 trackno_3
and you can use following to handle this;
foreach ($argv as $k => $v) {
if ($k == 0) continue;
$temp = explode("_", $v);
${$temp[0]} = $temp[1];
}
Simply,
myid_3 becomes $myid = 3;
variable names hidden in the values so you don't need to know about sequences