I just wrote this and was thinking there must be an easier/more clean way to do this as it looks terrible doing it this way:
if(isset($_GET['m']) && isset($_GET['v'])) {
Router::Get($_GET['m'], $_GET['v']);
} elseif(isset($_GET['m'])) {
Router::Get($_GET['m'], "");
} else {
Router::Get("", "");
}
I'm looking for a cleaner way, like:
Router::Get(is('m'), is('v'));
Any suggestions to shorten/clean this kind of if-statements?
Can do,
$m = isset($_GET['m']) ? $_GET['m'] : "";
$v = isset($_GET['v']) ? $_GET['v'] : "";
Router::Get($m, $v);
You can encapsulate the logic:
Router::$query = $_GET;
Router::Get('m', Router::Get('v'))
class Router {
static public $query;
static function Get($name, $default = '') {
return isset(self::$query[$name]) ? self::$query[$name] : $default;
}
}
Related
Here my code :
$context = new Context;
$context->name = 'blabla';
if($original_lang === 'en') {
$context->en = $sentence;
} else if($original_lang === 'fr') {
$context->fr = $sentence;
} else if($original_lang === 'ja') {
$context->ja = $sentence;
}
$context->save;
I think the part with original lang is redundant, anyone know a best way to write this ? thanks !
You can write as below
$context->{$original_lang} = $sentence;
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;
I'm not so sure whether it is smart to post both problems in one question, but lets try:
So, I was checking my server's error log and it still has two notices, both about "Array to string conversion in [...]".
The first line should be this:
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
Context:
// Build an url which match a route
if ($this->use_routes || $force_routes) {
$url = $route['rule'];
$add_param = array();
foreach ($params as $key => $value) {
if (!isset($route['keywords'][$key])) {
if (!isset($this->default_routes[$route_id]['keywords'][$key])) {
$add_param[$key] = $value;
}
} else {
if ($params[$key]) {
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
} else {
$replace = '';
}
$url = preg_replace('#\{([^{}]*:)?'.$key.'(:[^{}]*)?\}#', $replace, $url);
}
}
$url = preg_replace('#\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\}#', '', $url);
if (count($add_param)) {
$url .= '?'.http_build_query($add_param, '', '&');
}
}
The second one is this line:
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
as part of this:
// legacy mode or default image
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ((Configuration::get('PS_LEGACY_IMAGES')
&& (file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg')))
|| ($not_default = strpos($ids, 'default') !== false)) {
if ($this->allow == 1 && !$not_default) {
$uri_path = __PS_BASE_URI__.$ids.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg';
}
} else {
// if ids if of the form id_product-id_image, we want to extract the id_image part
$split_ids = explode('-', $ids);
$id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]);
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ($this->allow == 1) {
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').$theme.'.jpg';
}
}
return $this->protocol_content.Tools::getMediaServer($uri_path).$uri_path;
}
public function getMediaLink($filepath)
{
return $this->protocol_content.Tools::getMediaServer($filepath).$filepath;
}
PHP is not my strength, so I have no idea what to do :/
Also I found some other questions about Array to string notices, but it seemed to me like you can't solve them the same way...
Thanks in advance for any help!
This error is appearing because some of the variables in these two lines are supposed to be String but they are actually array.
You need to print all the variables used in these 2 lines using the var_dump() function of PHP, this will tell you which of the variables are actually an Array, but they are supposed to be a String as per your code.
On the basis of the output, you need to modify your code to fix the issue.
1)
I have this:
function ObtainRequest($Field, $Method) {
$Returned = "";
if ($Method == "POST")
$Returned = $_POST[$Field];
else if ($Method == "GET")
$Returned = $_GET[$Field];
else
$Returned = $_REQUEST[$Field];
return $Returned;
}
Now, using the function:
if (isset(ObtainRequest("OneField","POST"))) {
DoSomething();
} else if (!isset(ObtainRequest("OneField","POST"))) {
DoOtherthing();
}
But my script isn't running (SHOWING PLANK PAGE)...
What's my mistake?
2)
The $_REQUEST is lost inside of function?
This code works!!:
if (isset($_REQUEST["OneField"])) {
DoSomething();
}
This code doesn't work!!:
if (isset(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
This code doesn't work!!:
if (empty(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
3)
Is it applicable to Session too?
Your mistake is here:
$Method == "Post"
But you passing uppercased POST:
ObtainRequest("OneField","POST")
Fix with strtoupper():
function ObtainRequest($Field, $Method) {
$Returned = "";
$Method = strtoupper($Method);
if ($Method == "POST")
$Returned = isset($_POST[$Field]) ? $_POST[$Field] : false;
else if ($Method == "GET")
$Returned = isset($_GET[$Field]) ? $_GET[$Field] : false;
else
$Returned = isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
return $Returned;
}
Also, this function might be shortened with switch construction:
function ObtainRequest($Field, $Method) {
switch(strtoupper($Method)){
case "POST": return isset($_POST[$Field]) ? $_POST[$Field] : false;
case "GET": return isset($_GET[$Field]) ? $_GET[$Field] : false;
default: return isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
}
}
Second problem is that isset() might be used with variables, but not with function results. Use boolean check instead:
if (ObtainRequest("OneField","POST") !== false) {
DoSomething();
} else if (ObtainRequest("OneField","POST") === false) {
DoOtherthing();
}
Is it applicable to Session too?
Well, if you interested in my opinion: I would not mix $_SESSION in such function with $_POST, $_GET and $_REQUEST, because $_SESSIONs meaning is different. Also, it exists differently, not like them.
However something like this function might be realized for $_SESSION itself.
The first problem which I can see that you are using post instead of POST...
yes you can do this with sessions too, but codes need to be modified a bit..
I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}