Fix for slashes hosing Symfony URLs

I found this information in this forum topic, “Slash in parameter” which references this ticket, but had snags and wanted to write it all up cleanly here.

The Problem

Sometimes a parameter in a GET string contains slashes, which are interpreted as file path delimeters by Apache and/or parameter name/value separators by Symfony.

So this URL works: http://myapp/employee/bytitle/title/System+Engineer

But this one returns a 404 (Page Not Found) error: http://myapp/employee/bytitle/title/Programmer/analyst

Wrong solution

Double-escaping the slash into ‘%252F’ (e.g. urlencode(str_replace('/', "%2f", $this->getTitle()))) works if the URL isn’t rewritten by Apache.

This threw me because my URLs would work if they included the name of the controller file, frontend_dev.php or backend.php or even index.php like http://myapp/index.php/employee/bytitle/title/Programmer%252Fanalyst,

but they wouldn’t work through the implicit, controllerless URLs like http://myapp/employee/bytitle/title/Programmer%252Fanalyst

Right solution

Both

  1. Turn on the AllowEncodedSlashes Apache directive by adding this line to your server-wide section or the appropriate VirtualHost:
     AllowEncodedSlashes On
    AND,
  2. DON’T double-escape the parameter as above, but do use urlencode() or equivalent to change slashes to %2F, eg. in the view layer,
    <?php echo link_to(
        $employee->getTitle(),
        '/employee/bytitle?title='.
        urlencode($employee->getTitle())
    );  ?>

Additional Complication

Browsers may treat the encoded slash in the URL differently.

IE 7, 8 and Firefox 3, and Safari 3.2.1 on Windows display the URL in the address bar with the %2F intact, as you’d expect.

In Google Chrome 1.0.154.43, the links work but the address bar displays a slash instead of the encoded %2F, so if you hit the “Go” button you get a 404 error. Weird. Bug submitted!