xylar
xylar

Reputation: 7673

Search form post data and flat URLs

I have a form which filters articles based on tags. So a user may visit example.com/news submit the tags to filter by (e.g. tag1, tag2) using post data, this reloads the page with the filtered articles but the same URL.

The following url will bring back the same articles: example.com/news/tag1+tag2

Both methods go through the same controller. I would like to make users who have filtered by tags using the form are redirected to example.com/news/tag1+tag2 url format.

What is the best way of doing this? Would it be to send all tag filter requests through a search controller and then create a redirect to example.com/news/tag1+tag2?

Upvotes: 3

Views: 108

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270607

Seems like you should not do any search based on the initial submission of the filtered tags. If you passed through the search controller once then redirected, you would end up doing two searches.

If a user submits tags to filter, use those only to build a URL and redirect directly to the URL containing the filtered tags. Since you said it goes to the same search controller, that will subsequently initiate the correct search only once and the user's URL will already be what you want its end result to be.

So just retrieve the filtered tags from $_POST and immediately redirect to the end result URL which triggers the correct search.

Pseudo PHP

$valid_tags = array_filter($_POST['tags'], function($t) {
   // validate tags as alphanumeric (substitute the appropriate regex for your tag format)
   // this discards non-matching invalid tags.
   return preg_match('/^[a-z0-9]+$/i', $t);
});
// Don't forget to validate these tags in the search controller!
// Implode the tags (assuming they are received as an array) as a space separated string
// and urlencode() it
$tags = urlencode(implode(" ", $valid_tags));
header("Location: http://example.com/news/$tags");
exit();

Upvotes: 1

keyboardSmasher
keyboardSmasher

Reputation: 2811

$tags = 'tag1+tag2';
header ('Location: /news/' . $tags);
exit;

Upvotes: 0

Related Questions