473,757 Members | 2,320 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with mod_rewrite and replacing spaces in URL

Sent this to alt.php a couple of days back, but doesn't look like I'll
get an answer, so trying here.

I'm trying to convert a script to use friendly URLs, I've done this
before, but my PHP skills are quite basic so far, far from proficient
at this.

..htaccess file-

DirectoryIndex default.php index.asp index.html index.htm index.php

Options +FollowSymLinks
RewriteEngine on

RewriteRule ^([^/]+)/Artist/([^/]+)/$ search.php?typ= $1&search=$2 [L]
RewriteRule ^([^/]+)/Artist/([^/]+)/([^/]+)/$
search.php?typ= $1&search=$2&pa ge=$3 [L]

RewriteRule ^([^/]+)/$ default.php?typ =$1 [L]
RewriteRule ^([^/]+)/([^/]+)/$ default.php?typ =$1&page=$2 [L]

RewriteRule ^([^/]+)/([^/]+)/$ default.php?typ =$1&cat=$2 [L]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/$
default.php?typ =$1&cat=$2&page =$3 [L]

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/$
default.php?typ =$1&cat=$2&sct= $3 [L]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/$
default.php?typ =$1&cat=$2&sct= $3&page=$4 [L]

Each set of rules creates these URLs-

example.com/$1/Artist/$2/
example.com/$1/Artist/$2/$3/ ($3 is a page number)

example.com/$1/
example.com/$1/$2/ ($2 is a page number)

example.com/$1/$2/
example.com/$1/$2/$3/ ($3 is a page number)

example.com/$1/$2/$3/
example.com/$1/$2/$3/$4/ ($4 is a page number)

It works.

However when variable $2 or $3 (when not a page number), for example
$2 of-

example.com/$1/Artist/$2/
example.com/$1/Artist/$2/$3/ ($3 is a page number)

Includes a space I can't get the PHP script to create an hyphenated
version that works even though at browser level the hyphen is there
(click on it, but the right page does not load).

So a starting URL like

example.com/ringtone/Artist/Britney%20Spear s/ (works)

Converted to-

example.com/ringtone/Artist/Britney-Spears/ (doesn't work)

Using a function (see later) that converts spaces to hyphens doesn't
load what I see at example.com/ringtone/Artist/Britney%20Spear s/
instead I see a 404 error page (blank script page) and I don't
understand why (I've used the function before)

Using urlencode instead of the function replaces spaces with + so I
see

example.com/ringtone/Artist/Britney+Spears/ (works)

but it's not the format I want and there are other characters I'd like
to remove including ( ) ! &.

So what is wrong with this function (which I don't fully understand
BTW)-

function text2url( $string ){
$string = ltrim($string);
// remove unnecessary spaces and make everything lower case
$string = preg_replace( "/ +/", " ", strtolower($str ing) );

// special rule for dashes, I think it looks nicer :-p
$string = str_replace(' - ', '-', $string);
// removing a set of reserved characters (rfc2396: ; / ? : @ & = + $
,)
$string =
str_replace(arr ay(';','/','?',':','@',' &','=','+','$', ',','#'), '',
$string);

// replace some characters to similar ones (more readable uris)
$search = array(' ', 'ä', 'ö', 'ü','ë','ï','é' ,'è','à','ç',);
#$replace = array('_','ae', 'oe','ue','e',' i','e','e','a', 'c');
$replace = array('-','ae','oe','ue ','e','i','e',' e','a','c');
$string = str_replace($se arch, $replace, $string);

// remove everything we didn't so far...
$string = preg_replace("/[^a-z0-9_-]/", "", $string);

// urlencode everything, in case we missed something ;-)
return urlencode($stri ng);
}

When I use it like this

$artist2 = text2url($artis t);

echo'<a href="'.$site_u rl.''.$typ.'/Artist/'.$artist2.'/1/"><img
src="'.$site_ur l.'button_more_ from.gif" alt="All Truetones from
'.$artist.'" border="0"></a>'.$artist.' ';
It converts spaces to hyphens, but within a browser it fails.
This works but adds +

echo'<a
href="'.$site_u rl.''.$typ.'/Artist/'.urlencode($ar tist).'/1/"><img
src="'.$site_ur l.'button_more_ from.gif" alt="All Truetones from
'.$artist.'" border="0"></a>'.$artist.'' ;
Thanks in advance for any help as I'm stumped.

David
--
SEO Tutorial http://www.seo-gold.com/tutorial/
More Earnings Blog http://www.morearnings.com/
Oct 17 '06 #1
2 6544
David wrote:
Sent this to alt.php a couple of days back, but doesn't look like I'll
get an answer, so trying here.

I'm trying to convert a script to use friendly URLs, I've done this
before, but my PHP skills are quite basic so far, far from proficient
at this.

<snip>

One thing I immediately noticed: your text2url function lowercases
everything, but your Britney Spears example is capitalized.

At a more fundamental level, how are you using the URL to lookup the
artists themselves? This is where the problem lies. You are going to
have to do the same transformation to the artist name when looking up
the artist that you did when creating the friendly URL.

For example, here is a simple scheme which lowercases the URL and
replaces spaces with dashes, and the corresponding database lookup.

..htaccess:
-----------------------------------------
RewriteRule ^artists/([^/]+) /artists.php?art istName=$1
-----------------------------------------
URL creation:
-------------------------------------------
$url = "/artists/" . strtolower(str_ replace(" ", "-", $artistName));
-------------------------------------------
Artist lookup (assumes PDO/PGSQL):
------------------------------------
$artist_query = $pdo->prepare("selec t * from artists where
LOWER(REPLACE(a rtist_name, ' ', '-')) = :artistName");

$artist_query->bindParam(":ar tistName", $_GET["artistName "]);
$artist_query->execute();
$artist = $artist_query->fetch();
-----------------------------

This code will obviously not work verbatim; it's just an example of how
you need perform the same transformation on artist names when you're
looking them up, or the comparison won't work. Notice how in my SQL
query I'm comparing the passed-in artist name (in the form of
"britney-spears") with the artist name in the database (in the form of
"Britney Spears") only AFTER I transform the database version to the
proper format - LOWER(REPLACE(. ..)) transforms "Britney Spears" to
"britney-spears", making the comparison successful.

Jeremy
Oct 17 '06 #2
On Tue, 17 Oct 2006 11:55:44 -0700, Jeremy <je****@pinacol .comwrote:
>David wrote:
>Sent this to alt.php a couple of days back, but doesn't look like I'll
get an answer, so trying here.

I'm trying to convert a script to use friendly URLs, I've done this
before, but my PHP skills are quite basic so far, far from proficient
at this.

<snip>


One thing I immediately noticed: your text2url function lowercases
everything, but your Britney Spears example is capitalized.
I'd tried it with and without lowercase, so that wasn't a major
problem. Don't mind if the URls have upper case characters.
>At a more fundamental level, how are you using the URL to lookup the
artists themselves? This is where the problem lies. You are going to
have to do the same transformation to the artist name when looking up
the artist that you did when creating the friendly URL.

For example, here is a simple scheme which lowercases the URL and
replaces spaces with dashes, and the corresponding database lookup.

.htaccess:
-----------------------------------------
RewriteRule ^artists/([^/]+) /artists.php?art istName=$1
-----------------------------------------
URL creation:
-------------------------------------------
$url = "/artists/" . strtolower(str_ replace(" ", "-", $artistName));
-------------------------------------------
I've tried similar and it's worked fine with other sites, just this
one fails!

Tried a simpler function-

function safeurl($name){
$retVal = str_replace('/',' ',$name);
$retVal = str_replace('-',' ',$retVal);
return $retVal;
}
To replace a / with a space and spaces with a -

Example code-
$viewart = '<div style="clear:bo th; text-align:right;
padding-right:15px;">
<h4>View All <a
href="'.$site_u rl.''.safeurl($ typ).'/Artist/'.safeurl($arti st).'/1/">Polyphoni c
Ringtones by '.$artist.'</a></h4>
</div>';
}
?>

<?php echo''.$viewart .'';?>
It works at code level, the \ and spaces are removed/replaced with -
when viewed in a browser but when clicking links they fail.
This code on the other hand works fine-

$viewart = '<div style="clear:bo th; text-align:right;
padding-right:15px;">
<h4>View All <a
href="'.$site_u rl.''.urlencode ($typ).'/Artist/'.urlencode($ar tist).'/1/">Polyphoni c
Ringtones by '.$artist.'</a></h4>
</div>';
}
?>

<?php echo''.$viewart .'';?>
This as expected replaces spaces with a + and characters like / are
replaced with %2F etc... the + URLs work but the / and some other
characters don't, so partial success.

I don't understand why the function fails?
>
Artist lookup (assumes PDO/PGSQL):
------------------------------------
$artist_quer y = $pdo->prepare("selec t * from artists where
LOWER(REPLACE( artist_name, ' ', '-')) = :artistName");

$artist_quer y->bindParam(":ar tistName", $_GET["artistName "]);
$artist_quer y->execute();
$artist = $artist_query->fetch();
-----------------------------
Does it make any difference that most of the data is from a CSV file
(no database)?

The code to get data is-

$row=0;
$file = fopen("$filepat h", "r");

while (($data = fgetcsv($file, 1000, ";")) !== FALSE) {
if ($sct==''){
if ($data[$DATA["typ"]]==$typ and $data[$DATA["cat"]]==$cat or
$data[$DATA["typ"]]==$typ and $cat==''){

$row++;

$nam[$row] = $data[$DATA["nam"]];
$dsc[$row] = $data[$DATA["dsc"]];
$dsl[$row] = $data[$DATA["dsl"]];
$pth[$row] = $data[$DATA["pth"]];
$ppl[$row] = $data[$DATA["ppl"]];

} }

if ($sct>''){
if ($data[$DATA["typ"]]==$typ and $data[$DATA["cat"]]==$cat and
$data[$DATA["sct"]]==$sct){

$row++;

$nam[$row] = $data[$DATA["nam"]];
$dsc[$row] = $data[$DATA["dsc"]];
$dsl[$row] = $data[$DATA["dsl"]];
$pth[$row] = $data[$DATA["pth"]];
$ppl[$row] = $data[$DATA["ppl"]];

} }
}
fclose($file);

First time I've worked with a site using a CSV file.

Should I be replacing the spaces etc... in this code somehow?
>This code will obviously not work verbatim; it's just an example of how
you need perform the same transformation on artist names when you're
looking them up, or the comparison won't work. Notice how in my SQL
query I'm comparing the passed-in artist name (in the form of
"britney-spears") with the artist name in the database (in the form of
"Britney Spears") only AFTER I transform the database version to the
proper format - LOWER(REPLACE(. ..)) transforms "Britney Spears" to
"britney-spears", making the comparison successful.
I tried variations of your code, but couldn't get anything to work.
>Jeremy
Thanks very much for the advice so far, appreciated.

David
--
Free Search Engine Optimization Tutorial
http://www.seo-gold.com/tutorial/
Oct 18 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2279
by: Westcoast Sheri | last post by:
Hello. How do I do this: If a visitor types in any number after my url, I want mod_rewrite to convert it to my url/anotherpage.html?number=number_visitor_typed Example: http://www.mysite.com/12345678.html would result in:
4
2551
by: Support | last post by:
Hello, I am running RedHat & Apache. RedHat does not allow creating more that 32000 subdirectories in one folder due to #defined constant limitation in the core code. I need to display 47000 directories on web page: e.g. mydomain.com/andrew , mydomain.com/bill , etc. Each directory contains .html/htm files and image files (*.jpg, *gif, jpeg etc.)
2
1584
by: Philo Hippo | last post by:
Hi, I need to be able to remove spaces from the beginning or the end of a string. This is my very 1st attempt at doing that in JS and here is what i got: function SearchForDomains(winName, SearchWhat) { var re = /\s*(\w*)\s*/;
8
19600
by: Andrew McNab | last post by:
Hi folks, I have a problem with an MS Access SQL query which is being used in an Access Report, and am wondering if anyone can help. Basically, my query (shown below) gets some records from a couple of tables in my database using INNER JOINS and the WHERE clause to specify the required constraints. However, I also want to read two fields from a *single* record from a table called 'Locations' and then apply one of these field's values...
11
2079
by: joelbyrd | last post by:
I have a people-networking type site in which each user has their own profile page, with their user id encoded. So, for example, the web address of their page might look like "www.example.com/my_profile.php?user_id=fdjkhfh2489298hf298h3s0dhfxj". I want the users to be able to choose their own web address that would look like "www.example.com/Joel", and then when they type in that address, they are automatically redirected to their profile...
5
2131
by: Fred.Grieco | last post by:
Hi every body, I have a little pb and I'm turning around : function MyFCTN(var1,var2) { var mytable = document.getElementById("myTBL"); for (var i=myTBL.childNodes.length-1; i>0; i--){ myTBL.removeChild(myTBL.childNodes); } for(var i=0; i<var1.length; i++){
3
1979
by: Rik G. | last post by:
I'm trying to replace a PHP query string with virtual directories using Apache's mod_rewrite. Here's my test .htaccess: RewriteEngine on RewriteRule ^qqq$ database.php?cat=0 RewriteRule ^qqq/xxx$ database.php?cat=0 The problem is that database.php contains several relative paths to images. This means mydomain/qqq works fine and all the images are found but when typing mydomain/qqq/xxx the file database.php seems to think it
10
6079
by: Adrian Smith | last post by:
This may be more a cgi thing than a Python one, but I'm trying to get this page: http://adrian10.phpwebhosting.com/trial.html consisting basically of this: <FORM ACTION="/cgi-bin/python3.cgi" METHOD="POST"> <TEXTAREA NAME="essay" COLS=60 ROWS=20 WRAP=HARD></TEXTAREA> <P><INPUT TYPE=SUBMIT VALUE="submit" NAME="submitbutton">
7
1740
by: Dale | last post by:
again, i know this is OT...just move along to the next post if it bugs you. :) i had been trying to have this: project.66.204.32.110 from the client browser, map to a virtual host where the document root would be:
0
9297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10069
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9884
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7285
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6556
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5168
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5324
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2697
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.