Page 1 of 1

.htaccess and white space

Posted: Tue Aug 04, 2009 11:54 am
by jkwok
Hi,

I have a simple search input text field where a user can type in a string and get some search results. I'm trying to send the data using a clean URL with the search string in the URL.

ex. searching for 'golf' = http://www.mysite.com/search/golf

This works, however if the user inputs 'golf club' I get a 404 page not found error because of the white space. My .htaccess looks like this so far:

Code: Select all

 
RewriteEngine on
 
RewriteRule ^search/([a-zA-Z0-9_\-]+%)/?$ results.php?c=$1
 
And the code sending the data looks like this:

Code: Select all

 
<ul>
    <li><p>Search:</p></li>
    <li>
           <input id="searchLMARK" type="text" name="criteria">
    </li>
    <li><a href="" onclick="if(document.getElementById('searchLMARK').value!='')location.href='/search/' + escape(document.getElementById('searchLMARK').value);return false;"><span>Search</span></a></li>
</ul>
 
The results.php page then grabs the $_GET['c'] parameter and queries & displays results. Is there a way I can fix this white space error?

Thanks,
Jason

Re: .htaccess and white space

Posted: Tue Aug 04, 2009 11:57 am
by John Cartwright
Technically you should never have whitespace in the url, and is usually converted to an underscore or something for "clean urls".

However, to answer your questions need to add the space character to your range.

Code: Select all

RewriteRule ^search/([a-zA-Z0-9_\-\s]+%)/?$ results.php?c=$1

Re: .htaccess and white space

Posted: Tue Aug 04, 2009 12:10 pm
by jackpf
I believe conventional url encoding converts white space into a plus "+" symbol.

Re: .htaccess and white space

Posted: Tue Aug 04, 2009 1:33 pm
by jkwok
Hi guys,

Thanks for the quick replies! Taking John Cartwright's advice about never having whitespace in the URL I focused on working around it. I left my .htaccess file alone and instead changed the input being sent and the results.php page receiving the parameter as follows:

code snippet sending the parameter has been altered to exchange any blank space with a '-'

Code: Select all

 
 <ul>
     <li><p>Search:</p></li>
     <li>
            <input id="searchLMARK" type="text" name="criteria">
     </li>
     <li><a href="" onclick="if(document.getElementById('searchLMARK').value!='')location.href='/search/' + escape(document.getElementById('searchLMARK').value.split(' ').join('-'));return false;"><span>Search</span></a></li>
 </ul>
 
code from results.php takes the parameter and then replaces the '-' with a space so it can be used for a query.

Code: Select all

 
$landmark = str_replace('-',' ',mysql_real_escape_string($_GET['c']));
 
Thanks again to you both for your advice, very much appreciated.
Jason