I have a web page with basicly the following URL structure:
www.example.com/main.php?userId=mattias.wolff
www.example.com/definitions.php?userId=mattias.wolff
www.example.com/tasks.php?userId=mattias.wolff
www.example.com/profile.php?userId=mattias.wolff
What I would like to do is to change this to get rid of the parameters:
www.example.com/mattias.wolff
www.example.com/mattias.wolff/definitions
www.example.com/mattias.wolff/tasks
www.example.com/mattias.wolff/profile
Server side this is not a problem since I can just use mod rewrite to rewrite the URLs to the "old" format (including paramters etc.)
My question is how this should be handled client side? The pages content is very much generated by JavaScript and I therefore need to get the parameters in the same way as before.
Is there some best practice that I have missed here? Writing a function on that parse the new URL in Javascript or send the "old" URL from server side in some kind of parameter?
Do not forget that essentially, the URL is a (kind of a) query, too. The main difference here is whether you are using named parameters or positional parameters.
The ? notation is essentially a standard to allow browser to construct an URL from a form query automatically.
You could as well be using URLs of the scheme:
www.example.com/name=mattias.wolff/page=definitions
if that is what you want.
My recommendation for you is to really define a URL scheme for your pages that completely suits your needs and has enough room for future extension. Ideally, you should be able to switch back to the old scheme at some point if necessary, without major name conflicts.
There is clearly nothing wrong with organizing your URLs in the scheme of /[username]/[page], and using this scheme from JavaScript (both for parsing and generating links!) as long as you don't change it all the time.
With the following simple(?) function you can transform a URL in the way you indicate:
function transform (href) {
var m = href.match (/((?:[^\/]+\/\/)?[^\/]+\/)(.*)\.php\?userId=(.*)/);
return m ? m[1] + m[3] + '/' + m[2] : href;
}
Basically the function extracts the components of the URL into an array using a regexp match then reassembles the URL in the way you want. If the match fails the original URL is returned.
Tested on Chrome with :
var test = ["www.example.com/main.php?userId=mattias.wolff",
"www.example.com/definitions.php?userId=mattias.wolff",
"http://www.example.com/tasks.php?userId=mattias.wolff",
"www.example.com/profile.php?userId=mattias.wolff"];
for (var i = test.length; i--;)
console.log ('"' + test[i] + '" --> "' + transform (test[i]) + '"');
Output :
"www.example.com/profile.php?userId=mattias.wolff" --> "www.example.com/mattias.wolff/profile"
"http://www.example.com/tasks.php?userId=mattias.wolff" --> "http://www.example.com/mattias.wolff/tasks"
"www.example.com/definitions.php?userId=mattias.wolff" --> "www.example.com/mattias.wolff/definitions"
"www.example.com/main.php?userId=mattias.wolff" --> "www.example.com/mattias.wolff/main"
Related
I am looking for the method that allows to modify a value/text on my home page with the used link.
For example, if the URL is mywebsite.com/index.php?name=Mike
somewhere on my website, it will say
"Welcome Mike"
If the URL is mywebsite.com/index.php?name=Mark, it will automatically change to
"Welcome Mark"
without changing anything in my code.
Is it possible with HTML only or do I need PHP?
This is possible with HTML, but you need JavaScript. Here's an example:
// Find the query
let query = window.location.search;
// Extract the name
let match = query.match(/name=([^&]+)/);
// If the name exist, put it in the body
if (match) document.body.innerHTML = match[1];
Note that this won't work here, but it will work in the website.
As #JNa0 said, PHP is better suited to this task. The PHP would look like echo $_GET["name"];
You may do it with JavaScript by reading location.search and parse it then modify the DOM (see #AlexH’s answer), but that would be overkilled for such a task. Prefer PHP (or any server-side system) when possible.
I'm puttings filters in links with GET variables like this: http://example.com/list?size=3&color=7 and I'd like to remove any given filter parameter from URL whenever a different value for that particular filter is selected so that it doesn't, for example, repeat the color filter like so:
http://example.com/list?size=3&color=7&color=1
How can I if(isset($_GET['color'])) { removeGet('color'); } ?
You can use parse_url and parse_str to extract parameters like in example below:
$href = 'http://example.com/list?size=3&color=7';
$query = parse_url( $href, PHP_URL_QUERY );
parse_str( $query, $params );
// set custom paramerets
$params['color'] = 1;
// build query string
$query = http_build_query( $params );
// build url
echo explode( '?', $href )[0] . '?' . $query;
In this example explode() is used to extract the part of the url before the query string, and http_build_query to generate query string, you can also use PECL http_build_url() function, if you cannot use PECL use alternative like in this question.
You can't remove variables from GET request, just redirect to address without this var.
if (isset($_GET['color'])) {
header ('Location: http://www.example.com/list?size=' . $_GET['size']);
exit;
}
Note: in URL http://example.com/list?size=3&color=7&color=1 is just one $_GET['color'], not two. Only one of them is taken. You can check, is $_GET['key'] exists, but you don't know how many of them you have in your URL
So, assuming I'm understanding your question correctly.
Your situation is as follows:
- You are building URLs which you put into a webpage as a link ( <a href= )
- You are using the GET syntax/markup (URL?key=value&anotherkey=anothervalue) as a way to assign filters of some sort which the user then receives when they click on a given link
What you want is to be able to modify one of the items in your GET parameter list (http://example.com/list?size=3&color=7&color=1) so you have only one filter key but you can modify the filter value. So instead of the above you would start with: (http://example.com/list?size=3&color=7) but after changing the color 'filter' you would instead have http://example.com/list?size=3&color=1).
Additionally you want to do the above in PHP, (as opposed to JavaScript etc...).
There are a lot of ways to implement the change and the most effective way to do it depends on what you are already doing, most likely.
First, if you are dynamically producing the HTML markup which includes the links with the filter text, (which is what it sounds like), then it makes the most sense to create a PHP array to hold your GET parameters, then write a function that would turn those parameters into the GET string.
New filters would appear when a user refreshed the page, (because, if you are dynamically producing the HTML then a server request is required to rebuild the page).
IF, however, you want to update the link URLs on a live page WITHOUT a reload look into doing it with JavaScript, it will make your life easier.
NOTE: It is likely possible to modify the page, assuming the links are hard coded, & the page is hard coded markup, by opening the page as a file in PHP & making the appropriate change. It's my opinion that this would be a headache and not worth the time & effort AND it would still require a page reload (which you could NOT trigger yourself).
Summary
If you are writing dynamic pages with PHP it shouldn't be a big deal, just create a structure (class or array) and a method/function to write that structure out as a GET string. The structure could then be modified according to your desire before generating the page.
If, however, you are dealing with a static page, I recommend JavaScript (either creating js structures to allow a user to dynamically select filters or utilizing AJAX to build new GET parameter lists with PHP and send that back to the javascript).
(NOTE: I am reminded that I have done something along the lines of modifying links on-the-fly for existing pages by intercepting them before they are displayed to the user [using PHP] but my hands were tied in other areas and I would not recommend it if you have a choice AND it should be noted that this still required a reload...)
Try doing something like this in your back-end script:
$originalValues=array();
foreach($_GET as $filter=>$value)
{
if(empty($originalValues[$filter]))
$originalValues[$filter] = $value;
}
This may do what you want, but it feels hackish. You may want to revise your logic.
Good luck!
just put a link/button send the user to index... like this.
<a class="btn btn-primary m-1" href="http:yoururl/index.php" role="button">Limpar</a>
I'm new with the angularjs and I want your help. I'm trying to include the $routeProvider into my project in order to use templating system.
$routeProvider.when('/admin.php?page=all_transactions', {
templateUrl : 'pages/home.html',
controller : 'TransactionsController'
});
I saw that most of the examples i found the url of .when had the following format /route1/:param for urls like #/route1/12345
Because I'm using the angular in wordpress admin page I want the .when to work with $_GET parameters like the one I gave with the example code.
The depth of parameters I want it to be up to 3 and ignore any other parameters.
Does anyone know how I can do it?
is it enough for u to know, that the params are there? Or do u need explicit values. If the params are enough u could follow this example: URL Routing with Query Parameters
url: "/contacts?myParam"
// will match to url of "/contacts?myParam=value"
If you need to have more than one, separate them with an '&':
url: "/contacts?myParam1&myParam2"
// will match to url of "/contacts?myParam1=value1&myParam2=wowcool"
Hope this helps.
Edit: For accessing the values u can do the following: Accessing query parameter values
Also can get other arbitrary params in the query string form /view/1/2?other=12 with $routeParams.other – DavidC Aug 17 '14 at 21:04
OR:
While routing is indeed a good solution for application-level URL parsing, you may want to use the more low-level $location service, as injected in your own service or controller:
var paramValue = $location.search().myParam;
This simple syntax will work for http://example.com/path?myParam=someValue. However, only if you configured the $locationProvider in the html5 mode before:
$locationProvider.html5Mode(true);
Otherwise have a look at the http://example.com/#!/path?myParam=someValue "Hashbang" syntax which is a bit more complicated, but have the benefit of working on old browsers (non-html5 compatible) as well.
Setup:
Script that generates word images from multiple letter images
(autotext.php)
URL is formatted:
www.whatever.com/autotext.php?text=hello%20world
Script that alters images server-side to run filters or generate
smaller sizes (thumbnail.php)
URL is formatted:
www.whatever.com/thumbnail.php?src=whatever.png&h=XXX&w=XXX
Use-case:
I want to generate a smaller version of the autotext server-side. So my call would look something like:
www.whatever.com/thumbnail.php?src=autotext.php?text=hello%20world&h=XXX&w=XXX
As you can see, I would like to treat a URL with _GET variables as a variable itself. No amount of playing with URI encoding has helped make this work.
I have access to the PHP for both scripts, and can make some simple alterations if that's the only solution. Any help or advice would be appreciated. I would not even rule out a Javascript frontend solution, though my preference is to utilize the two scripts I already have implemented.
You should be able to do this by urlencoding all the $_GET params into a variable then assigning that variable to another, like this (untested):
// Url generation
$url = www.whatever.com/thumbnail.php?src=(urlencode(http_build_query($_GET)));
Then you should be able to retrieve on other side:
$src = urldecode(explode('&', $_GET['src']));
I've seen this exact behavior when trapping where to redirect a user, after an action occurs.
---- Update ----
Your "use case" url was correct:
www.whatever.com/thumbnail.php?src=autotext.php?text=hello%20world&h=XXX&w=XXX
.... except that you CANNOT have more than one ? within a "valid" url. So if you convert the 2nd ? to a &, you should then be able to access $_GET['text'] from the autotext.php script, then you can urldecode it to get the contents.
I have a project where I need to write text from a database into an HTML5 canvas / Javascript application.
To select this content, I've specified an attribute "reference" where I can ask the database with the content id, for example: index.php?reference=exercise1.
I have used AJAX because I need to get the text content into a Javascript variable in order to write data on canvas.
My solution is working but I need to get the reference attribute value from Javascript document.URL and not PHP $_GET.
Here is the code:
var url = decodeURIComponent(document.URL);
var attr = "reference";
var attrPos = url.lastIndexOf(attr);
var referencePos = attrPos + attr.length + 1;
var reference = url.substr(referencePos,url.length);
What I'm doing seems not to be the clean way to me.
First, ?reference= should be used with PHP $_GET and not be hacked through Javascript.
Then, I have to use lastIndexOf() instead of the search() method in order to get the good value if my application is located in a folder named "reference".
Still, if I have my project in a folder named "reference" with a URI like localhost/reference/projectfolder/index.php and a reference named "projectfolder" in the database, it will load the content even if I have not asked for index.php?reference=projectfolder
From your experience, what is the best solution in my case: be able to get PHP/MySQL data to use with Javascript. Ajax seems to be the best way but as you can see it's not clean, at least my solution.
Thanks for your help.
Still, if I have my project in a folder named "reference" with a URI
like localhost/reference/projectfolder/index.php and a reference named
"projectfolder" in the database, it will load the content even if I
have not asked for index.php?reference=projectfolder
if you want the document to be empty when you are requesting just index.php, check if $_GET["reference"] is set and then return an empty body.
From your experience, what is the best solution in my case: be able to
get PHP/MySQL data to use with Javascript. Ajax seems to be the best
way but as you can see it's not clean, at least my solution.
Check this gist on how to return JSON in your body https://gist.github.com/2627924