Bengau
Bengau

Reputation: 175

Friendly URL from query srings URL

What is the best way to do when I type a search on my site to get the url like mysite.com/searach/blabla/video instead of mysite.com/?search=blabla&type=video. Please don't tell me that I have to use CodeIgniter because it doesn't help. I am sure that all I need is a small function in PHP.

This is my search.php:

<form id="searchwrapper" name="searchform">
<input type="text" class="searchbox" id="txtSearch" name="search" alt="Search Criteria" />
<input type="submit" src="../images/empty.png" class="searchbox_submit"/>

<p id="circ">
<input  type="radio" id="mp3" name="type" checked value="mp3"/>
<label class="circ-btn normal" for="mp3">mp3</label>
                        </p>
<p id="circ">
<input type="radio" id="album" name="type" <?php echo $radio2;?> value="album"/>
<label class="circ-btn normal" for="album">Album</label></p>                
</form>

My .htacces rules are set correctly; when I access my site directly using mysite.com/searach/blabla/video, it works fine, but this is not the issue. I need to have my link like this when I type a search on my site. Instead I get this link and is not right mysite.com/?search=blabla&type=video.

Upvotes: 0

Views: 422

Answers (3)

gllen
gllen

Reputation: 66

As others commented, you need mod_rewrite if you're using apache.

If you actually want to type in a search and end up at a SEF URL, as you described, you want something like:

RewriteCond %{QUERY_STRING} ^search=(\w+)&type=(\w+)$
RewriteRule ^ http://mysite.com\/%1\/%2? [R,L]

.. which would redirect requests such as

http://mysite.com/index.php?search=A&type=B

.. to

http://mysite.com/A/B

.. and JKirchartz provided the sample to use a php script for a SEF url, for example, having apache serve

http://mysite.com/video.php?search=A&type=B

.. behind the scenes when

http://mysite.com/A/B

.. is requested

Upvotes: 1

JKirchartz
JKirchartz

Reputation: 18022

You can use mod_rewrite, and put this in your .htaccess file

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^search/([^/\.]+)/([^/\.]+)/?$ index.php?search=$1&type=$2 [L]

then use this in your php

$URI = substr($_SERVER['REQUEST_URI'], 1);
$URIparts = explode("/", $URI);

That gives you an array with the parts of the url.

Also you should try to sanitize the input for security.

Upvotes: 2

Matt
Matt

Reputation: 43

You can use apache Mod Rewrite, though it can be frustrating for someone just learning it. Alternatively, you could move your site to a cms like drupal, wordpress, or joomla and have it automatically create an alias for you.

Upvotes: 0

Related Questions