Special characters in CakePHP URL

若如初见. 提交于 2019-12-13 07:58:00

问题


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);
}

回答1:


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).



来源:https://stackoverflow.com/questions/15636986/special-characters-in-cakephp-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!