Voting

: two plus six?
(Example: nine)

The Note You're Voting On

Lucas Gonze -- lucas at gonze dot com
20 years ago
I have attempted to incorporate all of the previous comments, plus several bug fixes, into dphantom's linkencode. I see no bugs for these test cases:
http://example.com/path1;var1=val1/p2;v2
http://example.com/p1;v1/p2;v2
http://[ip:v6:440]:8080
http://example.com:8080
http://example.com/~joe
http://example.com/foobar/~joe
http://username:password@hostname/path 1//path 2/?arg 1=value 1&arg 2=value 2#fragment identifier
hostname/path 1//path 2/?arg 1=value 1&arg 2=value 2#fragment identifier
http://invalid_host..name/

function linkencode($p_url){
$uparts = @parse_url($p_url);

$scheme = array_key_exists('scheme',$uparts) ? $uparts['scheme'] : "";
$pass = array_key_exists('pass',$uparts) ? $uparts['pass'] : "";
$user = array_key_exists('user',$uparts) ? $uparts['user'] : "";
$port = array_key_exists('port',$uparts) ? $uparts['port'] : "";
$host = array_key_exists('host',$uparts) ? $uparts['host'] : "";
$path = array_key_exists('path',$uparts) ? $uparts['path'] : "";
$query = array_key_exists('query',$uparts) ? $uparts['query'] : "";
$fragment = array_key_exists('fragment',$uparts) ? $uparts['fragment'] : "";

if(!empty($scheme))
$scheme .= '://';

if(!empty($pass) && !empty($user)) {
$user = rawurlencode($user).':';
$pass = rawurlencode($pass).'@';
} elseif(!empty($user))
$user .= '@';

if(!empty($port) && !empty($host))
$host = ''.$host.':';
elseif(!empty($host))
$host=$host;

if(!empty($path)){
$arr = preg_split("/([\/;=])/", $path, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
$path = "";
foreach($arr as $var){
switch($var){
case "/":
case ";":
case "=":
$path .= $var;
break;
default:
$path .= rawurlencode($var);
}
}
// legacy patch for servers that need a literal /~username
$path = str_replace("/%7E","/~",$path);
}

if(!empty($query)){
$arr = preg_split("/([&=])/", $query, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
$query = "?";
foreach($arr as $var){
if( "&" == $var || "=" == $var )
$query .= $var;
else
$query .= urlencode($var);
}
}

if(!empty($fragment))
$fragment = '#'.urlencode($fragment);

return implode('', array($scheme, $user, $pass, $host, $port, $path, $query, $fragment));
}

<< Back to user notes page

To Top