索引
- php常用方法
- base64保存为图片
- 判断时间
- 裁剪图片
- 百度地图经纬度转腾讯地图经纬度
- 中奖概率换算
- 判断时间是否在某个区域内
- 去除Bom头
- 获取近1年的所有月份
- 获取两个时间戳的相差天数,小时,分钟,秒
- 判断是否手机浏览器
- 设置脚本运行时间
- curl的get-post方式
- Hmac加密
- 获取区域网IP地址
- 判断ip是否在允许范围内
- 文件下载
- get请求
- post请求
- 图片合成
- 生成验证码
- 多图上传保存
- excel导出
- excel导入
- 图片缩放
- 下载远程图片到本地
- 解析url地址获得参数
- 下载视频
- curl分片现在大文件
php常用方法
//判断某个字符是否在数组内
bool in_array ($needle,$array [,strict])
//例子:
//分割字符串
preg_split();
//例子:
$str='1,2,3,4';
preg_split('/,/',$str);
//求数组交集,并集,差集
array_diff()//差集
array_merge ( array array1[,array… ] ) //并集
array_intersect ( array array1,arrayarray2 [, array $ … ] ) //交集
//数组的插入,头部,尾部,中部
//头部
array_unshift(array $array,$val)//头部插入
array_shift()//头部移除
array_push(array $array,$val)//插入尾部
array_pop()//
//数组去除重复值
array_unique()
//一维数组转为字符串
implode
//字符串转为数组
explode
base64保存为图片
多用网站裁剪图片上传
public function upload2(){
$pid = $_SESSION['cmpid'];
$model='communication';
$categpry='img';
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $this->post->file, $result)) {
$ramd = $this->loadModel('businesscard')->random(6, 0);
$type = $result[2];
$new_file ='slidimg/'.time() . $ramd . '.' . $type;
// $new_file = "./test.{$type}";
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $this->post->file)))) {
// $ym = date('Ym', time());
// $upload_path = $this->app->getAppRoot() . "www/data/upload/" . $model . '/' . $categpry . '/' . $ym . "/"; //上传文件的存放路径
// //开始移动文件到相应的文件夹
// if (!file_exists($upload_path)) {
// mkdir($upload_path, 0777, true);//创建目录
// }
// if (copy('/module/communication/1512122578eT7Vin.jpeg','/www/data/upload/communication/img/201712/s.jpeg')) {
// echo "ok";
// } else {
// echo 'false';
// }
$this->dao->insert(TABLE_CSLIDERIMG)
->set('url')->eq('module/communication/'.$new_file)
->set('create_time')->eq(helper::now(time()))
->set('cpid')->eq($pid)
->exec();
echo '新文件保存成功:', $new_file;
}
}
// echo 'xxx----' . $a;
// $pid = ‘123124afeewrt234’;
// $upload=$this->communication->uploadimg($pid);
// echo $upload;
}
判断时间
if(date('Y-m-d')==date('Y-m-d', strtotime($res[0]->createtime))){
$finance_day_num+=1;
$finance_day_money+=$res[0]->payamount;
}
裁剪图片
public function upload3()
{
$pid = $_SESSION['cmpid'];
$allow_type = array('jpg', 'jpeg', 'gif', 'png'); //定义允许上传的类型
$file = $this->loadModel('businesscard')->file($_FILES['file'], $allow_type, 'communication', 'img');
$ramd = $this->loadModel('businesscard')->random(6, 0);
$filename=time() . $ramd;
if ($file) {
$left = $this->post->left;
$width = $this->post->width;
$height = $this->post->height;
$top = $this->post->top;
$image = '../../' . $file;
$source = imagecreatefromjpeg($image);
$croped = imagecreatetruecolor($width, $height);
imagecopy($croped, $source, 0, 0, $left, $top, $width, $height);
imagejpeg($croped, "$filename.jpg");
imagedestroy($croped);
unlink('../../' . $file);
$fielPath=preg_split('/\//', $file);
if (copy("$filename.jpg", "../../$fielPath[0]/$fielPath[1]/$fielPath[2]/$fielPath[3]/$fielPath[4]/$fielPath[5]/$filename.jpg")) {
unlink("$filename.jpg");
$this->dao->insert(TABLE_CSLIDERIMG)
->set('url')->eq("$fielPath[0]/$fielPath[1]/$fielPath[2]/$fielPath[3]/$fielPath[4]/$fielPath[5]/$filename.jpg")
->set('create_time')->eq(helper::now(time()))
->set('cpid')->eq($pid)
->exec();
echo 1;
} else {
echo 0;
}
} else {
echo 0;
}
}
百度地图经纬度转腾讯地图经纬度
/**
* 百度地图经纬度转腾讯地图经纬度
* @param $lat
* @param $lon
* @return string
*/
public function map_bd2tx($lat, $lon)
{
$tx_lat = 0;
$tx_lon = 0;
$x_pi = 3.14159265358979324;
$x = $lon - 0.0065;
$y = $lat - 0.006;
//Math
$z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
$theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
$tx_lon = $z * cos($theta);
$tx_lat = $z * sin($theta);
return $tx_lat . "," . $tx_lon;
}
中奖概率换算
$proArr = array(
array('id'=>1,'name'=>'特等奖','v'=>1),
array('id'=>2,'name'=>'一等奖','v'=>222),
array('id'=>3,'name'=>'二等奖','v'=>333),
array('id'=>4,'name'=>'三等奖','v'=>4444),
array('id'=>5,'name'=>'谢谢惠顾','v'=>9999)
);
$res=$this->get_rand1($proArr);
/**
* 不同概率的抽奖原理就是把0到*(比重总数)的区间分块
* 分块的依据是物品占整个的比重,再根据随机数种子来产生0-* 中的某个数
* 判断这个数是落在哪个区间上,区间对应的就是抽到的那个物品。
* 随机数理论上是概率均等的,那么相应的区间所含数的多少就体现了抽奖物品概率的不同。
* @param $proArr
* @return array
*/
function get_rand1($proArr)
{
$result = array();
foreach ($proArr as $key => $val) {
$arr[$key] = $val['v'];
}
// 概率数组的总概率
$proSum = array_sum($arr);
asort($arr);
// 概率数组循环
foreach ($arr as $k => $v) {
$randNum = mt_rand(1, $proSum);
if ($randNum <= $v) {
$result = $proArr[$k];
break;
} else {
$proSum -= $v;
}
}
return $result;
}
判断时间是否在某个区域内
function get_curr_time_section()
{
$checkDayStr = date('Y-m-d ',time());
$timeBegin1 = strtotime($checkDayStr."09:00".":00");
$timeEnd1 = strtotime($checkDayStr."18:00".":00");
$curr_time = time();
if($curr_time >= $timeBegin1 && $curr_time <= $timeEnd1)
{
return 0;
}
return -1;
}
$result = get_curr_time_section();
echo $result;
去除Bom头
/**
* 去掉UTF-8 Bom头。
* Remove UTF-8 Bom.
*
* @param string $string
* @access public
* @return string
*/
public static function removeUTF8Bom($string)
{
if(substr($string, 0, 3) == pack('CCC', 239, 187, 191)) return substr($string, 3);
return $string;
}
获取近1年的所有月份
$z = date('Y-m');
$a = date('Y-m', strtotime('-12 months'));
$begin = new DateTime($a);
$end = new DateTime($z);
$end = $end->modify('+1 month');
$interval = new DateInterval('P1M');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
echo $date->format("Y-m") . "<br />";
}
获取两个时间戳的相差天数,小时,分钟,秒
/**
* 计算两个时间戳之间相差的日时分秒
* @param $begin_time 开始时间戳
* @param $end_time 结束时间戳
* @return array
*/
function timediff($begin_time,$end_time)
{
if($begin_time < $end_time){
$starttime = $begin_time;
$endtime = $end_time;
}else{
$starttime = $end_time;
$endtime = $begin_time;
}
//计算天数
$timediff = $endtime-$starttime;
$days = intval($timediff/86400);
//计算小时数
$remain = $timediff%86400;
$hours = intval($remain/3600);
//计算分钟数
$remain = $remain%3600;
$mins = intval($remain/60);
//计算秒数
$secs = $remain%60;
$res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
return $res;
}
判断是否手机浏览器
//判断是否是微信浏览器
function isWeixin() {
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
return true;
} else {
return false;
}
}
//判断是否是手机浏览器
function isMobile() {
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
return true;
}
// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
if (isset($_SERVER['HTTP_VIA'])) {
// 找不到为flase,否则为true
return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
}
// 脑残法,判断手机发送的客户端标志,兼容性有待提高。其中'MicroMessenger'是电脑微信
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$clientkeywords = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile','MicroMessenger');
// 从HTTP_USER_AGENT中查找手机浏览器的关键字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
return true;
}
}
// 协议法,因为有可能不准确,放到最后判断
if (isset ($_SERVER['HTTP_ACCEPT'])) {
// 如果只支持wml并且不支持html那一定是移动设备
// 如果支持wml和html但是wml在html之前则是移动设备
if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
return true;
}
}
// return true;
return false;
}
function isMobile2(){
$useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$useragent_commentsblock=preg_match('||',$useragent,$matches)>0?$matches[0]:'';
function CheckSubstrs($substrs,$text){
foreach($substrs as $substr){
if(false!==strpos($text,$substr)){
return true;
}else{
return false;
}
}
}
$mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
$mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');
$found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) || CheckSubstrs($mobile_token_list,$useragent);
if ($found_mobile){
return true;
}else{
return false;
}
}
设置脚本运行时间
ini_set('max_execution_time', '0');//永久
curl的get-post方式
/**
* post请求
* @param $url
* @param $postdata
* @return mixed
*/
function get_component($url,$postdata){
$ch = curl_init(); //用curl发送数据给api
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
$response = curl_exec($ch);
curl_close( $ch );
$rest = json_decode($response,true);
return $rest;
}
/**
* post请求 row形式
* @param $url
* @param $postdata
* @return mixed
*/
function post_row($url,$post_data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($post_data)
)
);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $response;
}
/**
* get请求
* @param $url
* @return mixed
*/
function curlget($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
$response = curl_exec($ch);
curl_close( $ch );
$rest = json_decode($response,true);
return $rest;
}
post请求json中文字符被转码
//强制不转码
json_encode($json,JSON_UNESCAPED_UNICODE)
Hmac加密
private function computeSignature($accessSecret, $canonicalString)
{
$s = hash_hmac('sha256', $canonicalString, $accessSecret, true);
return base64_encode($s);
}
获取区域网IP地址
$host_name = exec("hostname");
$host_ip = gethostbyname($host_name); //获取本机的局域网IP
echo $host_ip;
判断ip是否在允许范围内
/**
* 检查ip是否在允许范围
* @param $host_ip
* @return bool
*/
private function checkIP($host_ip){
$alip = '192.1.*.*';
$start_ip = $alip;
foreach ($alip as $ind=>$item) {
if($item=='*'){
$alip[$ind]=255;
$start_ip[$ind] = 1;
}
}
$end_id = implode('.', $alip);
$start_ip = implode('.', $start_ip);
$host_ip = bindec(decbin(ip2long($host_ip)));
$start_ip=bindec(decbin(ip2long($start_ip)));
$end_id=bindec(decbin(ip2long($end_id)));
if($start_ip<=$host_ip&&$host_ip<=$end_id){
return true;
}else{
return false;
}
}
文件下载
$fileName = ROOT_PATH.'/public/export/d58c42391a0cc5419a34c2a5eca19409abc904af954e0327561cbd1cee18ee20.html'; //得到文件名
header( "Content-Disposition: attachment; filename=".$fileName); //告诉浏览器通过附件形式来处理文件
header('Content-Length: ' . filesize($fileName)); //下载文件大小
readfile($fileName); //读取文件内容
get请求
function mcurl_get($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
post请求
function mcurl_post($url,$post_data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'mypost=' . $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "jb51.net's CURL Example beta");
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
图片合成
public function shareimg()
{
$id = $_POST['uid'];
//二维码图片
$qrodeimg = $this->getWxappQrCode($id);
//背景图片
$bannerimg = ROOT_PATH . '/public/wxcode/back_one.png';
//这是需要插入到背景图的图片url
// $qrodeimg = ROOT_PATH . '/public/wxcode/qrcode1.png';
//用户信息
//这是需要插入到背景图的图片url
// $head_img = $user['head_img'];
//这是要插入到图片的文字
// $tip1 = "长按小程序码可以查看我的名片,";
// $tip2 = "即可领取红包!";
// $text = $user['nickname'] . "发了一个口令红包";
if ($bannerimg) {
//生成中间带logo的二维码
//这是合成后的图片保存的路径
$upload_dir = "/public/wxcode/";
if (is_file($bannerimg)) {
//创建画布
$logo = imagecreatefromstring(file_get_contents($bannerimg));
$head_img1 = imagecreatefromstring(file_get_contents($qrodeimg));
// $head_img2 = imagecreatefromstring(file_get_contents($head_img));
//写入文字
// $msg = imagecolorallocate($logo, 255, 225, 177);
// $black = imagecolorallocate($logo, 255, 225, 177);
// $grey = imagecolorallocate($logo, 255, 225, 177);
//写的文字用到的字体
// $font = ROOT_PATH . '/statics/font/black_font.ttf';
//将$qrodeimg插入到$bannerimg里
imagecopyresampled($logo, $head_img1, 80, 80, 0, 0, 200, 200, imagesx($head_img1), imagesy($head_img1));
//将$head_img插入到$bannerimg里
// imagecopyresampled($logo, $head_img2, 400, 30, 0, 0, 100, 100, imagesx($head_img2), imagesy($head_img2));
//在图片里插入文字($msg,$black,$grey)
// imagettftext($logo, 24, 0, 280, 180, $msg,$font, $text);
// imagettftext($logo, 30, 0, 170, 280, $black,$font, $tip1);
// imagettftext($logo, 30, 0, 330, 340, $grey, $font, $tip2);
$rans = rand(100,900).time().'code'.'.png';
//生成图片
imagepng($logo, ROOT_PATH . $upload_dir . $rans);
//生成图片名字
// $twocode = $upload_dir . '97243655qrcode' . '.png'; //如果存在logo就生成带logo的
$twocode = $rans; //如果存在logo就生成带logo的
}
//返回结果图片url
throw new Success(['data' => 'http://'.$_SERVER['HTTP_HOST'].'/wxcode/'.$twocode]);
} else {
return false;
}
}
生成验证码
/**
* 验证码
*/
public function getCode($num = "4", $w = "80", $h = "26")
{
$str = Array(); //用来存储随机码
$vcode = "";
$string = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghjklpiuytrewq123456789";//随机挑选其中4个字符,也可以选择更多,注意循环的时候加上,宽度适当调整
for ($i = 0; $i < $num; $i++) {
$str[$i] = $string[rand(0, 35)];
$vcode .= $str[$i];
}
$this->set('verification', $vcode, 300);
$im = imagecreatetruecolor($w, $h);
$white = imagecolorallocate($im, 255, 255, 255); //第一次调用设置背景色
$black = imagecolorallocate($im, 0, 0, 0); //边框颜色
imagefilledrectangle($im, 0, 0, $w, $h, $white); //画一矩形填充
imagerectangle($im, 0, 0, $w - 1, $h - 1, $black); //画一矩形框
//生成雪花背景
for ($i = 1; $i < 200; $i++) {
$x = mt_rand(1, $w - 9);
$y = mt_rand(1, $h - 9);
$color = imagecolorallocate($im, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
imagechar($im, 1, $x, $y, "*", $color);
}
//将验证码写入图案
for ($i = 0; $i < count($str); $i++) {
$x = 13 + $i * ($w - 15) / 4;
$y = mt_rand(3, $h / 3);
$color = imagecolorallocate($im, mt_rand(0, 225), mt_rand(0, 150), mt_rand(0, 225));
imagechar($im, 5, $x, $y, $str[$i], $color);
}
ob_clean();//原来的程序没有这一栏
header("Content-type:image/jpeg"); //以jpeg格式输出,注意上面不能输出任何字符,否则出错
imagejpeg($im);
imagedestroy($im);
}
多图上传保存
public function moreimgupload()
{
$htmlfilename = 'files';
$new_folder='../../../www/data/upload/';
$allow_ext = array('jpg', 'jpeg', 'png', 'gif');
$data = array();
for ($i=0;$i<count($_FILES[$htmlfilename]['tmp_name']);$i++)
{
// 创建文件夹
$floder = $new_folder . date('Ym');
if(!is_dir($floder)){
mkdir($floder);
}
$ext=explode('/', $_FILES[$htmlfilename]['type'][$i]);
$end_ext=$ext[1];//后缀
if(!in_array(strtolower($end_ext),$allow_ext)){
Response::success('','上传文件不在允许范围');
}
$filenam = '/web' . time() . '.' . $end_ext;//保存文件名字
$upfile=$floder.$filenam;//此处路径换成你的
if(move_uploaded_file($_FILES[$htmlfilename]['tmp_name'][$i],$upfile)){
$data[] = 'www/data/upload/'.date('Ym').$filenam;
}
}
Response::success($data);
}
excel导出
include_once '../../../lib/phpexcel/phpexcel.class.php';
$objPHPExcel = new \PHPExcel();
$objWriter =new \PHPExcel_Writer_Excel2007($objPHPExcel);
$objPHPExcel->createSheet();
$objPHPExcel->setactivesheetindex(5);
$objPHPExcel->getActiveSheet(5)->setCellValue('A1', '项目');
$objPHPExcel->getActiveSheet(5)->setCellValue('B1', '修复成功');
$objPHPExcel->getActiveSheet(5)->setCellValue('C1', '修复失败');
$objPHPExcel->getActiveSheet(5)->setTitle('汇总');
$objPHPExcel->getActiveSheet(5)->setCellValue('A2', '荔湾移动4G');
$objPHPExcel->getActiveSheet(5)->setCellValue('B2', $repair_data->yd4gs);
$objPHPExcel->getActiveSheet(5)->setCellValue('C2', $repair_data->yd4gf);
//导出
$path='../../../www/data/excelexport';
$filename = time() . '.xls';
$objWriter->save("$path/$filename");
$name = $filename;
$fileName = $path.'/' . $name; //得到文件名
header("Content-Disposition: attachment; filename=" . $fileName); //告诉浏览器通过附件形式来处理文件
header('Content-Length: ' . filesize($fileName)); //下载文件大小
readfile($fileName); //读取文件内容
excel导入
include_once '../../../lib/phpexcel/phpexcel.class.php';
$file = $_FILES['file'];
if ($file['error'] == 4) $this->error('请选择上传excel文件');
$file_types = explode ( ".", $file['name'] );
$excel_type = array('xls','csv','xlsx');
if (!in_array(strtolower(end($file_types)),$excel_type)){
$this->error("不是Excel文件,请重新上传");
}
//哪一行开始是实际数据
$start_index=2;
//设置获取excel对象
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');//配置成2003版本,因为office版本可以向下兼容
$objPHPExcel = $objReader->load($file['tmp_name'],$encode='utf-8');//$file 为解读的excel文件
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow()+$start_index; // 取得总行数
$success_item = $fail_item = 0;
for($j=$start_index;$j<=$highestRow;$j++)
{
$mt_number = $objPHPExcel->getActiveSheet()->getCell("G".$j)->getValue();//平台监控点编号
}
Response::success('成功条数:'.$success_item.',失败条数:'.$fail_item);
图片缩放
/**
* 缩放图片
* @param $filename 图片地址
* @param $per 缩放倍数 1.2 0.3
* @return string
*/
private function scaleImg($filename,$per){
$per_str=implode('_', explode('.', $per));
$new_file_name=__DIR__.'/xxx_scale_'.$per_str.'.png';
//如果图片大小大于1
if (getimagesize($filename) > 1) {
list($width, $height) = getimagesize($filename);
$n_w = $width * $per;
$n_h = $height * $per;
$new = imagecreatetruecolor($n_w, $n_h);
$img = imagecreatefromstring(file_get_contents($filename));
//copy部分图像并调整
imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
imagepng($new, $new_file_name);
imagedestroy($new);
imagedestroy($img);
}
return $new_file_name;
下载远程图片到本地
/**
* 下载远程图片保存到本地
* @access public
* @return array
* @params string $url 远程图片地址
* @params string $save_dir 需要保存的地址
* @params string $filename 保存文件名
*/
function download($url, $save_dir = './publicimgs/',$filename='')
{
if(trim($save_dir)=='')
$save_dir='./';
if(trim($filename)==''){//保存文件名
$allowExt = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
$ext=strrchr($url,'.');
if(!in_array($ext,$allowExt))
return array('file_name'=>'','save_path'=>'','error'=>3);
$filename=time().$ext;
}
if(0!==strrpos($save_dir,'/'))
$save_dir.='/';
//创建保存目录
if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true))
return array('file_name'=>'','save_path'=>'','error'=>5);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
$resource = fopen($save_dir . $filename, 'a');
fwrite($resource, $file);
fclose($resource);
unset($file,$url);
return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
}
解析url地址获得参数
$link='http://www.baidu.com?article_id=123';
//app内链接 返回article_id 和article_anew_id
function convertUrlQuery($query)
{
$queryParts = explode('&', $query);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
$arr =parse_url($link);
$q=convertUrlQuery($arr['query']);
$article_id = $q['article_id'] ?? 0;
下载视频
function downVideo($url,$filePath)
{
//初始化
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, CURLOPT_URL, $url);
//打开文件描述符
$fp = fopen ($filePath, 'w+');
curl_setopt($curl, CURLOPT_FILE, $fp);
//这个选项是意思是跳转,如果你访问的页面跳转到另一个页面,也会模拟访问。
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl,CURLOPT_TIMEOUT,50);
//执行命令
curl_exec($curl);
//关闭URL请求
curl_close($curl);
//关闭文件描述符
fclose($fp);
}
downVideo("http://public.geek-in.net/clouddisk/bSCrjZKXyR.mp4", $root_dir . 'cs.mp4');
curl分片下载大文件
//get请求获取body体
function curl_get_with_body($url, $range)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_HTTPHEADER => array(
"Range: bytes={$range}"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
return "cURL Error #:" . $err;
} else {
return $response;
}
}
//get请求
function curl_get_with_head($url, $header)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "HEAD",
CURLOPT_POSTFIELDS => "",
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2,
//CURLINFO_HEADER_OUT => TRUE, //获取请求头
CURLOPT_HEADER => true, //获取响应头
CURLOPT_NOBODY => true, //不需要响应正文
CURLOPT_HTTPHEADER => $header,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$responseHeader = explode("\r\n", $response);
$totalLength = $eTag = '';
foreach($responseHeader as $response) {
if($response){
//获取文件总长度
if(strpos($response, 'Content-Range:', 0) !== false) {
$totalLength = explode(':', $response);
$totalLength = array_pop($totalLength);
$totalLength = explode('/', $totalLength);
$totalLength = array_pop($totalLength);
}
//获取文件etag
if(strpos($response, 'ETag:', 0) !== false) {
$eTag = explode(':', $response);
$eTag = array_pop($eTag);
$eTag = trim(str_replace('"', '', $eTag));
}
}
}
if ($err) {
return "cURL Error #:" . $err;
} else {
return ['length' => $totalLength, 'etag' => $eTag];
}
}
function download_file($file_url,$file_path,$rname,$ext)
{
// $file = "http://public.geek-in.net/clouddisk/NYsrTpPRjz.mp4";
$range = "0-1";
$response = curl_get_with_head($file_url, array(
"Range: bytes={$range}"
));
$eTag = $response['etag'];
$length = $response['length'];
if(file_exists($file_path.$rname.'.'.$ext)) {
if (filesize($file_path . $rname . '.' . $ext) != $length) {//大小不一样重新下载
try {
unlink($file_path . $rname . '.' . $ext);
}catch (Exception $exception){
echo "删除文件失败:{$file_path}{$rname}.{$ext}" . PHP_EOL;
}
$chunkCount = 100;
$chunkCount = $length/10000000;
$step = ceil($length / $chunkCount);
echo 11111;
$fp=fopen("{$file_path}{$rname}.{$ext}", 'w+');
for($i=0;$i<$chunkCount;$i++) {
$start = $i * $step;
$end = (($i+1) * $step) -1;
if($end > $length) {
$end = $length;
}
$range = $start. '-'. $end;
$con = curl_get_with_body($file_url, $range);
// file_put_contents("{$file_path}{$rname}.{$ext}", $con, FILE_APPEND);
fwrite($fp, $con);
echo("总大小{$length},共计{$chunkCount}片,第{$i}片下载完成, range:". $range .PHP_EOL);
}
echo "下载完成,总大小:{$length},";
fclose($fp);
}
}
}
download_file("http://www.www.ss.mp4","D:\","cc","mp4")