宗小宗-PHP程序猿

欢迎各位朋友前来,如果我的文章中有不对的地方,还望指正;如需转载,请注明原处

PHP个人常用函数封装

function GetIP(){
    if(!empty($_SERVER["HTTP_CLIENT_IP"])){
          $cip = $_SERVER["HTTP_CLIENT_IP"];
    }elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
          $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }elseif(!empty($_SERVER["REMOTE_ADDR"])){
          $cip = $_SERVER["REMOTE_ADDR"];
    }else{
          $cip = "";
    }
    return $cip;
}
function HttpRequest($url, $type = 'get', $data = '',$timeout = 10,$header = array())
    {$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if (strtoupper($type) == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_ENCODING , 'gzip');
        $result['response'] = curl_exec($ch);
        $result['status']=curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $result;
    }
function SaveLog($content = '', $filename = 'others')
    {
        $rootDir = \Config::get('app.rootDir');
        $logdir = $rootDir . '/app/storage/logs/';
        if (!is_dir($logdir)) mkdir($logdir, 0777, true);
        $filename = $filename.'_'.date('ymd');
        $filename = $logdir . $filename . ".log";
        $fp = fopen($filename, "a+");
        $line = 1;
        while (stream_get_line($fp, 8192, "\n")) {
            $line++;
        }
        if ($line > 9999) {
            file_put_contents($filename, '');
            $line = 1;
        }
        $info = '<' . sprintf("%04d", $line) . '>' . date("Y-m-d H:i:s") . '<>';
        $string = $info . str_replace("\n", "", str_replace("\r", "", $content)) . "\r\n";
        file_put_contents($filename, $string, FILE_APPEND);
        fclose($fp);
    }
/**
     * 获取或保存文件内容
     * @param string $filedir 文件路径
     * @param string $content 文件内容
     * @return string
     */
    function FileContent($filedir = '', $content = '')
    {
        if (empty($filedir)) return '';
        if (empty($content)) {
            if (file_exists($filedir)) {
                $fp = fopen($filedir, "r");
                $content = file_get_contents($filedir);
                fclose($fp);
                return $content;
            } else {
                return '';
            }
        } else {
            $fps = fopen($filedir, "a");
            file_put_contents($filedir, $content);
            fclose($fps);
            return true;
        }
    }

 

posted @ 2016-04-02 11:53  宗小宗  阅读(577)  评论(0编辑  收藏  举报