Search form data and flat urls

I have a form that filters articles based on tags. So the user can visit example.com/news

submit tags for filtering using (eg tag1, tag2) using post data, this reloads the page with filtered articles but with the same url.

The following URL will return the same articles: example.com/news/tag1+tag2

Both methods go through the same controller. I would like to have users filtered by tags using a form be redirected to example.com/news/tag1+tag2

url format .

What's the best way to do this? Will this send all tag filter requests through the search controller and then create a redirect to example.com/news/tag1+tag2

?

+3


source to share


2 answers


It looks like you shouldn't be searching based on the original submission of the filtered tags. If you go through a search controller and then redirect, you end up doing two searches.

If a user submits tags for filtering, use them only to generate a URL and redirect directly to the URL containing the filtered tags. Since you said it goes to the same search controller, which 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 download the filtered tags from $_POST

and immediately redirect to the final result url that 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();

      

+1


source


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

      



0


source







All Articles