php代码片段系列之json与获取ip

代码片段系列--原生

 

//获取ip地址
private function getip()
{
    if (isset($_SERVER)) {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } elseif (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER['REMOTE_ADDR'];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")) {
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }
    $l = strpos($realip, ',');
    if ($l) {
        $realip = substr($realip, 0, $l);
    }
    return $realip;
}

-----------------------------------------------------------------------------------------------------

//输出json
private function outPrintApiJson($code, $msg, $data = array(), $info = array())
{
    //header("Content-Type:application/json");
    $array = array(
        "code" => $code,
        "msg" => $msg,
    );
    if (!empty($data)) {
        $array["data"] = $data;
    }
    if (!empty($info)) {
        $array["info"] = $info;
    }
    echo $_GET['callback'] . '(' . json_encode($array) . ')'; //用jsonp兼容IE9以下浏览器
    exit;
}

你可能感兴趣的:(PHP基础,PHP)