Retaining a search string in the URL

As you know, for a good reason, CakePHP will use the POST method by default to submit form data. However, there is a case where this could present a problem…

Let’s say you are building a little search tool for all of your articles. It would be nice to allow people to bookmark or copy/paste the search URL, which would look like this:

If you have a form that does the POST of the search term “Hippopotamus” that’s not going to work just like that.

Instead, create a form that will POST to searchRedirect() action, which would look something like:

function searchRedirect() {        
  if(!empty($this->data)) {            
    $this->redirect(array('controller'=>'articles', 'action'=>'search', $this->data['Article']['searchField']));      

Now you can build your search() action to read the value from the URL (which was passed via the redirect) and do whatever it has to display the results… and of course you now have the search term visible in the URL.

The example above is simplistic and you probably want to make sure to use urlencode() urldecode() or some other method to ensure that you read safe data from the URL param. Better yet, you might want to store the search term in the session (and read it from there), so that if someone tampers with the URL, it won’t cause any problems in your app.

P.S. FYI, this can hardly be called a hack as it is actually a common enough practice in web development

Related Posts