Mod rewrite test.php?p=one to test/one - forms

I rewrite rules like site.com/product/p1 to site.com/product.php?p=p1 successfully.
Now, I want to the the opposite, convert the query that is received from a form submission site.com/product.php?id=1234&name=test to site.com/product/test/1234 i.e. I don't want the site visitor to see the query parameters.
To make things more clear: on my site I have a form with two text input fields (and a few hidden fields as well); visitors can enter the product id and product name and submit the form. I want the resulting url (after the form submission) to be flat (site.com/product/test/1234) and not include any params.
Of course, I want my script (product.php) to retrieve all the parameters from the form. I guess I could do that in the same fashion that I turn site.com/product/p1 into site.com/product.php?p=p1.
Could anyone help me out?

mod_rewrite will not be flexible enough to do this in general. It's fine when you have one (and only one) query parameter to handle. As you add more, you need to handle every possible combination of query parameters, and have a new rule for each. mod_rewrite is only appropriate if you can no longer serve URLs in the old style, for example if you are upgrading a third-party server you cannot modify, and want to have httpd handle redirecting old bookmarked links to the new locations.
It is best to handle this inside your PHP script itself. The script at the "old" product.php?id=1234&name=test URL should read the GET parameters and return a HTTP 301 response ("Moved Permanently") to the new product/test/1234 URL. This will work if the request goes to product.php, or product.php?name=test, or product.php?id=1234, or product.php?name=test&id=1234. The script determines what to do with missing values, and how to build the replacement URL.
To do the rewrite with just a single query parameter, it will look like the reverse of your successful rewrite rule, e.g.
RewriteCond %{QUERY_STRING} ^p=(.*)$
RewriteRule /product.php /product/%1 [R]

Related

JMeter redirection URL

I'm trying to stress test a website where people are able to create reports which are stored in SQL, etc...
Let's say the page orders are the followings:
mywebsite.com/home
mywebsite.com/reports
mywebsite.com/reports/create
mywebsite.com/reports/2
As you can see, there is a sub-page called reports. It has a create button. Then the user is being redirected to the create sub-page. When it clicks the save button, it get's redirected straight to its reports sub-page. Now my issue is I don't see the redirection URL that is being received by the browser where to be redirected. Maybe the report ID will be 3 or 4, or 123.... etc. I want this value as a variable. At the create sub-page I have a Response code: 302 but I can't figure out where is it redirecting the user to and where can I modify this URL value.
When you are being redirected the server sends Location header which indicates where exactly you are being redirected
In order to extract this redirect URL you can add Regular Expression Extractor postprocessor as a child of the main request and configure it like:
Apply to: Main sample and sub-samples
Field to check: Response headers
Reference Name: anything meaningful, i.e. location
Regular Expression: Location: (.*)
Template: $1$
Assuming everything goes well you should be able to refer the extracted value as ${location} where required.
References:
Using RegEx (Regular Expression Extractor) with JMeter
JMeter: Regular Expressions

Nginx URL rewrite storing part of URI & Using it in redirect

Trying to make a nginx url rewrite for a branding only global site that
has search functionality (but no product catalog assigned as it's the global site) that will store part(or all if it's better) of the URL to pass it to a dedicated redirect script that geo redirects the user's query to the correct regional site.
Can someone tell me what is wrong with what I am doing?
rewrite ^/catalogsearch/result?q=(.*)$
/redirect-script?x=/catalogsearch/result=q=$1
permanent;
I don't think you can match the query string with the rewrite regexp.
Try this:
rewrite ^/catalogsearch/result$
/redirect-script?x=/catalogsearch/result=q=$arg_q
permanent;
$arg_q is one of the automatic variables containing the query arguments, see http://nginx.org/en/docs/http/ngx_http_core_module.html#var_arg_

How to create and implement a pixel tracking code

OK, here's a goal I've been looking for a while.
As it's known, most advertising and analytics companies use a so called "pixel" code in order to track websites views, transactions, conversion etc.
I do have a general idea on how it works, the problem is how to implement it. The tracking codes consist from few parts.
The tracking code itself.
This is the code that the users inserts on his webpage in the <head> section. The main goal of this code is to set some customer specific variables and to call the *.js file.
*.js file.
This file holds all the magic of CRUD (create/read/update/delete) cookies, track user's events and interaction with the webpage.
The pixel code.
This is an <img> tag with the src atribute pointing to an image *.gif (for example) file that takes all the parameters collected on the page, and stores them in the database.
Example:
WordPress pixel code: <img id="wpstats" src="http://stats.wordpress.com/g.gif?host=www.hostname.com&list_of_cookies_value_pairs;" alt="">
Google Analitycs:
http://www.google-analytics.com/__utm.gif?utmwv=4&utmn=769876874&etc
Now, it's obvious that the *.gif request has to reach a server side scripting language in order to read the parameters data and store them in a db.
Does anyone have an idea how to implement this in Zend?
UPDATE
Another thing I'm interested in is: How to avoid the user's browser to load the cached *.gif ? Will a random parameter value do the trick? Example: src="pixel.gif?nocache=random_number" where the nocache parameter value will be different on every request.
As Zend is built using PHP, it might be worth reading the following question and answer: Developing a tracking pixel.
In addition to this answer and as you're looking for a way of avoiding caching the tracking image, the easiest way of doing this is to append a unique/random string to it, which is generated at runtime.
For example, server-side and with the creation of each image, you might add a random URL id:
<?php
// Generate random id of min/max length
$rand_id = rand(8, 8);
// Echo the image and append a random string
echo "<img src='pixel.php?a=".$vara."&b=".$varb."&rand=".$rand_id."'>";
?>
Just adding my 2 cents to this thread because I think an important, and frequently used, option is missing: you don't necessarily need a scripting language to capture the request. A more efficient approach is to use the web server access log (like apache access log for instance) to log the request and then handle that log with whatever tools you see fit, like ELK stack for instance.
This makes serving the requests much lighter because no scripting language is loaded to prepare the response, just native apache response, which is typically much more efficient.
First of all, the *.gif doesn't need to be that file type, the only thing that is of interest is the Content-Type http header. Set that to image/gif (or any other, appropiate type) in the beginning, execute your code and render some sort of image to the response body.
Well, all of the above codes are correct and is good but to be certain, the guy above mention "g.gif"
You can just add a simple php code to write to an sql or fwrite("file.txt",$opened)
where var $opened serves as the counter++ if someone opened your mail... then save it as "g.gif"
TO DO all of this just add these:
<Files "/thisdirectory">
AddType application/x-httpd-php .gif
</Files>
to your ".htaccess" file but be sure to make a new directory for that g.gif or whatever.gif where the directory only contains g.gif and .htaccess

How to find the #fragment in a URL in Lift

I'm pretty new to Lift, and one of the things I've been trying to find is how to, in the context of a snippet, find the '#' in the current page's URL. So if a user visits http://www.example.com/some/path/page#stuff then I would like to extract "stuff" from that. I've been googling and searching the API docs and have yet to find anything for this.
I don't think the part behind the # ever gets sent to the server in the first place.
That's what wikipedia has to say about it:
In URIs a hashmark # introduces the
optional fragment near the end of the
URL. The generic RFC 3986 syntax for
URIs also allows an optional query
part introduced by a question mark ?.
In URIs with a query and a fragment
the fragment follows the query. Query
parts depend on the URI scheme and are
evaluated by the server — e.g., http:
supports queries unlike ftp:.
Fragments depend on the document MIME
type and are evaluated by the client
(Web-browser). Clients are not
supposed to send URI-fragments to
servers when they retrieve a document,
and without help from a local
application (see below) fragments do
not participate in HTTP redirections.
I don't think the part behind the #
ever gets sent to the server in the
first place.
You are correct, sir. That is the entire point of the hash.
Dylan, you could do something from the Javascript side:
$.ajax( { data : { fragment : window.location.hash ...

Use GET or POST for a search form

I have a couple search forms, 1 with ~50 fields and the other with ~100. Typically, as the HTML spec says, I do searches using the GET method as no data is changed. I haven't run into this problem yet, but I'm wondering if I will run out of URL space soon?
The limit of Internet Explorer is 2083 characters. Other browsers, have a much higher limit. I'm running Apache, so the limit there is around 4000 characters, which IIS is 16384 characters.
At 100 fields, say average field name length of 10 characters, that's already 5000 characters...amazing on the 100 field form, I haven't had any errors yet. (25% of the fields are multiple selects, so the field length is much longer.)
So, I'm wondering what my options are. (Shortening the forms is not an option.) Here my ideas:
Use POST. I don't like this as much because at the moment users can bookmark their searches and perform them again later--a really dang nice feature.
Have JavaScript loop through the form to determine which fields are different than default, populate another form and submit that one. The user would of course bookmark the shortened version.
Any other ideas?
Also, does anyone know if the length is the encoded length or just plain text?
I'm developing in PHP, but it probably doesn't make a difference.
Edit: I am unable to remove any fields; I am unable to shorten the form. This is what the client has asked for and they often do use a range of fields, in the different categories. I know that it's hard to think of a form that looks nice with this many fields, but the users don't have a problem understanding how it works.
Are your users actually going to be using all 50-100 fields to do their searches? If they're only using a few, why not POST the search to an "in between" page which header()-redirects them to the results page with only the user-changed fields in the URL? The results page would then use the default values for the fields that don't exist in the URL.
To indirectly address your question, if I was faced with a 100-field form to fill in on one page, I'd most likely close my browser, it sounds like a complete usability nightmare.
My answer is, if there's a danger that I'm getting anywhere near that limit for normal usage of the form, I'm probably Doing It Wrong.
In order of preference, I would
Split the form up and use some server-side state retention
Switch to POST, and then generate and redirect to a shorter URL on POST that resolved to the same result
Give up ;)
You mention in a comment that many of the fields "are hidden and can be opened as required".
If you are willing to discard graceful degradation, you could always actually add and remove the fields from the form, rather than just hiding and showing them: the browser won't submit the ones that aren't included in the form.
This is a variant of the "Make and model" forms that online insurance etc. pages use -- select the make, submit back to the server and get the list of models for that manufacturer.
If you don't mind using javascript then you could have it work out the length of the query string and if it is too long then switch to a post. Then have some sort of url mapper to allow them to bookmark these posted searches.
Use post and if the user bookmarks the search, save it in a database and give it a unique token, then redirect to the search page using GET and passing the token as parameter.
TinyURL is a nice example: You give it a very long URL, it saves it to a DB, gives you a unique identifier for that URL and later you can request the long URL using that identifier.
In PHP it would be something along the lines of:
<?php
if (isset($_GET['token']))
{
$token = addslashes($_GET['token']);
$qry = mysql_query("SELECT fields FROM searches WHERE token = '{$token}'");
if ($row = mysql_fetch_assoc($qry))
{
performSearch(unserialize($row['fields']));
exit;
}
showError('Your saved search has been removed because it hasn\'t been used in a while');
exit;
}
$fields = addslashes(serialize($_POST));
$token = sha1($_SERVER['REMOTE_ADDR'].rand());
mysql_query("INSERT INTO searches (token, fields, save_time) Values ('{$token}', '{$fields}', NOW())");
header('Location: ?token='.$token);
exit;
?>
And run a script daily:
<?php
mysql_query('DELETE FROM searches WHERE save_time < DATE_ADD(NOW(), INTERVAL -200 DAY)');
?>
Also, does anyone know if the length
is the encoded length or just plain text?
My guess was for encoded length. I made a simple test: a textarea and a submit button to a simplistic PHP script.
Loaded the page in IE6, pasted some French text in the textarea, 2000 characters. If I hit the submit button, nothing. I had to reduce the length of the text to be able to submit.
In other words, the 2083 character limit is exactly the maximal length of the URL found in the address bar after submitting the GET request.
I would go for the JavaScript solution: on submit, analyze the form, create a secondary form with hidden attributes, and submit that.
Some strategies on shortening the output:
As you point out, you can already skip all values left to default (no field, no value).
If you have a form like the one at Processing forum search you can group all checkbox states in one variable only, eg. using letter encoding.
Use short value attributes (in select for example).
Note: if the search page is actually composed of several independent forms, where users fill only one section or another, you can make several separate forms.
Might not apply to your case and might seems obvious but worth mentioning for the record... ^_^
One could philosophically look at the search submission POST as the creation of a saved search (especially when a search is as complex an object as the one your users are making). In this case, you could accept the post for the creation of a search and then redirect using a GET to fetch the appropriate search results (post/redirect/get).
This would also allow the users to bookmark the search results (GET) to coming back at any time to re-run the search.
Get can have one advantage if your search results can be shared, in case of post request if you send the link to someone, that person won't see any search results