php常用函数


// +----------------------------------------------------------------------
// 应用公共文件
/**
* 获取随机数的长度
* @param type $length 随机数长度
* @return string
*/
use think\Db;
use think\Cookie;
use lib\Rsa;
use think\File;
use think\Request;

function verifySign($params,$apikey="") {
ksort($params);
$string="";
foreach ($params as $k => $v) {

if($k != "sign" && $v != "" && !is_array($v)){
$string .= $k . "=" . $v . "&";
}
}
$string = $string . "key=".$apikey;
$string = md5($string);
$result = strtoupper($string);
return $result;
}

if (!function_exists('passWord')) {

function passWord($password) {
return md5(md5("lsf" . $password));
}

}
function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
{
if($code == 'UTF-8')
{
$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
preg_match_all($pa, $string, $t_string);
if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
return join('', array_slice($t_string[0], $start, $sublen));
}
else
{
$start = $start*2;
$sublen = $sublen*2;
$strlen = strlen($string);
$tmpstr = '';

for($i=0; $i< $strlen; $i++)
{
if($i>=$start && $i< ($start+$sublen))
{
if(ord(substr($string, $i, 1))>129)
{
$tmpstr.= substr($string, $i, 2);
}
else
{
$tmpstr.= substr($string, $i, 1);
}
}
if(ord(substr($string, $i, 1))>129) $i++;
}
//if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
return $tmpstr;
}
}
if (!function_exists('GetRmb')) {

function GetRmb() {
$rmb = 0;
$AppKey = "50777";
$Sign = "80780748ff7d3fe44ab2c03eba449cb0";
try {
$res = file_get_contents("http://api.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=" . $AppKey . "&sign=" . $Sign);
$data = json_decode($res, true);
if ($data["success"] == 1) {
$rmb = $data["result"]["rate"];
}
return $rmb;
} catch (\Exception $ex) {
return $rmb;
}
}

}
if (!function_exists('GetRandStr')) {

function GetRandStr($length) {
$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$len = strlen($str) - 1;
$randstr = '';
for ($i = 0; $i < $length; $i++) {
$num = mt_rand(0, $len);
$randstr .= $str[$num];
}
return $randstr;
}

}

/**
* 判断请求是否https和http
* @return string
*/
if (!function_exists('GetHttp')) {

function GetHttp() {
if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
return "https://";
} elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
return "https://";
}
return "http://";
}

}

/**
* 二维数据返回一维数组的指定的列
* @param type $input 指定的列
* @param type $columnKey 二维数组
* @param type $indexKey 键一般写
* @return type
*/
if (!function_exists('i_array_column')) {

function i_array_column($input, $columnKey, $indexKey = null) {
if (!function_exists('array_column')) {
$columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
$indexKeyIsNull = (is_null($indexKey)) ? true : false;
$indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
$result = array();
foreach ((array) $input as $key => $row) {
if ($columnKeyIsNumber) {
$tmp = array_slice($row, $columnKey, 1);
$tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
} else {
$tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
}
if (!$indexKeyIsNull) {
if ($indexKeyIsNumber) {
$key = array_slice($row, $indexKey, 1);
$key = (is_array($key) && !empty($key)) ? current($key) : null;
$key = is_null($key) ? 0 : $key;
} else {
$key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
}
}
$result[$key] = $tmp;
}
return $result;
} else {
return array_column($input, $columnKey, $indexKey);
}
}

function getIp() {
//strcasecmp 比较两个字符,不区分大小写。返回0,>0,<0。
if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$ip = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$ip = getenv('REMOTE_ADDR');
} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$ip = $_SERVER['REMOTE_ADDR'];
}
$res = preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
return $res;
}

/**
*
* @param type $content 操作的内容
* @param type $istype 日志类型 0后台日志,1前台日志
* @param type $username 操作人加上id
*/
function weihomSysLog($content, $istype, $username, $module = "") {
$data["content"] = $content;
$data["is_type"] = $istype;
$data["username"] = $username;
$data["addtime"] = time();
$data["module"] = $module;
$uniacid = Cookie::get('uniacid');
$data["uniacid"] = !empty($uniacid) ? Rsa::publicDecrypt($uniacid) : 0;
$data["ip"] = getIp();
$area = json_decode(file_get_contents("http://api.map.baidu.com/location/ip?ak=1amCKqfKoSobuxXg3q1Q1rYiUOX7czX9&ip=" . $data["ip"]), true);
try {
if (empty($area["status"])) {
$data["area"] = $area["content"]["address"];
} else {
$data["area"] = $area["message"];
}
} catch (\Exception $exc) {
$data["area"] = $exc->getMessage();
}
Db::name("sys_log")->insert($data);
}

/**
*
* @param type $content 操作的内容
* @param type $istype 日志类型 0后台日志,1前台日志
* @param type $username 操作人加上id
*/
function weihomSysPayLog($data) {
$model = Db::name("sys_paylog");
if ($model->where("tid", $data["ordersn"])->count() == 0) {
$newdata["title"] = $data["title"];
$newdata["uniacid"] = $data["uniacid"];
$newdata["openid"] = $data["userid"];
$newdata["type"] = $data["type"];
$newdata["tid"] = $data["ordersn"];
$newdata["fee"] = $data["money"];
$newdata["status"] = 0;
$newdata["module"] = $data["module"];
$newdata["create_time"] = date("Y-m-d H:i:s", time());
$res = $model->insert($newdata);
if ($res) {
return true;
} else {
return false;
}
return true;
}
return true;
}

/**
* 获取图片的网络路径
*/
if (!function_exists('httpImage')) {

function httpImage($url) {
if (strpos($url, "://") !== false) {
return $url;
} else {
return GetHttp() . $_SERVER['HTTP_HOST'] . $url;
}
}

}

/**
*
* @param type $model 表模型
* @param type $field 检查字段
* @param type $id 更新字段id
* @param type $value 值
*/
function isFieldRepeat($model, $where = array(), $id = 0) {
if ($id > 0) {
$count = $model->where("id", "<>", $id)->where($where)->count();
return $count;
} else {
$count = $model->where($where)->count();
return $count;
}
}

/**
* http请求
* @param type $url
* @param type $data
* @return type
*/
function httpRequest($url, $data = null) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}

/**
* xml转成数组
* @param type $xml
* @return type
*/
function FromXml($xml) {
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}

/**
* 数组转成xml
* @param type $xml
* @return type
*/
function ToXml($data = array()) {
if (!is_array($data) || count($data) <= 0) {
return '数组异常';
}
$xml = "";
foreach ($data as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "";
} else {
$xml .= "<" . $key . ">";
}
}
$xml .= "
";
return $xml;
}

/**
* 微信统一支付回调域名
* @return type
*/
function noticeWepayUrl() {
return GetHttp() . $_SERVER['HTTP_HOST'] . "/web/Payment/WepayNoticePayment";
}

/**
* 支付宝统一支付回调域名
* @return type
*/
function noticeAlipayUrl() {
return GetHttp() . $_SERVER['HTTP_HOST'] . "/web/Payment/AlipayNoticePayment";
}

/**
* 根据经纬度算距离
* @param $lat1
* @param $lng1
* @param $lat2
* @param $lng2
* @return int
*/
function getDistance($lat1, $lng1, $lat2, $lng2) {
//将角度转为狐度
$radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
$radLat2 = deg2rad($lat2);
$radLng1 = deg2rad($lng1);
$radLng2 = deg2rad($lng2);
$a = $radLat1 - $radLat2;
$b = $radLng1 - $radLng2;
$s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
return $s;
}

/**
* 对二维码数组排序
* @param type $array 二维数组
* @param type $key 需要排序的字段
* @param type $order 可以选择asc 和desc
* @return type
*/
function arrSort($array, $key, $order = "asc") {//asc是升序 desc是降序
$arr_nums = $arr = array();

foreach ($array as $k => $v) {
$arr_nums[$k] = $v[$key];
}
if ($order == 'asc') {
asort($arr_nums);
} else {
arsort($arr_nums);
}
foreach ($arr_nums as $k => $v) {
$arr[] = $array[$k];
}

return $arr;
}

/**
* 二维码数组求最大值
* @param type $arr 二维数组
* @param type $field 字段名
* @return type 返回最大数
*/
function getArrayMax($arr, $field) {
$temp = array();
foreach ($arr as $k => $v) {
$temp[] = $v[$field];
}
return max($temp);
}

/**
* 全概率计算中奖率
*
* @param array $p array('a'=>0.5,'b'=>0.2,'c'=>0.4)
* @return string 返回上面数组的key
*/
function rewardRandom($ps) {
static $arr = array();
$key = md5(serialize($ps));
if (!isset($arr[$key])) {
$max = array_sum($ps);
foreach ($ps as $k => $v) {
$v = $v / $max * 10000;
for ($i = 0; $i < $v; $i++)
$arr[$key][] = $k;
}
}
return $arr[$key][mt_rand(0, count($arr[$key]) - 1)];
}

/**
* 所有插件删除图片通用方法
* @param type $imgurl 图片路径
* @param type $uniacid 公众号id
* @param type $modules 插件名
*/
function deleteImg($imgurl, $uniacid, $modules) {
try {
unlink(ROOT_PATH . 'public' . $imgurl);
Db::name("appstore_images")->where(["image" => $imgurl, "modules" => $modules, "uniacid" => $uniacid])->delete();
} catch (Exception $ex) {

}
}

/**
* 所有插件上传图片通用方法
* @param type $file 文件
* @param type $uniacid 公众号id
* @param type $modules 插件名
* @return type
*/
function upload($file, $uniacid, $modules) {
if ($file) {
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/' . $uniacid);
if ($info) {
$getSaveName = str_replace("\\", "/", $info->getSaveName());
$images = "/uploads/" . $uniacid . "/" . $getSaveName;
Db::name("appstore_images")->insert(["image" => $images, "uniacid" => $uniacid, "modules" => $modules, "create_time" => date("Y-m-d H:i:s", time())]);
return array("success" => true, "data" => $images);
} else {
return array("success" => false, "msg" => $file->getError());
}
}
return array("success" => false, "msg" => "上传失败");
}

/**
* websocke解密算法
*
*/
function getBaseCode($char) {
return base64_decode(substr_replace($char, "", 8, 28));
}

// echo base64_encode("Hello World!") . "
";
// echo base64_encode("00") . "
";
// $a = base64_encode("run2.weihong.app,256,256,9999");
// echo "加密串:" . $a . "
";
// $b = substr_replace($a, 'bHNma2V5bHNma2V5bHNma2V5MDA=', 8, 0);
// echo "替换后加密串:" . $b . "
";
// echo "解密串:" . base64_decode($b) . "
";
// $c = substr_replace($b, "", 8, 28);
// // echo "替换解密串:".$c. "
";
// echo "替换解密串:" . base64_decode($c) . "
";
// exit();

function comomMember($data, $uniacid, $addons) {
$memberModel = Db::name("member");
$member = $memberModel->where(["openid" => $data["openid"], "uniacid" => $uniacid, "module" => $addons])->find();
$newdata = array(
"nickname" => trim($data["nickName"]),
"uniacid" => $uniacid,
"avatar" => trim($data["avatarUrl"]),
"openid" => trim($data["openid"]),
"province" => $data["province"],
"city" => $data["city"],
"sex" => $data["gender"],
"country" => $data["country"],
"module" => $addons
);
if (empty($member)) {
$newdata["addtime"] = date("Y-m-d H:i:s", time());
return $memberModel->insertGetId($newdata);
} else {
$newdata["uptime"] = date("Y-m-d H:i:s", time());
$newdata["uid"] = $member["uid"];
$memberModel->update($newdata);
return $member["uid"];
}
}

/**
* 去掉所有的空格和换行
* @param type $str 字符串
*/
function trimall($str) {
$qian = array(" ", " ", "\t", "\n", "\r");
return str_replace($qian, '', $str);
}

/**
* 腾讯地图获取地址信息
* @param type $data
* @return type
*/
function getTenxunBicycling($data) {
return json_decode(httpRequest('https://apis.map.qq.com/ws/direction/v1/bicycling/?from=' . $data["qaddress"]["latitude"] . ',' . $data["qaddress"]["longitude"] . '&to=' . $data["saddress"]["latitude"] . ',' . $data["saddress"]["longitude"] . '&output=json&callback=cb&key=' . $data["tenxunkey"]), true);
}

/**
* 方法二:判断判断是否是微信打开(好像不行)
*/
function isWeixin() {
$wxua = $_SERVER['HTTP_USER_AGENT'];
//MicroMessenger 是android/iphone版微信所带的
//Windows Phone 是winphone版微信带的 (这个标识会误伤winphone普通浏览器的访问)
if (strpos($wxua, 'MicroMessenger') == false || strpos($wxua, 'Windows Phone') == false) {
//echo "来自普通浏览器访问";
return false;
} else {
// echo "来自微信浏览器访问";
return true;
}
}

/*
* 通知模板组合
*/

function sendData($option) {
$pramvalue = array();
if (!empty($option["pramvalue"])) {
foreach ($option["pramvalue"] as $k => $v) {
if ($k == 0) {
$pramvalue["first"] = array('value' => urlencode($v),
'color' => '#743A3A');
} else {
$pramvalue["keyword" . $k] = array('value' => urlencode($v),
'color' => '#FF0000');
}
}
}
$option["url"] = empty($option["url"]) ? "javascript:;" : $option["url"];
$template = array(
"touser" => $option["openid"],
"template_id" => $option["templeteid"],
'url' => GetHttp() . $_SERVER['HTTP_HOST'] . $option["url"],
'topcolor' => '#ccc',
'remark' => array('value' => urlencode($option["remark"]),
'color' => '#FF0000'
)
);
if (!empty($pramvalue)) {
$template["data"] = $pramvalue;
}
return $template;
}

/**
* 大写字母转成你想要的
* @param type $word
* @return string
*/
function camelCase2underScoreCase($word = '', $spl = '_') {
$uc_word = '';
if (!empty($word)) {
$word_arr = str_split($word);
if (!empty($word_arr)) {
foreach ($word_arr as $k) {
if (ord($k) >= 65 && ord($k) <= 90) {
$k = $spl . chr(ord($k) + 32);
}
$uc_word .= $k;
}
}
}
return $uc_word;
}

/**
* 打印调试函数
* @param $content
* @param $is_die
*/
function pre($content, $is_die = true) {
header('Content-type: text/html; charset=utf-8');
echo '

' . print_r($content, true);
$is_die && die();
}

/**
* 驼峰命名转下划线命名
* @param $str
* @return string
*/
function toUnderScore($str) {
$dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
return '_' . strtolower($matchs[0]);
}, $str);
return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
}

/**
* 获取当前域名及根路径
* @return string
*/
function base_url() {
$request = Request::instance();
$subDir = str_replace('\\', '/', dirname($request->server('PHP_SELF')));
return $request->scheme() . '://' . $request->host() . $subDir . ($subDir === '/' ? '' : '/');
}

/**
* 写入日志
* @param string|array $values
* @param string $dir
* @return bool|int
*/
function write_log($values, $dir) {
if (is_array($values))
$values = print_r($values, true);
// 日志内容
$content = '[' . date('Y-m-d H:i:s') . ']' . PHP_EOL . $values . PHP_EOL . PHP_EOL;
try {
// 文件路径
$filePath = $dir . '/logs/';
// 路径不存在则创建
!is_dir($filePath) && mkdir($filePath, 0755, true);
// 写入文件
return file_put_contents($filePath . date('Ymd') . '.log', $content, FILE_APPEND);
} catch (\Exception $e) {
return false;
}
}

/**
* curl请求指定url
* @param $url
* @param array $data
* @return mixed
*/
function curl($url, $data = []) {
// 处理get数据
if (!empty($data)) {
$url = $url . '?' . http_build_query($data);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //这个是重点。
$result = curl_exec($curl);
curl_close($curl);
return $result;
}

if (!function_exists('array_column')) {

/**
* array_column 兼容低版本php
* (PHP < 5.5.0)
* @param $array
* @param $columnKey
* @param null $indexKey
* @return array
*/
function array_column($array, $columnKey, $indexKey = null) {
$result = array();
foreach ($array as $subArray) {
if (is_null($indexKey) && array_key_exists($columnKey, $subArray)) {
$result[] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
} elseif (array_key_exists($indexKey, $subArray)) {
if (is_null($columnKey)) {
$index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
$result[$index] = $subArray;
} elseif (array_key_exists($columnKey, $subArray)) {
$index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
$result[$index] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
}
}
}
return $result;
}

}

/**
* 多维数组合并
* @param $array1
* @param $array2
* @return array
*/
function array_merge_multiple($array1, $array2) {
$merge = $array1 + $array2;
$data = [];
foreach ($merge as $key => $val) {
if (
isset($array1[$key]) && is_array($array1[$key]) && isset($array2[$key]) && is_array($array2[$key])
) {
$data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
} else {
$data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
}
}
return $data;
}

/**
* 获取全局唯一标识符
* @param bool $trim
* @return string
*/
function getGuidV4($trim = true) {
// Windows
if (function_exists('com_create_guid') === true) {
$charid = com_create_guid();
return $trim == true ? trim($charid, '{}') : $charid;
}
// OSX/Linux
if (function_exists('openssl_random_pseudo_bytes') === true) {
$data = openssl_random_pseudo_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
// Fallback (PHP 4.2+)
mt_srand((double) microtime() * 10000);
$charid = strtolower(md5(uniqid(rand(), true)));
$hyphen = chr(45); // "-"
$lbrace = $trim ? "" : chr(123); // "{"
$rbrace = $trim ? "" : chr(125); // "}"
$guidv4 = $lbrace .
substr($charid, 0, 8) . $hyphen .
substr($charid, 8, 4) . $hyphen .
substr($charid, 12, 4) . $hyphen .
substr($charid, 16, 4) . $hyphen .
substr($charid, 20, 12) .
$rbrace;
return $guidv4;
}

/**
* 直接调用model方法
* @param type $model
* @return \model
*/
function addonsShopModel($mod) {
$model = "addons\shop\core\model\{$mod}";
$model = str_replace("{", "", $model);
$model = str_replace("}", "", $model);
return new $model;
}

/**
* 直接调用plugins方法
* @param type $model
* @return \model
*/
function addonsShopPlugins($mod) {
$model = "addons\shop\core\plugins\{$mod}";
$model = str_replace("{", "", $model);
$model = str_replace("}", "", $model);
return new $model;
}

/**
* 直接调用com方法
* @param type $model
* @return \model
*/
function addonsShopCom($mod) {
$model = "addons\shop\core\com\{$mod}";
$model = str_replace("{", "", $model);
$model = str_replace("}", "", $model);
return new $model;
}

/**
* 直接调用enum方法
* @param type $model
* @return \model
*/
function addonsShopEnum($mod) {
$model = "addons\shop\core\senum\{$mod}";
$model = str_replace("{", "", $model);
$model = str_replace("}", "", $model);
return new $model;
}

/**
* 下载网络图片
* @param type $url
* @return string
*/
function download_remote_pic($url) {
$header = [
'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding: gzip, deflate',
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$data = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($code == 200) {//把URL格式的图片转成base64_encode格式的!
$imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
}
$img_content = $imgBase64Code; //图片内容
//echo $img_content;exit;
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
$type = $result[2]; //得到图片类型png?jpg?gif?
return base64_decode(str_replace($result[1], '', $img_content));
}
}

/**
* 上传微信临时文件
* @param $filename 文件名+路径
* @return \CURLFile|string 返回可直接用于Curl发送的模式
* PHP5.5以后,将废弃以@文件名的方式上传文件。
*/
function http_post($url = '', $fileurl = '') {
$curl = curl_init();
if (class_exists('\CURLFile')) {
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$data = array('media' => new \CURLFile($fileurl));
} else {
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
}
$data = array('media' => '@' . realpath($fileurl));
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}

/**
* 获取图片访问绝对路径
*/
function getAbsolutePath($url) {
return "{$_SERVER['DOCUMENT_ROOT']}{$url}";
}

/**
* 任意时间本月的开始建和结束时间
* @param type $y
* @param type $m
* @return type
*/
function mFristAndLast($y = "", $m = "") {
if ($y == "")
$y = date("Y");
if ($m == "")
$m = date("m");
$m = sprintf("%02d", intval($m));
//填充字符串长度
$y = str_pad(intval($y), 4, "0", STR_PAD_RIGHT);
$m > 12 || $m < 1 ? $m = 1 : $m = $m;
$firstday = strtotime($y . $m . "01000000");
$firstdaystr = date("Y-m-01", $firstday);
$lastday = strtotime(date('Y-m-d 23:59:59', strtotime("$firstdaystr +1 month -1 day")));
return array(
"firstday" => $firstday,
"lastday" => $lastday
);
}
function json_response($success=true,$msg="",$data=''){
if(!$success && $msg==""){
$msg = "网络错误";
}

return json(
array(
"success"=>$success,
"msg"=>$msg,
"data"=>$data
)
);
}
}

你可能感兴趣的:(php常用函数)