Solutions for URL Manipulation and Browser Detection in PHP and JavaScript

Some useful code snippets collected during my Weixin official accounts development.

URL Parsing

Server-side URL Parsing - PHP

$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];

if ($params) {
    echo $protocol . '://' . $host . $script . '?' . $params;
} else {
    echo $protocol . '://' . $host . $script;
}

or with customized functions

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
echo curPageURL();

function curPageName() {
 return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
echo curPageName();

Client-side URL Parsing - Javascript

// Client-side JavaScript
// find the first link in the DOM
var url = document.createElement('a');
url.href = window.location.href;

console.log(
    'href = ' + url.href + '\n' +           // the full URL
    'protocol = ' + url.protocol + '\n' +       // http:
    'host = ' + url.host + '\n' +       // example.com:80
    'hostname = ' + url.hostname + '\n' +       // example.com
    'port = ' + url.port + '\n' +           // 80
    'pathname = ' + url.pathname + '\n' +       // /path/page
    'search = ' + url.search + '\n' +         // ?a=1&b=2
    'hash = ' + url.hash                    // #hash
);

Add Parameter to URL

Server-side Handling - PHP

<?php
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];

//$uri = $_SERVER[REQUEST_URI];
//$phpself = $_SERVER['PHP_SELF'];

if ($params) {
    echo $protocol.'://'.$host.$script.'?'.$params.'&usrid=100';
} else {
    echo $protocol.'://'.$host.$script.'?usrid=100';
}
?>

Client-side Handling - Javascript

if (window.location.href.indexOf("usrid=") == -1) { //Avoid looping refreshing
    if(window.location.search === "") {
        window.location.href = window.location.href + "?usrid=100";
    } else {
        window.location.href = window.location.href + "&usrid=100";
    }
};

Update or Append URL Parameter

Server-side Handling - PHP

function addOrUpdateParameter($paramName, $paramValue) {
    $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
    $host = $_SERVER['HTTP_HOST'];
    $script = $_SERVER['SCRIPT_NAME'];

    $params = $_GET;
    $params[$paramName] = $paramValue;
    $paramString = http_build_query($params);

    return $protocol.'://'.$host.$script.'?'.$paramString;
}

echo addOrUpdateParameter('usrid', 100);

And Some Other Hints

str_replace('&b='.$_GET['b'], '', $_SERVER['QUERY_STRING']);
preg_replace('/(^|&)b=[^&]*/', '', $_SERVER['QUERY_STRING']);

// 1. parse_url() to extract the query string from the URL
// 2. parse_str() to split the query string into an array
// 3. array_merge() to add a new array "b" => 5
// 4. http_build_query() to re-build a query string
// 5. The remaining parts from the first step (protocol, host, path...) to re-build the full URL or - if you have the HTTP pecl extension - a http_build_url() with HTTP_URL_JOIN_QUERY will alleviate much of the work.

Client-side Handling - Javascript

function addOrUpdateParameter(paramName, paramValue) {
    var url = window.location.href;
    var hash = location.hash;
    url = url.replace(hash, '');
    if (url.indexOf(paramName + "=") >= 0) {
        var prefix = url.substring(0, url.indexOf(paramName));
        var suffix = url.substring(url.indexOf(paramName));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        currentParamValue = (suffix.indexOf("&") >= 0) ? suffix.substring(0, suffix.indexOf("&")) : suffix;
        if (currentParamValue.localeCompare(paramValue) == 0) return; //Avoid looping refreshing
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + paramName + "=" + paramValue + suffix;
    } else {
        if (url.indexOf("?") < 0) {
            url += "?" + paramName + "=" + paramValue;
        }
        else{
            url += "&" + paramName + "=" + paramValue;
        }
    }
    window.location.href = url + hash;
}

addOrUpdateParameter('usrid','100');

Browser Detection

判定微信的内置浏览器方法

<?php
function is_weixin(){  
    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
        return true;
    }  else {
        return false;
    }
}
?>
function is_weixin() {
        var ua = navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i)=="micromessenger") {
            return true;
        } else {
            return false;
        }
    }

Others

微信开发-新浪SAE开发平台验证Token一直失败

原因: 如果不进行实名认证,SAE会在回复的内容中会带上干扰的html内容信息,从而导致Token验证失败或者该公众号暂时无法提供服务,请稍后再试
解决办法: 在echo $echoStr;之前添加header('content-type:text');就可以验证成功了.

微信公众平台文字回复换行问题

如果\n是用单引号'包装的话,安卓6.0上面是原样输出\n的,不过换成用双引号"包装的话就输出正常了。

js解决微信或者iOS中下拉网页出现“由XXX提供”

原理:阻止最外层的html向浏览器传递他们已经到头的信息!

document.addEventListener(‘touchstart’,stopScrolling,false);
document.addEventListener(‘touchmove’,stopScrolling,false);
function stopScrolling(touchEvent) {
    touchEvent.preventDefault();
}

References


* cached version, generated at 2019-06-22 17:38:31 UTC.

Subscribe by RSS