Sometimes when you're designing a website without using a CMS like Wordpress, or your project uses more than one CMS, it becomes necessary to look outside the box for a website search solution. Thankfully it's rather easy to set up with the help of an external search engine. I prefer duckduckgo.com since it's a privacy-first search engine which doesn't track you.
To add the form to your website, use the following html:
<form method="get" action="search.php" target="_blank"> <input placeholder="Search" name="query" /><input type="submit" value="Go" /> </form>
You'll notice the form action refers to search.php, which contains the function that makes the whole thing work. In the same directory as your html file, create a new file called search.php and paste the following inside it:
<?php $term = $_GET["query"]; // This line gets the search term submitted by the user $term = preg_replace('/[^A-Za-z0-9-s]/', '', $term); // This line uses a regex to remove anything other than letters and numbers from the term so we don't break our search $term = str_replace(" ","+",$term); // Replaces spaces with pluses $urlstub = "https://duckduckgo.com/?q=site:fabulouspanda.com+"; // Replace fabulouspanda.com with your own domain. This adds the formatted search term to the duckduckgo url header('Location:'.$urlstub.$term); // redirect the user to our custom search die(); //make sure to kill the process now that it's all done ?>
Now your form will function as expected. However there are more options you can change such as removing
If you'd rather not send users in to a new window or tab when they search.
You may also want to filter out special characters as users are typing their query, which can be accomplished by adding a little onkeyup regex to the input field like so:
<input type="text" class="input-field" name="query" placeholder="Search" onkeyup="this.value = this.value.replace(/[^a-zA-Z0-9_-s]/g, '')" /><input type="submit" value="Submit" />
Then it's up to you to style your form in keeping with the appearance of your website. For some inspiration I've put together a few of the styling options here, which also serves as a good example of this tutorial's code at work.
If you have any questions, comments or improvements I'd love to hear them in the comments below or on the FabulousPanda Forum