PHP个人常用函数封装

时间:2023-11-21 13:22:50
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;
}
}