#native_company# #native_desc#
#native_cta#

urlStrEncode / urlStrDecode

By Fred Scalliet
on April 2, 2004

Version: 0.1

Type: Function

Category: HTTP

License: Other

Description: Encodes/decodes a string to/from an url-argument compatible one. (“my page” => “my%20page”). I suspect that such functions already exist in the basic package, but I couldn’t find them in the doc so I coded some anyway 😉

<?
// These encode/decode functions are only indispensable for region-specific 
// characters under some browsers (like MSIE for example), and harmless in any 
// other case, except if the encoded string is an URL/filename beginning with a 
// special character (which shouldn't happen anyway), and that you forget to 
// decode it.

// THIS SCRIPT IS ABSOLUTELY COMPLETELY TOTALLY PUBLIC DOMAIN
// original author: http://fred.dsimprove.org/


// Create a string of all characters that aren't special and 
// thus won't need to be url-encoded:

$urlNormalCharArray = array('09','az','AZ','_','-','.','/') ;
$urlNormalCharStr   = '' ;
foreach ($urlNormalCharArray as $span) {
  $min = ord($span[0]) ;
  if (!($max = ord(@$span[1])))
    $max = $min ;
  for ($i = $min ; $i <= $max ; $i++)
    $urlNormalCharStr .= chr($i) ;
  }

// destroy obselete variables (useless but looks pro ;)

unset ($min, $max, $span, $i) ;
unset ($urlNormalCharArray) ;

//echo "<pre>n" ; print_r ($urlNormalCharStr) ; echo "n</pre>n" ; //DEBUG//
//echo urlStrEncode("azerty c'est un trs beau nom")."<br>n"; //TEST (iso-8859-1)
//echo urlStrDecode("azerty%20c%27est%20un%20tr%e8s%20beau%20nom")."<br>n"; //TEST//


// and now the functions :


function urlStrEncode ($s) {   
  if ($s === 0) $s = '0' ;
  else if (empty($s)) $s = '' ;

  global $urlNormalCharStr ;
  $r = '' ;

  for ($i=0 ; $i<strlen($s) ; $i++) {
    $c  = $s[$i] ;
    $r .= ( strchr($urlNormalCharStr,$c) ? $c : '%'.dechex(ord($c)) ) ;
    }
  
  return $r ;
  }


function urlStrDecode ($s) {
  if ($s === 0) $s = '0' ;
  else if (empty($s)) $s = '' ;

  $r = '' ;

  for ($i=0 ; $i<strlen($s) ; $i++) {
    $c = $s[$i] ;
    if ($c == '%') {
      $r .= chr(hexdec($s[$i+1].$s[$i+2])) ;
      $i += 2 ;
      }
    else {
      $r .= $c ;
      }
    }

  return $r ;
  }


// ------

?>