/** * Add param(s) at the end of an URL, using either "?" or "&" depending on existing url * * @param string existing url * @param string|array Params to add (string as-is) or array, which gets urlencoded. * @param string delimiter to use for more params */ function url_add_param($url, $param, $glue = '&') { if (empty($param)) { return $url; } if (($anchor_pos = strpos($url, '#')) !== false) { // There's an "#anchor" in the URL $anchor = substr($url, $anchor_pos); $url = substr($url, 0, $anchor_pos); } else { // URL without "#anchor" $anchor = ''; } // Handle array use case if (is_array($param)) { // list of key => value pairs $param_list = array(); foreach ($param as $k => $v) { $param_list[] = get_param_urlencoded($k, $v, $glue); } $param = implode($glue, $param_list); } if (strpos($url, '?') !== false) { // There are already params in the URL $r = $url; if (substr($url, -1) != '?' && substr($param, 0, 1) != '#') { // the "?" is not the last char AND "#" is not first char of param $r .= $glue; } return $r . $param . $anchor; } // These are the first params return $url . '?' . $param . $anchor; }
/** * Get URL param, urlencoded. * This handles arrays, recursively. * @return string */ function get_param_urlencoded($var, $value, $glue = '&') { if (is_array($value)) { // there is a special formatting in case of arrays $r = array(); $keep_keys = array_diff(array_keys($value), array_keys(array_values($value))); foreach ($value as $key => $value) { $r[] = get_param_urlencoded($var . '[' . ($keep_keys ? $key : '') . ']', $value, $glue); } return implode($glue, $r); } else { // not an array : normal formatting return rawurlencode($var) . '=' . rawurlencode($value); } }