搜索表单发布数据和平面URL

时间:2013-01-20 21:47:09

标签: php forms url

我有一个基于标签过滤文章的表单。因此,用户可以使用帖子数据访问example.com/news提交标签以进行过滤(例如tag1,tag2),这会使用过滤后的文章重新加载页面,但网址相同。

以下网址会带回相同的文章:example.com/news/tag1+tag2

两种方法都通过同一个控制器。我想让使用表单按标签过滤的用户重定向到example.com/news/tag1+tag2网址格式。

这样做的最佳方式是什么?是通过搜索控制器发送所有标记过滤器请求,然后创建重定向到example.com/news/tag1+tag2吗?

2 个答案:

答案 0 :(得分:1)

好像你不应该根据过滤标签的初始提交进行任何搜索。如果您通过搜索控制器一次然后重定向,您最终将进行两次搜索

如果用户提交要过滤的标记,请使用 only 构建网址并直接重定向到包含过滤标记的网址。既然你说它去了同一个搜索控制器,那么随后只会一次启动正确的搜索,并且用户的URL已经是你想要的最终结果了。

因此,只需从$_POST中检索已过滤的代码,然后立即重定向到最终结果网址,从而触发正确的搜索。

伪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 :(得分:0)

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