Generate a dynamic switch structure in PHP - php

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;
}

Related

How do i get current user Fullname to display in a form validation message

I am using a Wordpress plugin called Ultimate Membership Pro which is using Ajax call to validate Username in the Registration form. However, I would like to retrieve the full name of the user when a Username that has been registered is trying to register again.
Example - I want the Validation message to say: This username has been taken by John Doe
I have tried to manipulate a filename called indeed-membership-pro.php file in the plugin directory.
//I added this code under the function
//I called a global method
global $current_user;
$uid = get_user_by('login', $value);
case 'user_login':
if (!validate_username($value)){
$return = $register_msg['ihc_register_error_username_msg'];
}
if (username_exists($value)) {
//I concatenate the error message with the input username to get the user ID. But i need the user FirstName and Lastname
$return = $register_msg['ihc_register_username_taken_msg'] . $uid->ID;
}
break;
function ihc_check_value_field($type='', $value='', $val2='', $register_msg=array()){
//I called a global method
global $current_user;
$uid = get_user_by('login', $value);
if (isset($value) && $value!=''){
switch ($type){
case 'user_login':
if (!validate_username($value)){
$return = $register_msg['ihc_register_error_username_msg'];
}
if (username_exists($value)) {
//I am able to get the user ID But i need First Name and last Name
$return = $register_msg['ihc_register_username_taken_msg']. $uid->ID;
}
break;
case 'user_email':
if (!is_email($value)) {
$return = $register_msg['ihc_register_invalid_email_msg'];
}
if (email_exists($value)){
$return = $register_msg['ihc_register_email_is_taken_msg'];
}
$blacklist = get_option('ihc_email_blacklist');
if(isset($blacklist)){
$blacklist = explode(',',preg_replace('/\s+/', '', $blacklist));
if( count($blacklist) > 0 && in_array($value,$blacklist)){
$return = $register_msg['ihc_register_email_is_taken_msg'];
}
}
break;
case 'confirm_email':
if ($value==$val2){
$return = 1;
} else {
$return = $register_msg['ihc_register_emails_not_match_msg'];
}
break;
case 'pass1':
$register_metas = ihc_return_meta_arr('register');
if ($register_metas['ihc_register_pass_options']==2){
//characters and digits
if (!preg_match('/[a-z]/', $value)){
$return = $register_msg['ihc_register_pass_letter_digits_msg'];
}
if (!preg_match('/[0-9]/', $value)){
$return = $register_msg['ihc_register_pass_letter_digits_msg'];
}
} else if ($register_metas['ihc_register_pass_options']==3){
//characters, digits and one Uppercase letter
if (!preg_match('/[a-z]/', $value)){
$return = $register_msg['ihc_register_pass_let_dig_up_let_msg'];
}
if (!preg_match('/[0-9]/', $value)){
$return = $register_msg['ihc_register_pass_let_dig_up_let_msg'];
}
if (!preg_match('/[A-Z]/', $value)){
$return = $register_msg['ihc_register_pass_let_dig_up_let_msg'];
}
}
//check the length of password
if($register_metas['ihc_register_pass_min_length']!=0){
if (strlen($value)<$register_metas['ihc_register_pass_min_length']){
$return = str_replace( '{X}', $register_metas['ihc_register_pass_min_length'], $register_msg['ihc_register_pass_min_char_msg'] );
}
}
break;
case 'pass2':
if ($value==$val2){
$return = 1;
} else {
$return = $register_msg['ihc_register_pass_not_match_msg'];
}
break;
case 'tos':
if ($value==1){
$return = 1;
} else {
$return = $register_msg['ihc_register_err_tos'];
}
break;
default:
//required conditional field
$check = ihc_required_conditional_field_test($type, $value);
if ($check){
$return = $check;
} else {
$return = 1;
}
break;
}
if (empty($return)){
$return = 1;
}
return $return;
} else {
$check = ihc_required_conditional_field_test($type, $value);//Check for required conditional field
if ($check){
return $check;
} else {
return $register_msg['ihc_register_err_req_fields'];
}
}
}
add_action("wp_ajax_nopriv_ihc_ap_reset_custom_banner", "ihc_ap_reset_custom_banner");
add_action('wp_ajax_ihc_ap_reset_custom_banner', 'ihc_ap_reset_custom_banner');
$user_object->display_name is what you are looking for.
This given, it may not be a good idea to reveal user data such as first name & last name as part of the error message.

How to retrive multiple url parameter in php

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...

Prestashop remove one checkout step

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.

PHP Switch using it with Functions

I have this switch and I do certain things based on the selection of the action with the switch. Based on my testing, function thats in the switch is not even taking place when the page runs.
I am interested in being able to running the sortby action for now. when I go to the page, switch puts me in the first case but does not run the function.Why? How do I fix it?
switch ($_GET['action']) {
case 'sortby':
sort_by($_GET['sortby']);
break;
case 'add':
resident_add($_GET['residentID']);
include('inc/modify/add.php');
break;
case 'edit':
resident_edit($_GET['residentID']);
include('inc/modify/edit.php');
break;
case 'delete':
resident_delete($_GET['residentID']);
include('inc/modify/delete.php');
break;
case 'search':
echo "";
break;
default:
resident_default($_GET['sortby']);
}
function sort_by($sortby) {
if ($sortby == "last_name") {
$sort_db_field = "Last Name";
$sort_order = "ASC";
} elseif ($sortby == "lot") {
$sort_db_field = "Lot";
$sort_order = "ASC";
} elseif ($sortby == "date_added") {
$sort_db_field = "No";
$sort_order = "DESC";
} else {
include('inc/error.php?error_code=100');
}
return $sort_db_field;
return $sort_order;
}
$data = mysqli_query($dbcon, "SELECT * FROM `residents` ORDER BY `residents`.`".$sort_db_field."` ".$sort_order."") or die(mysqli_error());
You can't have 2 return statements in a function, the second one will never be executed.
Declare two variable before your switch:
$sort_db_field = "";
$sort_order = "";
switch ($_GET['action']) {
/*snip*/
}
Then in the function drop the returns. This function will now set the values in the two variables you declared.

Send value to php file

I'm try to send a value to a PHP file, but when I check, this value became null.
I send the value by: user_login.php?p_action=New_User
The code of user_login.php is:
require("include/session_inc.php");
require("include/user_handling_inc.php");
require("include/db_inc.php");
start_Session(false, false);
switch ($p_action) {
case 'Login': {
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
break;
}
case 'Save_Profile': {
$l_flag = "Save_Profile";
break;
}
case 'New_User':
$l_flag = "New_User";
break;
case 'Create_New_User':
$l_flag = "Create_New_User";
}
switch ($l_flag) {
case 'New_User': {
include "include/user_new_inc.php";
break;
}
case 'Save_Profile': {
load_User_Data(" username = '$p_in_username' ", false);
include "include/user_profile_save_inc.php";
break;
}
case 'Wrong_Password':
echo "Wrong Pass";
break;
case 'OK':
load_User_Data(" username = '$p_in_username' ", true);
store_User_Cookie($g_userdata->user_id);
include "include/user_profile_inc.php";
break;
case 'Create_New_User':
$l_user_id = create_New_User ($p_in_username, $p_in_email, 'Y');
if ($l_user_id != -1) {
store_User_Cookie($l_user_id);
echo "Success !! <br><br> \n";
echo "<a href\"/index.php\"> Back to Main </a>";
}
break;
}
First your code isn't correct please read more about using Switch here
second to access to any variable came from url you can use Global variable $_GET or $_REQUEST
and you can read more about them from here and here
and this is your code after fixing it please try to run it
<?php
require("include/session_inc.php");
require("include/user_handling_inc.php");
require("include/db_inc.php");
start_Session(false, false);
$p_action=$_GET["p_action"];
switch ($p_action) {
case 'Login':
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
break;
case 'Save_Profile':
$l_flag = "Save_Profile";
break;
case 'New_User':
$l_flag = "New_User";
break;
case 'Create_New_User':
$l_flag = "Create_New_User";
break;
}
switch ($l_flag) {
case 'New_User':
include "include/user_new_inc.php";
break;
case 'Save_Profile':
load_User_Data(" username = '$p_in_username' ", false);
include "include/user_profile_save_inc.php";
break;
case 'Wrong_Password':
echo "Wrong Pass";
break;
case 'OK':
load_User_Data(" username = '$p_in_username' ", true);
store_User_Cookie($g_userdata->user_id);
include "include/user_profile_inc.php";
break;
case 'Create_New_User':
$l_user_id = create_New_User ($p_in_username, $p_in_email, 'Y');
if ($l_user_id != -1) {
store_User_Cookie($l_user_id);
echo "Success !! <br><br> \n";
echo "<a href\"/index.php\"> Back to Main </a>";
}
break;
}
?>
you need to make the code like this friend
switch ($_GET["p_action"]) {
case 'Login': {
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
that well give you the value of the get!!!
Use $_GET to get your parameter.
Sometimes $_REQUEST is preferable since it access both get & post data.
2nd thing never trust the user input so you must use addslashes(); or real_escape_string() function to prevent attacks on the system.
So Code would be like this :
$var = addslashes($_GET['p_action']);
switch($p) {
case 'Login':
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
break;
"OTHER CASES HERE"
}
Notice that : Don't add { } for CASE. Read syntax for switch
here.

Categories