Suppose I have developed a website www.example.com,
Now I want to pass a param just after the domain name. e.g. www.example.com/param. Is that possible?
My defult route
you can pass the parameter to default route like following.
routes.php
$route['default_controller'] = 'pages';
$route['about'] = 'pages/about';
$route['(.*)'] = 'pages';
You should call $route['(.*)'] in the last line of the code, else if you type www.example.com/about About Page URL in the browser, it will redirect to default controller method.
$route['(.*)'] : it means you can pass unlimited param in the URL
use can use $this->uri->segment() or $this->uri->segment_array() to collection the paramaters in the function
example:
If your URL like this
www.example.com/param1/param2/param3/param4
public function index(){
$param1 = $this->uri->segment(1); // return `param1`
$param2 = $this->uri->segment(2); // return `param2`
$param3 = $this->uri->segment(3); // return `param3`
$param4 = $this->uri->segment(4); // return `param4`
// OR
$paramArray = $this->uri->segment_array(4); // all parameter in Array format
}
Related
In my node app I am using the router.use to do the token validation.
I want to skip validation for few urls, so I want to check if the url matches, then call next();
But the URL I want to skip has a URLparam
E.g., this is the URL /service/:appname/getall.
This has to be matched against /service/blah/getall and give a true.
How can this be achieved without splitting the url by '/'
Thanks in advance.
The parameters will match :[^/]+ because it is a : followed by anything other than a / 1 or more times.
If you find the parameters in the template and replace them with a regex that will match any string you can do what you asked for.
let template = '/service/:appname/getall'
let url = '/service/blah/getall'
// find params and replace them with regex
template = template.replace(/:[^/]+/g, '([^/]+)')
// the template is now a regex string '/service/[^/]+/getall'
// which is essentially '/service/ ANYTHING THAT'S NOT A '/' /getall'
// convert to regex and only match from start to end
template = new RegExp(`^${template}$`)
// ^ = beggin
// $ = end
// the template is now /^\/service\/([^\/]+)\/getall$/
matches = url.match(template)
// matches will be null is there is no match.
console.log(matches)
// ["/service/blah/getall", "blah"]
// it will be [full_match, param1, param2...]
Edit: use \w instead of [^/], because:
The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]). https://expressjs.com/en/guide/routing.html#route-parameters
I believe this is true for most parsers so I have updated my answer. The following test data will only work with this updated method.
let template = '/service/:app-:version/get/:amt';
let url = '/service/blah-v1.0.0/get/all';
template = template.replace(/:\w+/g, `([^/]+)` );
template = new RegExp(`^${template}$`);
let matches = url.match(template);
console.log(url);
console.log(template);
console.log(matches);
// Array(4) ["/service/blah-v1.0.0/get/all", "blah", "v1.0.0", "all"]
I have used Yii2 advanced application. i rewrite url in frontend and backend.
After rewrite Frontend url is
localhost:83/Working-copy/mySite/
And For Backend
localhost:83/Working-copy/mySite/admin
Now i want to get base url like
/Working-copy/mySite/
But i don't get it properly
I have tried following ways,
echo Yii::getAlias('#web') // ans= /Working-copy/mySite/admin
echo Yii::getAlias('#backend') // ans= /var/www/Working-copy/mySite/backend
echo Yii::getAlias('#webroot') // ans= /var/www/Working-copy/mySite/backend
echo Yii::$app->request->BaseUrl // ans= /Working-copy/mySite/admin
echo Yii::$app->getBasePath(false) // ans= /var/www/Working-copy/mySite/backend
echo Yii::$app->homeUrl // ans = /Working-copy/mySite/admin/
In some url i get /var/www/ and in some url get /admin/.
i only want my project name.
any solution please?
Create components into common folder.
Add Request.php
namespace common\components;
class Request extends \yii\web\Request {
public $web;
public $adminUrl;
public function getBaseUrl(){
return str_replace($this->web, "", parent::getBaseUrl()) . $this->adminUrl;
}
public function getActualBaseUrl(){
return str_replace($this->web, "", parent::getBaseUrl());
}
public function resolvePathInfo(){
if($this->getUrl() === $this->adminUrl){
return "";
}else{
return parent::resolvePathInfo();
}
}
}
Use Yii::$app->request->getActualBaseUrl().
Is it possible to log variable name (not value) in JavaScript?
var max_value = 4;
console.log(max_value); // should log "max_value" as a string
UPDATE: I need a testing function that should be able to log any variable name (passed as an argument) as a string, not just this one variable.
There is a solution that can help you. I grabbed this function from this stackoverflow answer, which is able to get the name of the function parameters:
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
var fnStr = func.toString().replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
if(result === null)
result = [];
return result;
}
then all you need to do now, is to use the name of your variable as a parameter of an anonymous function and pass all the function as argument of the getParamNames :
variablesNames = getParamNames(function (max_value, min_value) {});
This will return an array like this :
result => ["max_value", "min_value"];
Let's make it practical, first change the name of the getParamNames function to something easy and small like this :
function __ (func) {
// code here ...
}
second thing, instead of returning an array, just return the first element of the array, change this :
return result;
to this :
return result.shift();
now, you can get the name of your variable like this :
__(function( max_value ){});
How does $_GET Variable works with Concrete5? Can I use that on regular page?
I know I can do this with single page via url segment, I'm just wondering if it is possible with regular page.
Example is :http://www.domain_name.com/about-us/?name=test...
Get-parameters are available via the controllers. In the view of a page or block use:
$this->controller->get("parameterName");
A cleaner way for custom parameters would be to define them in the function view() of the page controller. If at http://www.domain_name.com/about-us is your page and you define the view function of it's pagetype controller like this:
function view($name) {
$this->set("name", $name);
}
... and call the URL http://www.domain_name.com/about-us/test – then "test" will be passed under $name to your page view.
Note that controllers for page types must be in controllers/page_types/ and called BlablaPageTypeController ... with "PageType" literally being in there.
You can use it in a template. For instance, you can grab a variable...
$sort_by = $_GET['sort'];
And then use that variable in a PageList lookup, similar to:
$pl = new PageList();
$ctHandle = "teaching";
// Available Filters
$pl->filterByCollectionTypeHandle($ctHandle); //Filters by page type handles.
// Sorting Options
if ($sort_by == "name") {
$pl->sortByName();
} else {
$pl->sortBy('teaching_date', 'desc'); // Order by a page attribute
}
// Get the page List Results
$pages = $pl->getPage(); //Get all pages that match filter/sort criteria.
$pages = $pl->get($itemsToGet = 100, $offset = 0);
Then you can iterate over that array to print stuff out...eg
if ($pages) {
foreach ($pages as $page){
echo ''.$page->getCollectionName() . '<br />';
}
}
Props to the C5 Cheatsheet for the PageList code.
Can I allow the domain matching for my extension to be user configurable?
I'd like to let my users choose when the extension runs.
To implement customizable "match patterns" for content scripts, the Content script need to be executed in by the background page using the chrome.tabs.executeScript method (after detecting a page load using the chrome.tabs.onUpdated event listener).
Because the match pattern check is not exposed in any API, you have to create the method yourself. It is implemented in url_pattern.cc, and the specification is available at match patterns.
Here's an example of a parser:
/**
* #param String input A match pattern
* #returns null if input is invalid
* #returns String to be passed to the RegExp constructor */
function parse_match_pattern(input) {
if (typeof input !== 'string') return null;
var match_pattern = '(?:^'
, regEscape = function(s) {return s.replace(/[[^$.|?*+(){}\\]/g, '\\$&');}
, result = /^(\*|https?|file|ftp|chrome-extension):\/\//.exec(input);
// Parse scheme
if (!result) return null;
input = input.substr(result[0].length);
match_pattern += result[1] === '*' ? 'https?://' : result[1] + '://';
// Parse host if scheme is not `file`
if (result[1] !== 'file') {
if (!(result = /^(?:\*|(\*\.)?([^\/*]+))(?=\/)/.exec(input))) return null;
input = input.substr(result[0].length);
if (result[0] === '*') { // host is '*'
match_pattern += '[^/]+';
} else {
if (result[1]) { // Subdomain wildcard exists
match_pattern += '(?:[^/]+\\.)?';
}
// Append host (escape special regex characters)
match_pattern += regEscape(result[2]);
}
}
// Add remainder (path)
match_pattern += input.split('*').map(regEscape).join('.*');
match_pattern += '$)';
return match_pattern;
}
Example: Run content script on pages which match the pattern
In the example below, the array is hard-coded. In practice, you would store the match patterns in an array using localStorage or chrome.storage.
// Example: Parse a list of match patterns:
var patterns = ['*://*/*', '*exampleofinvalid*', 'file://*'];
// Parse list and filter(exclude) invalid match patterns
var parsed = patterns.map(parse_match_pattern)
.filter(function(pattern){return pattern !== null});
// Create pattern for validation:
var pattern = new RegExp(parsed.join('|'));
// Example of filtering:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete') {
var url = tab.url.split('#')[0]; // Exclude URL fragments
if (pattern.test(url)) {
chrome.tabs.executeScript(tabId, {
file: 'contentscript.js'
// or: code: '<JavaScript code here>'
// Other valid options: allFrames, runAt
});
}
}
});
To get this to work, you need to request the following permissions in the manifest file:
"tabs" - To enable the necessary tabs API.
"<all_urls>" - To be able to use chrome.tabs.executeScript to execute a content script in a specific page.
A fixed list of permissions
If the set of match patterns is fixed (ie. the user cannot define new ones, only toggle patterns), "<all_urls>" can be replaced with this set of permissions. You may even use optional permissions to reduce the initial number of requested permissions (clearly explained in the documentation of chrome.permissions).