Vjack7
12/4/2019 - 3:10 AM

php/laravel模块

php/laravel模块

处理url将含有http://2kdev.net去掉 截取字符串

用于处理上传的图片中含有http的字符串

function filter_url($sUrl)
{
    $iPosition = stripos($sUrl, '.net');
    if ($iPosition) {
        $sTidyUrl = substr($sUrl,stripos($sUrl, '.net')+4);
    } else {
        $sTidyUrl = $sUrl;
    }
    return $sTidyUrl;
}

利用php的Gb 处理图像 添加水印

//图片加水印$target_path 需要添加水印的图片的路径
//$target_path = public_path($destination) . '/' . $filename;
function add_water_mark($target_path)
{
    $water_path = public_path('/uploadfile/') . 'watermark.png';//水印图片路径
    $dst = imagecreatefromstring(file_get_contents($target_path));//创建图片的实例 也可以用imagecreatefromjpeg(路径即可)
    $src = imagecreatefromstring(file_get_contents($water_path));//创建图片的实例
    list($src_w, $src_h) = getimagesize($water_path);//获取水印图片的宽高
    //将水印图片复制到目标图片上,最后个参数50是设置透明度,这里实现半透明效果,两个20是控制水印坐标位置
    imagecopymerge($dst, $src, 20, 20, 0, 0, $src_w, $src_h, 100);
    //输出图片
    list($dst_w, $dst_h, $dst_type) = getimagesize($target_path);//PHP list函数
    switch ($dst_type) {
        case 1://GIF
            header('Content-Type: image/gif');
            imagegif($dst, $target_path);
            break;
        case 2://JPG
            header('Content-Type: image/jpeg');
            imagejpeg($dst, $target_path);//将生成的图片移动到指定位置
            break;
        case 3://PNG
            header('Content-Type: image/png');
            imagepng($dst, $target_path);
            break;
        default:
            break;
    }
    //释放内存
    imagedestroy($dst);
    imagedestroy($src);
}

解决json_encode会将中文进行Unicode编码的问题

function json_encode_ex($value)
    {
        if (version_compare(PHP_VERSION,'5.4.0','<'))
        {
            $str = json_encode($value);
            $str = preg_replace_callback(
                "#\\\u([0-9a-f]{4})#i",
                function($matchs)
                {
                    return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
                },
                $str
            );
            return $str;
        }
        else
        {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
    }

正则判断url

//验证url网址
 if (url) {
    //判断URL地址的正则表达式为:http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
    //下面的代码中应用了转义字符"\"输出一个字符"/"
    var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
    var objExp = new RegExp(Expression);
    if (objExp.test(url) != true) {
      $("#error_urlMsg").html('*网址格式不正确!请重新输入');
      return false;
    }
 }

闪存数据显示

@if(Session::has('error'))
    <p style="color: red;font-size: larger">{{Session::get('error')}}</p>
@elseif(Session::has('success'))
    <p style="color: green;font-size: larger">{{Session::get('success')}}</p>
@endif
{{--全局$errors变量--}}
@if (count($errors) > 0)
    <div class=" alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

后台图片上传,预览,出处肿瘤小程序BannerController

{{--blade中上传图片--}}
<div class="am-form-group">
    <label class="am-u-sm-2 am-form-label"><span style="color: red">*</span>上传图片:</label>
    <div class="am-u-sm-10">
        <div class="tpl-form-file-img">
            <img id="pictureShow" src="{{ old('img_banner') }}" alt="请上传图片" width="100px" height="100px" style="display:none">
        </div>
        <input  id="file" type="file" >
        <input  id="img_banner" name="img_banner" class="img_banner" type="hidden" value="{{old('img_banner')}}">
    </div>
    {{--错误提示,用于表单提交时,图片为空格式错误时的提示,这个$errors应该是全局变量吧--}}
    <div class="col-xs-offset-2 input-group">
        <small style="color: red" id='error_pathMsg'>{{$errors->first('img_banner')}}</small>
    </div>
</div>
{{--下面为提交时的代码--}}
function postBanner() {
            if (!check()) {
        //前台验证 步骤一
                return false;
            }
        //上传图片 步骤二
            postThumb('img_banner', 'banner', '');
        //flag用于判断有无 上传成功
            if ($('#flag').val() == 0) {
                return false;
            }
        //步骤三
            $('form').submit();
        }

{{--点击上传图片后预览和最后上传可以封装到一个js文件中--}}
<script type="text/javascript" src="{{ asset('assets/admin/adminjs/fileupload.js') }}"></script>
{{--下面为js的内容--}}
/**
 * Created by crr on 2019/3/5.
 * 需要
 * 上传的文件id 为 file
 * 展示图片的id 为 pictureShow
 * 错误提示的id 为 pictureShow
 * 适用新增和修改图片的预览
 * */
window.onload = function () {
    $('#file').on('change', function () {
        /*https://blog.csdn.net/zh123456zh789/article/details/78805178 讲解的很详细*/
        /*获取到上传的图片文件*/
        var file = $("#file")[0].files[0];
        /*lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索。*/
        extStart = file.name.lastIndexOf('.');
        /*js获取到文件的后缀名*/
        ext = file.name.substring(extStart, file.name.length).toUpperCase();
        if (ext !== '.PNG' && ext !== '.JPG' && ext !== '.JPEG' && ext !== '.GIF') {
            $("#error_pathMsg").html('*请上传正确格式的图片');
            $("#pictureShow").attr('src', '');
            return false;
        }
        var size = file.size / 1024;
        if (size > 10240) {
            $("#error_pathMsg").html('*图片大小不能超过10M');
            $("#pictureShow").attr('src', '');
            return false;
        }
        /*用jquery中的show方法*/
        $('#pictureShow').show();
        /*生成图片的url地址 用户预览*/
        var path = window.URL.createObjectURL(file);
        /*清除错误提示*/
        $("#error_pathMsg").html('');
        /*添加图片地址*/
        $("#pictureShow").attr('src', path);

    })
}

/*
 * 上传图片
 * crr
 * 参数1:图片的id。
 * 参数2:上传标志,此标志与后台存放图片位置有关。
 * 参数3:根据实际情况,若不需要,调用本方法可以传空字符串。
 * 上传成功后 提交表单
 */
function postThumb(picture, upload, type) {
    /*获取到上传的图片*/
    var file = $('#file')[0].files[0];//type = file
    var thumb = $("#" + picture).val();//type = hidden
    var imgSrc = $('#pictureShow').attr("src");
    /*即当前有图片,并且file为空即没有上传新图片*/
    if (thumb && !file) { //编辑图片时,若图片未做修改,直接返回,不再执行以下上传过程。
        $('#flag').val(1);
        return;
    }
    if (!file) {
        $("#error_pathMsg").html('*请上传图片');
        return false;
    }
    if (!imgSrc) {
        $("#error_pathMsg").html('*请上传正确格式的图片');
        return false;
    }
    /*以formData来进行传输表单数据*/
    var formData = new FormData;
    formData.append('file', file);
    formData.append('type', type);
    formData.append('upload', upload);
    formData.append('_token', $("#_token").val());
    $.ajax({
        url: '/admin/upload',
        type: 'post',
        data: formData,
        dataType: 'json',
        processData: false,
        contentType: false,
        async: false,
        success: function (res) {
            $("#" + picture).val(res.url)
            $('#flag').val(1)
        },
        error: function () {
            $("#flag").val(0)
        }
    })
}
{{--后台处理上传的图片,注意并不是提交的表单 只是在步骤二--}}
/* 图片上传 */
    public function upload(Request $request)
    {
        $upload = $request->input('upload');//图片存储地址
        $type = $request->input('type');
        $destination = '/uploadfile/' . $upload;//最前面有一个/
        $file = $request->file('file');
        if (!$file) return response()->json(['success' => 0, 'msg' => '请上传文件']);//ajax返回
        if (!$file->isValid())
            return response()->json(['success' => 0, 'msg' => $file->getErrorMessage()]);

        $filename = uniqid() . '.' . $file->getClientOriginalExtension();//生成一个unionid,获取原后缀名
        $file->move(public_path($destination), $filename);//移动图片
        return response()->json([
            'success' => true,
            'url' => $destination . '/' . $filename,
            'status' => $type
        ]);
    }

手动创建验证器

{{--处理表单数据--}}
use Validator

public function store(Request $request)
    {
        //去除掉数组中的一个
        $aBanner = array_except($request->all(), 'all_show_num');
        $rules = array(
            'img_banner' => 'required',
            'module' => 'required',
            'theme' => 'required',
            'method' => 'required',
            'creat_time' => 'required',
            'status' => 'required'
        );
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->passes()) {
            if (Banner::create($aBanner)) {
                return redirect('admin/banner')->with('success', '添加成功');
            } else {
                return redirect('admin/banner')->with('error', '添加失败');
            }
        } else {
            return redirect('admin/banner')->with('error', '请填写全部数据,添加失败');
        }
    }

比较好的日期选择器

官网

<div class="am-input-group am-input-group-sm tpl-form-border-form cl-p">
                                    <input type="text" class="am-form-field" id="creat_time"
                                           name="creat_time" autocomplete="off"
                                           placeholder="请输入创建日期">
</div>
<script type="text/javascript" src="{{asset('assets/admin/laydate/laydate.js')}}"></script>
 <script>
        laydate.render({
            elem: '#creat_time'
        });
</script>

过滤表情

/*
* 过滤表情 用于处理用户昵称
*/
function filterEmoji($str)
{
    $str = preg_replace_callback('/./u',
    function (array $match) {
    return strlen($match[0]) >= 4 ? '' : $match[0];
    },
    $str);
return $str;
}

判断url中是否包含?若包含返回&,不包含返回?

/*
* 用于判断并拼接url,用点来拼接
* $sUrl . $sSymbol . 'openid='
*/
function url_symbol($sUrl)
{
    $sSymbol = '?';
    if (strpos($sUrl, '?') !== false) {
        $sSymbol = '&';
    }
    return $sSymbol;
}
或
$sSymbol = strpos($sUrl, '?') !== false ? '&' : '?';

Excel上传和处理

{{--流程:点击上传->前台弹出提示内容->利用jquery插件ajaxFileUpload上传Excel文件,这一步后台判断类型并且将上传的Excel文件路径存储到数据库 
(需要引入js文件并且需要在jquery下方引入)->在用ajax的post请求处理Excel--}} 
<div class="am-btn-group am-btn-group-xs">
    <input type="hidden" name="_token" id="_token" value="{{ csrf_token() }}">
    <button type="button" class="am-btn am-btn-default am-btn-success" onclick="upload_file_prompt();" style="margin-left: 30px;display:inline-block">
        <span class="am-icon-plus"></span>批量导入
    </button>
    <input type="file" name="upload_but" id="upload_but" style="display: none" onchange="check_upload_excel(this.id)"/>
</div>

{{--js引用可以统一写在_head.blade.php中--}}
<script src="{{asset('assets/admin/js/jquery.min.js')}}"></script>
{{--文件上传 必须在jquery引用的下方--}}
<script src="{{asset('assets/admin/js/ajaxfileupload.js')}}"></script>
<script>
        function upload_file_prompt()
        {
            swal({
                    title: "上传说明",
                    text: "支持格式:xls、xlsx格式,请下载<a href='/uploadfile/activeuser/activeuser.xlsx'>导入</a>文件" +
                    ",将数据粘贴到对应列,粘贴时鼠标右键选择粘贴值(避免存在公式),导入该文件即可!",
                    html: true,
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#4db14d",
                    confirmButtonText: "Yes, upload it!",
                    closeOnConfirm: true
                },
                function(){
                    $('#upload_but').click();
                });
        }
        function check_upload_excel(fileid)
        {
            swal({'title' : "文件上传中, 请耐心等待~", showConfirmButton: false });
            $.ajaxFileUpload({
                url: '/admin/upload-excel',//用于文件上传的服务器端请求地址
                secureuri: false,//是否需要安全协议,一般设置为false
                fileElementId: fileid,//文件上传域的id <input type="file" id="file" name="file" />
                data: {
                    _token: $('#_token').val(),
                    'fileid': fileid
                },
                dataType: 'json',
                type: 'post',
                success: function (result) {
                    if (result.success) {
                        swal({'title': "文件上传成功,正在处理数据,请勿关闭网页或刷新!", showConfirmButton: false});
                        var data = {
                            fileid: result.id,
                            _token: $('#_token').val(),
                        };
                        $.post('/admin/save-data', data, function (res) {
                            if (res.success) {
                                swal({
                                        title: res.msg,
                                        text: "3秒后自动刷新",
                                        timer: 3000,
                                        showConfirmButton: false
                                    },
                                    function () {
                                        window.location.reload();
                                    });
                            }
                        }, 'json');
                    }
                }
            })
        }
    </script>
{{--后台处理--}}
use Maatwebsite\Excel\Facades\Excel; 
//引入Excel处理 需要 
- 在compser.json文件中引入"maatwebsite/excel": "^2.1"并进行composer update 
- 在config/app.php的provider中加入Maatwebsite\Excel\ExcelServiceProvider::class 
- 在aliases中加入 'Excel' => Maatwebsite\Excel\Facades\Excel::class
/*进行文件的移动和入库并将入库的id返回*/
public function postUploadfile(Request $request)
{
    if ('POST' === $request->method('POST')) {
        $oFile = $request->file($request->input('fileid'));
        //检验一下上传的文件是否有效
        if ($oFile->isValid()) {
            //缓存在tmp文件夹中的文件名,如php4FAF.tmp
            //$sTmpName = $oFile->getFileName();
            //缓存在tmp文件夹的文件的绝对路径,如 -F:\wamp\tmp\php4FAF.tmp
            //$sRealPath = $oFile->getRealPath();
            //校验文件类型
            $sMimeType = $oFile->getMimeType();
            if ($sMimeType != "application/vnd.ms-excel"
                &&
                $sMimeType != "application/vnd.ms-office"
                &&
                $sMimeType != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                && ! starts_with($sMimeType, 'image/')
            ) {
                echo json_encode(array('success'=>false, 'msg'=>"格式错误"));
                exit;
            }
            //上传的原始文件名称
            $sClientName = $oFile->getClientOriginalName();
            //校验文件大小
            $iFileSize = $oFile->getSize();
            $iMinSetSize = min(intval(ini_get('upload_max_filesize')), intval(ini_get('post_max_size')));
            if ($iFileSize > ($iMinSetSize * 1024 * 1024)) {
                echo json_encode(array('success'=>false, 'msg'=>'文件过大,需小于' . $iMinSetSize .'兆'));
                exit;
            }
            //上传文件后缀
            $sEntension = $oFile->getClientOriginalExtension();
            //上传文件路径
            $sPublicPath = public_path();
            $sUploadPath = '/uploadfile/' . $sEntension;
            $sFullPath = $sPublicPath . $sUploadPath;
            $this->mkdir_upload($sFullPath);
            $sFileName = $sEntension.date('Ymdhis') .'.' .$sEntension;
            //移动文件,返回文件绝对路径
            $sRealFile = $oFile->move($sFullPath, $sFileName);
            //excel处理文件格式
            $sExcelFile = 'uploadfile/' . $sEntension . '/' . $sFileName;
            //上传成功,返回相对路径
            if (file_exists($sRealFile)) {
                if ($sEntension == 'xls' || $sEntension == 'xlsx') {
                    $oExcel = ActiveUserExcel::firstOrCreate(['original_file' => $sClientName, 'new_path' => $sUploadPath . '/' . $sFileName]);
                    echo json_encode(array('success'=>true, 'datalist'=>$sEntension, 'id'=>$oExcel->id));
                    exit;
                } else {
                    echo json_encode(array('success'=>false, 'msg'=>"上传失败,请检查文件格式"));
                    exit;
                }
            } else {
                echo json_encode(array('success'=>false, 'msg'=>"上传失败"));
                exit;
            }
        } else {
            echo json_encode(array('success'=>false, 'msg'=>"上传失败"));
            exit;
        }
    }
}
public function postSavedata(Request $request)
    {
        set_time_limit(0);
        $iFileId = intval($request->input('fileid'));
        $oExcleFile = ExcelModel::where('id', $iFileId)->first();
        if (is_null($oExcleFile)) {
            echo $this->errorRet('该文件已不存在!');
            exit;
        }
        //load接收格式, uploadfile/xlsx/xlsx20180314082254.xlsx
        Excel::load(substr($oExcleFile->newfile, 1), function($reader) use ($oExcleFile) {
            //excel第一个sheet
            $reader = $reader->getSheet(0);
            $results = $reader->toArray();
            //去除标题
            unset($results[0]);
            //处理数据
            foreach ($results as $key => $result) {
                if ( $result[0] ) {
                    //array_walk($result, 'submit_filter');
                    $videoModel = new Video();
                    $videoModel->show_time = $result[0];
                    $videoModel->time = $result[1];
                    $videoModel->author = $result[2];
                    $videoModel->title = $result[3];
                    $videoModel->meeting_id = $result[4];
                    $videoModel->url = $result[5];
                    $videoModel->save();
                }
            }
        });
        echo $this->successRet('上传成功!');
    }
  • 这样用save处理插入有时候会慢,可以改为insert,但insert的字符串可能会很大,可能要改下数据表中的字段大小
public function postSavedata(Request $request)
    {
        set_time_limit(0);//表示持续运行到程序结束
        $iFileId = intval($request->input('fileid'));
        info($iFileId);
        $oExcleFile = ExcelModel::where('id', $iFileId)->first();
        if (is_null($oExcleFile)) {
            echo $this->errorRet('该文件已不存在!');
            exit;
        }
        //load接收格式, uploadfile/xlsx/xlsx20180314082254.xlsx
        Excel::load(substr($oExcleFile->newfile, 1), function($reader) use ($oExcleFile) {
            //excel第一个sheet
            $reader = $reader->getSheet(0);
            $results = $reader->toArray();
            //去除标题
            unset($results[0]);
            $aInsert = [];
            //处理数据
            foreach ($results as $key => $result) {
            //$key是从1开始的
                if ( $result[0] ) {
                    if (strtotime($result[2])>strtotime('2018-10-14')) {
                        $aInsert[$key - 1]['type'] = 2;
                    } else {
                        $aInsert[$key - 1]['type'] = 1;
                    }
                    $aInsert[$key - 1]['show_time'] = $result[2];
                    $aInsert[$key - 1]['time'] = $result[3];
                    $aInsert[$key - 1]['author'] = $result[1];
                    $aInsert[$key - 1]['title'] = $result[6];
                    $aInsert[$key - 1]['meeting_id'] = Meeting::where('type', 2)->where('name', trim($result[7]))->pluck('id');
                    $aInsert[$key - 1]['url']  = trim($result[9]);
                }
            }
            //注:insert并不会维护created_at和updated_at字段,所以如果有需要需手动添加date('Y-m-d H:i:s', time());
            DB::table('video')->insert($aInsert);
        });
        echo $this->successRet('上传成功!');
    }