Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

php - Special characters in CakePHP URL

I'm developing a web application where users have profiles, and skills related to that profile. I want to develop a page where a user can see all profiles that correspond to a particular skill. For example, if I wanted to see all users with the skill of "HTML" I could use http://site.com/skills/HTML. Pretty simple.

I've got it working, however some users have skills with spaces (for example project management) and some have special characters (for example C#). When I browse to a URL like http://site.com/skills/C#, Cake automatically makes it http://site.com/skills/C because it parses out the special character (# in this case).

How can I safely allow skills in the URL that have special characters in them? This is the action I'm currently using:

public function view($name) {
    // Find skill using $name
    $skill = $this->Skill->find('first', array(
        'conditions' => array('Skill.name' => $name)
    ));

    if(!$skill) {
        // Skill doesn't exist, return 404
        // TODO: route to 404 page
        throw new NotFoundException();
    }

    $this->set('skill', $skill);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The # is a "special" character that by default jumps to a named anchor. In order to use special characters in an URL, you will need to use urlencode().

But please note that your URL's will not look "fancy", it will just be encoded to the raw HTML entity of the special character. In your case C# will become C%23. So you might want to consider using a different URL alias for your tag, like CSharp (you can just set a "background" database field to "translate" the original value to an URL-friendly one).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...