I have 4 parameter in my URL. I retrieve the url parameter from my url that is given. With every parameter I'm changing the path to a directory and get different images.
My sample url look like this:
www.sample.com?cat=section1&language=de&prices=pl
The code is working but it's a spagheti code.
Is there a solution to make is less DRY ? How do I retrieve multiple url parameter ?
if(isset($_GET["cat"])) {
switch ($cat) {
case 'section1':
if(isset($_GET["language"])) {
$language = htmlspecialchars($_GET["language"]);
if($language == "de") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/dp/low/*.jpg');
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
elseif ($language == "en") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/ep/low/*.jpg');
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
elseif ($language == "cz") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/cp/low/*.jpg');
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
break;
case 'section2':
//the same like in section 1, path is .../section2/...
break;
case section3:
//the same like in section 1, path is .../section3/...
break;
default:
//the same like in section 1
break;
}
else {
//the same like in section 1
}
The path d=german, e=english, c=czech, p=prices, n=noprices
You could shorten/remove many if else statements with just doing the checks:
$lang_code = $language[0];
There you have your first letter, you can do the same with every GET parameter.
So you can use that as in:
$files=glob('pages/section1/'.$lang_code.'p/low/*.jpg');
You can do the same for everything else.
P.s.: don't forget to sanitze any user input i.e.:
$language=mysqli_real_escape_string($conn, $_GET['language']);
I'd probably do something like this:
<?php
$allowedCat = ['section1', 'section2'];
$allowedLanguage = ['pl', 'en', 'cz'];
$allowedPrice = ['pl', '??'];
$cat = (isset($_GET["cat"])) ? $_GET["cat"] : null;
$language = (isset($_GET["language"])) ? $_GET["language"] : null;
$prices = (isset($_GET["prices"])) ? $_GET["prices"] : null;
if (!in_array($cat, $allowedCat)) throw new \Exception('Invalid `cat`');
if (!in_array($language, $allowedLanguage)) throw new \Exception('Invalid `language` option.');
if (!in_array($prices, $allowedPrice)) throw new \Exception('Invalid `price` option.');
$someVar1 = ($prices === 'pl') ? 'p' : 'n';
$someVar2 = $language[0];
$files = glob("pages/{$cat}/{$someVar1}{$someVar2}/low/*.jpg");
Think that should be self explanatory. Translates one to one really. Was not certain on how the other price option was specified...
Related
I want to check if the user is using the default settings. In the example below, I'm trying to check if all "foreached" items return true. If a single foreached item doesn't return true, return false on the whole function.
private function is_using_default_settings() {
// returns a huge array with settings
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] == $option[$preset[0]] && !is_null($preset[1])) {
return true;
}
}
return false;
}
I've been brainstorming for the past few days to get this sorted on my own, but sadly cannot get it to work. What is the best approach to this?
you can check when is false and block the full foreach then return value, if all is true return value true
try this:
private function is_using_default_settings() {
$returnValue = true;
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] != $option[$preset[0]] || is_null($preset[1])) {
$returnValue = false;
break;
}
}
return $returnValue;
}
You should return false when any check fails in the foreach, otherwise return true.
function check()
{
foreach($arr as $v)
{
//check fails
if(fail of the check)
return false;
}
return true;
}
Is there a way you can create a dynamic generated switch statement? I will explain further, I have a table with all the possible coins. Every person has a table with their own coins. If you click on a coin a new action will happen in the php and you will be direct for example to index.php?actie=Ripple.
My code:
case "Ripple":
if ($_SESSION["name"] == "d"){
$dataFromTransactions = $pol->toonAllesD("XRP/BTC");
}
else{
$dataFromTransactions = $pol->toonAlles("XRP/BTC");
}
Uitvoer::toonDeRippleTable($dataFromTransactions,"Ripple");
break;
case "LiteCoin":
if ($_SESSION["name"] == "d"){
$dataFromTransactions = $pol->toonAllesD("LTC/BTC");
}
else{
$dataFromTransactions = $pol->toonAlles("LTC/BTC");
}
Uitvoer::toonDeRippleTable($dataFromTransactions,"LiteCoin");
break;
Is there a way that I need to do like a:
$alleCoins = $pol->getAlleCoinsYouBuyed()
foreach($alleCoins as $coinInfo){
case $coinInfo->Coinname :
if ($_SESSION["name"] == "d"){
$dataFromTransactions = $pol->toonAllesD($coinInfo->Market);
}
else{
$dataFromTransactions = $pol->toonAlles($coinInfo->Market);
}
Uitvoer::toonDeRippleTable($dataFromTransactions,$coinInfo->Coinname);
break;
}
this code must be in the index.php
This is the solution
if ($_SESSION["name"] == "d"){
$alleCoins = dataBaseTrade::getPoloniexInstantie()->getAlleCoinsYouBuyedD();
}
else {
$alleCoins = dataBaseTrade::getPoloniexInstantie()->getAlleCoinsYouBuyed();
}
$searchNameArray = json_decode(json_encode($alleCoins), true);
$searchNameArray = array_column($searchNameArray, "Coinname" );
switch ($actie){
case ($actie != "home" || "user"):
$valueOfThePlaceInTheArray = array_search($actie,$searchNameArray);
$thisCoin = $alleCoins[$valueOfThePlaceInTheArray];
if ($_SESSION["name"] == "d"){
$dataFromTransactions = $pol->toonAllesD($thisCoin->Market);
}
else{
$dataFromTransactions = $pol->toonAlles($thisCoin->Market);
}
Uitvoer::toonDeRippleTable($dataFromTransactions,$thisCoin->Coinname);
break;
}
I'm new to prestashop and I'm having major trouble removing the address(I want to have only Summary=Shrnutí, Login/Guest Checkout=Přihlásit se, Delivery=Doručení and Payment=Platba here https://www.enakupak.cz/objednavka?step=1) step,. I am using prestashop 1.6.1.5
I know I have to modify order-carrier.tpl file and have followed several posts here and there but couldn't get it done right.
Does any of you have any actual idea on how to do this ?
I think that it will be change in this part of OrderController.php but dont know how to concretly change it
switch ((int)$this->step) {
case OrderController::STEP_SUMMARY_EMPTY_CART:
$this->context->smarty->assign('empty', 1);
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
case OrderController::STEP_DELIVERY:
if (Tools::isSubmit('processAddress')) {
$this->processAddress();
}
$this->autoStep();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'order-carrier.tpl');
break;
case OrderController::STEP_PAYMENT:
// Check that the conditions (so active) were accepted by the customer
$cgv = Tools::getValue('cgv') || $this->context->cookie->check_cgv;
if ($is_advanced_payment_api === false && Configuration::get('PS_CONDITIONS')
&& (!Validate::isBool($cgv) || $cgv == false)) {
Tools::redirect('index.php?controller=order&step=2');
}
if ($is_advanced_payment_api === false) {
Context::getContext()->cookie->check_cgv = true;
}
// Check the delivery option is set
if ($this->context->cart->isVirtualCart() === false) {
if (!Tools::getValue('delivery_option') && !Tools::getValue('id_carrier') && !$this->context->cart->delivery_option && !$this->context->cart->id_carrier) {
Tools::redirect('index.php?controller=order&step=2');
} elseif (!Tools::getValue('id_carrier') && !$this->context->cart->id_carrier) {
$deliveries_options = Tools::getValue('delivery_option');
if (!$deliveries_options) {
$deliveries_options = $this->context->cart->delivery_option;
}
foreach ($deliveries_options as $delivery_option) {
if (empty($delivery_option)) {
Tools::redirect('index.php?controller=order&step=2');
}
}
}
}
$this->autoStep();
// Bypass payment step if total is 0
if (($id_order = $this->_checkFreeOrder()) && $id_order) {
if ($this->context->customer->is_guest) {
$order = new Order((int)$id_order);
$email = $this->context->customer->email;
$this->context->customer->mylogout(); // If guest we clear the cookie for security reason
Tools::redirect('index.php?controller=guest-tracking&id_order='.urlencode($order->reference).'&email='.urlencode($email));
} else {
Tools::redirect('index.php?controller=history');
}
}
$this->_assignPayment();
if ($is_advanced_payment_api === true) {
$this->_assignAddress();
}
// assign some informations to display cart
$this->_assignSummaryInformations();
$this->setTemplate(_PS_THEME_DIR_.'order-payment.tpl');
break;
default:
$this->_assignSummaryInformations();
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
}
What if you cann this code after first case - break:
case OrderController::STEP_SUMMARY_EMPTY_CART:
$this->context->smarty->assign('empty', 1);
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
After this case add this case:
case OrderController::STEP_ADDRESSES:
$this->_assignAddress();
$this->processAddressFormat();
if (Tools::getValue('multi-shipping') == 1) {
$this->_assignSummaryInformations();
$this->context->smarty->assign('product_list', $this->context->cart->getProducts());
$this->setTemplate(_PS_THEME_DIR_.'order-address-multishipping.tpl');
} else {
$this->autoStep();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'order-carrier.tpl');
}
break;
Check, is it work.
I have a method that can return 3 different cases
public function check_verification_status($user_id) {
global $db;
$sql = "SELECT * FROM `users`
WHERE `id` = ".clean($user_id)."
AND `type_id` = 1";
$result = #mysql_query($sql,$db); check_sql(mysql_error(), $sql, 0);
$list = mysql_fetch_array($result);
if ($list['verification_key'] == '' && !$list['verified']) {
//No key or verified
return 0;
} elseif ($list['verification_key'] != '' && !$list['verified']) {
//key exists but not verified = email sent
return 2;
} elseif ($list['verification_key'] != '' && $list['verified']) {
//verified
return 1;
}
}
A form / message is output depending on the return value from this
I would have used bool for return values when comparing 2 cases, what is the proper way of handling more than 2 cases and what would the ideal return value be.
The way i call this:
$v_status = $ver->check_verification_status($user_id);
if ($v_status === 0) {
//do something
} elseif ($v_status === 1) {
//do something else
} elseif ($v_status === 2) {
//do something totally different
}
I want to learn the right way of handling such cases as I run into them often.
note: I know I need to upgrage to mysqli or PDO, its coming soon
What you have is fine, but you can also use a switch statement:
$v_status = $ver->check_verification_status($user_id);
switch ($v_status) {
case 0: {
//do something
break;
}
case 1: {
//do something else
break;
}
case 2: {
//do something totally different
break;
}
}
I have joomla 2.5 site, and I have
http://www.something.com/places?x=target
I would like to have URL like this:
http://www.something.com/places/target
How can I do this?
EDIT:
on .htaccess following works:
RewriteRule ^places/(.*)$ http://www.something.com/places?x=$1 [L,P,nc]
However it does not work with spaces ('/places/tar get' will only go to '/places?x=tar'). How can I fix that?
EDIT 2:
RewriteRule ^places/([^\ ])\ (.)$ http://www.something.com/places?x=$1\%20$2 [L,P,nc]
RewriteRule ^places/(.*)$ http://www.something.com/places?x=$1 [L,P,nc]
doest the trick. Thank you all!
If the places page belongs to a custom component (not a Joomla! built-in component), you will need to write or adjust the router.php file, in the component's directory.
It will need to contain something like:
function yourcomponentnameBuildRoute(&$query) {
$segments = array();
if (isset($query["x"])) {
$segments[] = $query["x"];
unset($query["x"]);
}
return $segments;
}
function yourcomponentnameParseRoute($segments) {
$vars = array();
$count = count($segments);
switch($segments[0]) {
case "target":
$vars["x"] = "target";
break;
}
return $vars;
}
UPDATE for your specific case:
Unfortunately there is no way to do this without a core hack.
So backup your *components/com_content/router.php* file, and then edit it as follows:
Replace the following code (around line 132):
if ($view == 'article') {
if ($advanced) {
list($tmp, $id) = explode(':', $query['id'], 2);
}
else {
$id = $query['id'];
}
$segments[] = $id;
}
unset($query['id']);
unset($query['catid']);
with this:
if ($view == 'article') {
if ($advanced) {
list($tmp, $id) = explode(':', $query['id'], 2);
}
else {
$id = $query['id'];
}
if(isset($query['x']) && $query['x']) {
$segments[] = $query['x'];
}
$segments[] = $id;
}
unset($query['x']);
unset($query['id']);
unset($query['catid']);
and this code (around line 212):
if (!isset($item)) {
$vars['view'] = $segments[0];
$vars['id'] = $segments[$count - 1];
return $vars;
}
// if there is only one segment, then it points to either an article or a category
// we test it first to see if it is a category. If the id and alias match a category
// then we assume it is a category. If they don't we assume it is an article
if ($count == 1) {
// we check to see if an alias is given. If not, we assume it is an article
if (strpos($segments[0], ':') === false) {
$vars['view'] = 'article';
$vars['id'] = (int)$segments[0];
return $vars;
}
with this:
if (!isset($item)) {
$vars['view'] = $segments[0];
$vars['id'] = $segments[$count - 1];
$vars['x'] = $count >= 2 ? $segments[$count - 2] : NULL;
return $vars;
}
// if there is only one segment, then it points to either an article or a category
// we test it first to see if it is a category. If the id and alias match a category
// then we assume it is a category. If they don't we assume it is an article
if ($count == 1 || ($count == 2 && (int) $segments[0] === 0)) {
// we check to see if an alias is given. If not, we assume it is an article
if (strpos($segments[0], ':') === false) {
$vars['view'] = 'article';
$vars['x'] = $count == 2 ? $segments[$count - 2] : NULL;
$vars['id'] = (int)$segments[$count - 1];
return $vars;
}
Then in your article's PHP code, you would use:
$target = JRequest::getVar("x");
I haven't tested it, so I'm not sure if it works. Let me know.