views:

28

answers:

3

Hello,

I am very confused about the following:

echo("<a href='http://".urlencode("www.test.com/test.php?x=1&amp;y=2")."'&gt;test&lt;/a&gt;&lt;br&gt;");

echo("<a href='http://"."www.test.com/test.php?x=1&amp;y=2"."'&gt;test&lt;/a&gt;");

The first link gets a trailing slash added (that's causing me problems) The second link does not.

Can anyone help me to understand why. Clearly it appears to be something to do with urlencode, but I can't find out what.

Thanks c

+2  A: 

You should not be using urlencode() to echo URLs, unless they contain some non standard characters.

The example provided doesn't contain anything unusual.

Example

$query = 'hello how are you?';

echo 'http://example.com/?q=' . urlencode($query);
// Ouputs http://example.com/?q=hello+how+are+you%3F

See I used it because the $query variable may contain spaces, question marks, etc. I can not use the question mark because it denotes the start of a query string, e.g. index.php?page=1.

In fact, that example would be better off just being output rather than echo'd.

Also, when I tried your example code, I did not get a traling slash, in fact I got

<a href='http://www.test.com%2Ftest.php%3Fx%3D1%26y%3D2'&gt;test&lt;/a&gt;
alex
Thanks all, I see now from what you've all said and some testing that the server is obviously adding a trailing slash when it sees a domain level url.When I encode the whole url (I should have read the isntructions better) I hide the fact that the URL is a file level request which would normally not have a trailing slash added. Thanks.
Columbo
+1  A: 

string urlencode ( string $str )

This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

Your urlencode is not used properly in your case.

Plus, echo don't usually come with () it should be echo "<a href='http [...]</a>";

Chouchenos
Correct, because `echo` is a language construct, *not* a function.
alex
+1  A: 

You should use urlencode() for parameters only! Example:

echo 'http://example.com/index.php?some_link='.urlencode('some value containing special chars like whitespace');

You can use this to pass URLs, etc. to your URL.

elusive