-->

Special characters in CakePHP URL

2019-09-20 14:43发布

问题:

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