Skip to content

Instantly share code, notes, and snippets.

@kriswallsmith
Created August 8, 2012 18:23
Show Gist options
  • Save kriswallsmith/3297290 to your computer and use it in GitHub Desktop.
Save kriswallsmith/3297290 to your computer and use it in GitHub Desktop.
implements QSA on Symfony2 redirects
<?php
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
/** @DI\Service */
class QSAListener
{
private $blacklist;
/** @DI\InjectParams({"blacklist"=@DI\Inject("%qsa.blacklist%")}) */
public function __construct(array $blacklist = array())
{
$this->blacklist = $blacklist;
}
/** @DI\Observe("kernel.response") */
public function onKernelResponse(FilterResponseEvent $event)
{
$request = $event->getRequest();
$response = $event->getResponse();
if (!$response->isRedirection() || !$request->isMethodSafe() || !$request->query->all()) {
return;
}
$query = array();
foreach (array_diff($request->query->keys(), $this->blacklist) as $key) {
$query[$key] = $request->query->get($key);
}
// attach the query string
$location = $response->headers->get('Location');
$location .= false === strpos($location, '?') ? '?' : '&';
$location .= http_build_query($query);
// modify the response content
$response->setContent(str_replace(
htmlspecialchars($response->headers->get('Location'), ENT_QUOTES, 'UTF-8'),
htmlspecialchars($location, ENT_QUOTES, 'UTF-8'),
$response->getContent()
));
// modify the location header
$response->headers->set('Location', $location);
}
}
@cordoval
Copy link

cordoval commented Aug 8, 2012

I see it is like a secure blocker of IPs, wonder what QSA stands for?

@phuedx
Copy link

phuedx commented Aug 8, 2012

@cordoval in this instance QSA stands for Query String Append. It's an emulation of mod_rewrite's [QSA] flag, which appends any query string parameters in the substitution URL to the query string parameters of the original URL.

@kriswallsmith
Copy link
Author

Thanks @phuedx!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment