Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal url encoding

I am having trouble properly encoding URL data. Using the following code:

$redirect = drupal_urlencode("user/register?destination=/node/1");
drupal_goto( $redirect );

but, the URL that comes up in my browser test is the following:

http://testsite.com/user/register%253Fdestination%253D/node/1

I thought using the drupal_urlencode function should fix this encoding issue. Can anyone suggest a way to fix this, please?

like image 638
sisko Avatar asked Dec 24 '11 15:12

sisko


People also ask

How do you encode a URL?

URL Encoding (Percent Encoding) URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.

What is the best way to URL encode a string?

URLEncoder is the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character = .

Should you encode URL parameters?

Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing into a URL.


1 Answers

You'd be better off using the built in url() function to create your URL, if you pass an array as the query parameter it handles URL encoding for you:

$options = array(
  'absolute' => TRUE,
  'query' => array('destination' => '/node/1')
);
$redirect = url('user/register', $options);

drupal_goto( $redirect );

drupal_encode() will encode the whole string that you pass to it, so if you want to do it your original way it would look like this:

$redirect = 'user/register?' . drupal_urlencode("destination=/node/1");
drupal_goto( $redirect );     
like image 156
Clive Avatar answered Sep 24 '22 03:09

Clive