How to check validaty of variables names dynamically generated by URI
I am building router for my custom MVC project.
In my router, for pr开发者_运维技巧etty URL names, I ran into problem. What is the best practice for dealing with dynamically generated variables names via URI?
Example:
http://knjiskicrv.comoj.com/book/id/2/
Will generate:
$page = 'book';
$id = '2';
Now, problem may arise when someone deliberately start messing up with URI. Like:
http://knjiskicrv.comoj.com/book/id+one/2/
I will get:
$page = 'book';
$id one = '2';
Hope someone could give me some advice how to prevent and solve this? Thanks.
I think you're asking about mitigating "Cross Site Scripting" (XSS) vulnerabilities.
That's a big topic. And remember: there are LOTS of ways for a (potentially malicious) user to "deliberately start messing ... with the URI".
Suggestion: start reading :)
Here are some links:
http://seancoates.com/blogs/xss-woes
http://www.cgisecurity.com/xss-faq.html
http://www.uri.edu/webservices/phpGuideline.html
First of all, input sanitize that url. Do not create dynamic variables from a spoofable input source. Well, you have to know, what to expect on the given page. What variables and what type of variables these hold.
What if you have to display a set of categories and one of the categories' name is 'id'
/products/monkeys/white/id/ - you are properly ...d
Choose a different convention for processing your URI.
Like divide the URI into area, section and page elements.
http://www.oink.com/products/pigs/spottyones/angry/the_big_spotty_pig.html
area = 'products'
section = array('spottyones','angry')
page = the_big_spotty_pig (this uniquely identifies the article, product etc.)
When I have to use variables, these are mostly about ordering, page nr, etc. So these can be appended as query string parameters.
UPDATE Sanitization:
You have to set the rules for yourself. Let's say the URI can only contain certain characters.
//Sanitization
$uri = $_SERVER['REQUEST_URI']; // /products/monkey/angry/page.html
//allow only characters, numbers, underline and dash
if (!preg_match('~^[a-z0-9-_]$~isD',$uri))
$uri = '/'; //URI has been tampered with
$uriparts = explode('/',$uri);
/* array('products','monkey','angry','page.html') */
//Do whatever you want with the uri parts ...
You could store those variables in an array, so you get
$var['id one'] = '2';
Just my suggestion.
精彩评论