I have this URL (part of the url):
index.php?option=com_umpai&status=success
When status = success is pass to component, i want it to run success task.
So i created a router php file to get status and put in task. Not sure if this is a correct method to do it? How can i put in the task by getting status in my url?
I am wondering does router.php apply to url type in the address bar?
This is my router codes:
<?php
defined('_JEXEC') or die('Restricted access');
function UmpaiBuildRoute(&$query)
{
$segments = array();
if(isset($query['status']))
{
switch($query['status']) {
case 'success':
$segments[] = 'success';
case 'fail':
$segments[] = 'fail';
case 'cancel':
$segments[] = 'cancel';
}
$segments[] = $query['task'];
unset($query['task']);
unset($query['status']);
}
return $router->build($segments);
}
function UmpaiParseRoute($segments)
{
$vars = array();
$count = count($segments);
if(!empty($count)) {
if($segments[0] == 'success'){
$vars['task'] = 'success';
}
}
return $router->parse($vars);
}
This is the simple code version to test if my router is working, but it is not working too:
function UmpaiBuildRoute(&$query)
{
$segments = array();
$segments[] = 'success';
return $segments;
}
function UmpaiParseRoute($segments)
{
$vars = array();
$count = count($segments);
if(!empty($count)) {
if($segments[0] == 'success'){
$vars['task'] = 'success';
}
}
return $vars;
var_dump($vars);
}
I tried this as well:
function UmpaiBuildRoute(&$query)
{
$segments[] = $_GET['status'];
}
function UmpaiParseRoute($segments)
{
$vars = array();
$count = count($segments);
if(!empty($count)) {
if($segments[0] == 'success'){
$vars['task'] = 'success';
}
}
return $vars;
}
Verhaeren (in the comments for the question) is right, try this:
if(!empty($_GET['status'])) {
// if status is set:
switch($_GET['status']) {
case 'success':
$segments[] = 'success';
case 'fail':
$segments[] = 'fail';
case 'cancel':
$segments[] = 'cancel';
}
} else {
// if status is not set...
};
Note: instead of this switch, you could also use $segments[] = $_GET['status'];
$_GET is an array but $_GET['status'] is a string. $_GET is an array with all URL variables (if any).
function UmpaiParseRoute()
{
$vars = array();
if(isset($_GET['status'])) {
$vars['task'] = 'success';
}
return $vars;
}
Also notice you don't need to pass $_GET as a parameter because is a SUPERGLOBAL variable.
Related
I'm looking for a way to include or require the content of a variable, instead of a file.
Normally, one can require/include a php function file with either of these:
require_once('my1stphpfunctionfile.php')
include('my2ndphpfunctionfile.php');
Suppose I wanted to do something like this:
$contentOf1stFFile = file_get_contents('/tmp/my1stphpfunctionfile.php');
$contentOf2ndFFile = file_get_contents('/tmp/my2ndphpfunctionfile.php');
require_once($contentOf1stFFile);
require_once($contentOf2ndFFile);
Now, in the above example, I have the actual function files which I am loading into variables. In the real world scenario I'm actually dealing with, the php code in the function files are not stored in files. They're in variables. So I'm looking for a way to treat those variables as include/require treats the function files.
I'm new to php so please forgive these questions if you find them foolish. What I'm attempting to do here does not appear to be possible. What I ended up doing was using eval which I'm told is very dangerous and should be avoided:
eval("?>$contentOf1stFFile");
eval("?>$contentOf2ndFFile");
Content of $contentOf1stFFile:
# class_lookup.php
<?php
class Lookup_whois {
// Domain name which we want to lookup
var $domain;
// TLD for above domain, eg. 'com', 'net', etc...
var $tld;
// Array which contains information needed to parse the whois server response
var $tld_params;
// Sets to error code if something fails
var $error_code;
// Sets user-friendly error message if something goes wrong
var $error_message;
// For internal use mainly - raw response from the whois server
var $whois_raw_output;
function Lookup_whois($domain, $tld, $tld_params) {
$this->domain = $domain;
$this->tld = $tld;
$this->tld_params = $tld_params;
}
function check_domain_spelling() {
if (preg_match("/^([A-Za-z0-9]+(\-?[A-za-z0-9]*)){2,63}$/", $this->domain)) {
return true;
} else {
return false;
}
}
function get_whois_output() {
if (isset($this->tld_params[$this->tld]['parameter'])) {
$query = $this->tld_params[$this->tld]['parameter'].$this->domain.'.'.$this->tld;
} else {
$query = $this->domain.'.'.$this->tld;
}
$server = $this->tld_params[$this->tld]['whois'];
if (!$this->check_domain_spelling()) {
$this->error_message = 'Domain name is not correct, check spelling. Only numbers, letters and hyphens are allowed';
return false;
}
if (!$server) {
$this->error_message = 'Whois server name is empty, please check the config file';
return false;
}
$output = array();
$fp = fsockopen($server, 43, $errno, $errstr, 30);
if(!$fp) {
$this->error_code = $errno;
$this->error_message = $errstr;
fclose($fp);
return false;
} else {
sleep(2);
fputs($fp, $query . "\n");
while(!feof($fp)) {
$output[] = fgets($fp, 128);
}
fclose($fp);
$this->whois_raw_output = $output;
return true;
}
}
function parse_whois_data() {
if (!is_array($this->whois_raw_output) && Count($this->whois_raw_output) < 1) {
$this->error_message = 'No output to parse... Get data first';
return false;
}
$wait_for = 0;
$result = array();
$result['domain'] = $this->domain.'.'.$this->tld;
foreach ($this->whois_raw_output as $line) {
#if (ereg($this->tld_params[$this->tld]['wait_for'], $line)) {
if (preg_match($this->tld_params[$this->tld]['wait_for'],$line)) {
$wait_for = 1;
}
if ($wait_for == 1) {
foreach ($this->tld_params[$this->tld]['info'] as $key => $value) {
$regs = '';
if (ereg($value.'(.*)', $line, $regs)) {
if (key_exists($key, $result)) {
if (!is_array($result[$key])) {
$result[$key] = array($result[$key]);
}
$result[$key][] = trim($regs[1]);
} else {
$result[$key] = trim($regs[1]);
$i = 1;
}
}
}
}
}
return $result;
}
}
?>
Are there any other alternatives?
No there are no other alternatives.
In terms of security there is no difference if you include() a file or eval() the content. It depends on the context. As long as you only run your own code there is nothing "dangerous".
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.
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...
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 trying to parse PHP source code with the token_get_all(). So far everything worked out with that function, but now i need a way to get the return values of methods.
Identifying where a return is done isn't the problem. I just see no way of getting the piece of code that comes after the return value.
For example for this piece of code:
<?php
class Bla {
public function Test1()
{
$t = true;
if($t) {
return 1;
}
return 0;
}
public function Test2()
{
echo "bbb";
return; // nothing is returned
}
public function Test3()
{
echo "ccc";
$someval1 = 1;
$someval2 = 2;
return ($someval + $otherval)*2;
}
}
?>
I'm using get_token_all() to identify where a return is done:
$newStr = '';
$returnToken = T_RETURN;
$tokens = token_get_all($source);
foreach ($tokens as $key => $token)
{
if (is_array($token))
{
if (($token[0] == $returnToken))
{
// found return, now get what is returned?
}
else
{
$token = $token[1];
}
}
$newStr .= $token;
}
I have no clue how to get the piece of code that is actually returned. That is what i want to get.
Anyone any idea how i could do this?
Perhaps this might help. Though I curious to know what you are ultimately trying to do.
$tokens = token_get_all($str);
$returnCode = '';
$returnCodes = array();
foreach ($tokens as $token) {
// If return statement start collecting code.
if (is_array($tokens) && $token['0'] == T_RETURN) {
$returnCode .= $token[1];
continue;
}
// if we started collecting code keep collecting.
if (!empty($returnCode)) {
// if we get to a semi-colon stop collecting code
if ($token === ';') {
$returnCodes[] = substr($returnCode, 6);
$returnCode = '';
} else {
$returnCode .= isset($token[1]) ? $token[1] : $token;
}
}
}