分类 php 下的文章

//前台HomeController.php在function jizhi_details($id){}中使用
if(array_key_exists('attchment',$details)){
     $details['attchment']= ffix($details['attchment']) ;
}

//详情页单附件数据修正,函数加到conf/FunctionsExt.php
function ffix($url){
    if($url){
        $fres = M('pictures')->find(['litpic'=> $url]);
        $attchment=[];
        if($fres){
          $attchment['fid'] = $fres['id'];
          $attchment['url'] = $fres['litpic'];
          $attchment['ftype'] = $fres['filetype'];
          $attchment['ftime'] = date('Y-m-d',$fres['addtime']);
          $attchment['fsize'] =usize($fres['size']);
         }else{
         $attchment['fid'] = 0;  
        }
    }else{
       $attchment['fid'] = 0;     
    }
    return $attchment;
}

//详情页使用附件字段信息
{$jz['attchment']['fid']}
{$jz['attchment']['litpic']}

//放入以下函数到conf/FunctionsExt.php
function fileFix($str){
    if($str){
    $segments = explode('||', $str);
    $result = [];
    foreach ($segments as $segment) {
        $segment = trim($segment);
        if (empty($segment)) continue;
        $parts = explode('|', $segment, 2);
        if (count($parts) === 2) {
            $url = trim($parts[0]);
            $title = trim($parts[1]);
            $result[] = [
                'title' => $title,
                'url'   => $url,
            ];
        }
    }
    return $result;
   }else{
     return [];  
   }
}
 //前台使用
 {if($jz['files'])}
    <ul>
       {php $files = fileFix($jz['files']) /}
         {foreach $files as $v}
        <li>
            <img src="{$v['url']}" alt="{$v['title']}" loading="lazy">
            <p>{$v['title']}</p>
        </li>
        {/foreach}
    
    </ul>
 {/if}

1.放入以下函数到conf/FunctionsExt.php
//修正多附件字段
    function fixFile($data){
           if($data){
                $inputStr = $data;
                $segments = explode('||', $inputStr);
                $segments = array_filter($segments, function($item) {
                    return trim($item) !== '';
                });
                //提取标题和顺序
                $pathToTitle = [];  
                $pathOrderMap = [];  
                $order = 1;
                foreach ($segments as $segment) {
                    if (empty(trim($segment))) continue;
                    $parts = explode('|', $segment, 2); 
                    if (count($parts) === 2) {
                        $path = trim($parts[0]);
                        $title = trim($parts[1]);
                        $pathToTitle[$path] = $title;
                        $pathOrderMap[$path] = $order++;
                    }
                }
                
     
                //获取url字符串
                $quotedUrls = [];
                foreach ($segments as $item) {
                    $parts = explode('|', $item, 2); 
                    $url = trim($parts[0] ?? '');
                    if (!empty($url)) {
                        $quotedUrls[] = '"' . $url . '"';
                    }
                }
                
                $orders = 'addtime desc';
                $sql = ' litpic in ('.implode(',',$quotedUrls).') ';
                $fres = M('pictures')->findAll($sql,$orders);
                
                foreach($fres as $k=>$v){
                     $url = $fres[$k]['litpic'];
                     $fres[$k]['title'] = $pathToTitle[$url]; 
                     $fres[$k]['orders'] = $pathOrderMap[$url];
                }
                usort($fres, function($a, $b) {
                    return $a['orders'] - $b['orders'];
                });
               return $fres;
             }else{
                 return [];  
             }   
    }
2.前台HomeController.php在function jizhi_details($id){}中使用
//重构附件files字段

    if(array_key_exists('files',$details)){
        $this->files = fixFile($details['files']);
    }
3.在前台Common控制器添加下载处理函数
    function download() {
        if($_POST){
            $id = $this->frparam('fid',1,'POST');
            $file_name =$this->frparam('file_name',1,'POST');
            if(!$id||!$file_name){
               http_response_code(405);
               //echo "错误:参数缺失";
               exit; 
            }
            if (!preg_match('/^[\w\x{4e00}-\x{9fa5}\-]+$/u', $file_name)) {
            http_response_code(405);
            //echo "错误:文件名包含非法字符";
            exit;
           }
            $fres = M('pictures')->find(['id'=> $id]);
            if($fres){
                $file_url = $fres['litpic'];
                $now =date('Ymd_His', time());
                $download_name = $file_name.$now. '.' . $fres['filetype'];
                if (file_exists(APP_PATH.$file_url) && is_file(APP_PATH.$file_url)) {
                    $fileSize = filesize(APP_PATH.$file_url);
                            header('Content-Description: File Transfer');
                            header('Content-Type: application/octet-stream');
                            header('Content-Disposition: attachment; filename="' . basename($download_name) . '"');
                            header('Expires: 0');
                            header('Cache-Control: must-revalidate');
                            header('Pragma: public');
                            header('Content-Length: ' . $fileSize);
                    readfile(APP_PATH.$file_url);
                    exit;
                }else{
                    http_response_code(404); 
                    //echo "错误:文件不存在。";
                    exit; 
                }
                
            }else{
              http_response_code(404);  
              //echo "错误:文件不存在。";
              exit;    
            }
         
        }else{
          http_response_code(405);  
          exit;
        }
    } 

4.前端详情页模板使用
    {foreach $rjfile as $v}
        <li>
          {$v['id']}
          {$v['title']}
          {$v['filetype']}
          {$v['size']}
          {fun date('Y-m-d',$v['addtime'])}
         <a href="javascript:;" class="downf" fid="{$v['id']}" fname="{$v['title']}">下载</a>
        </li>
    {/foreach}
5.结合js实现文件下载
<script type="text/javascript">
 function download(id,filename){
  $('body').append(`<form method="post" target="_blank" action="/common/download.html" id="downloadForm"><input type="hidden" name="fid" value="${id}" required><input type="hidden"  name="file_name" value="${filename}" required></form>`);
  setTimeout(function(){
    $("#downloadForm").submit();
    setTimeout(function(){
        $("#downloadForm").remove()
        
    },1000)
  },500)
}
$(function(){
    $(".downf").each(function(){
        $(this).click(function(){
            var fid = $(this).attr("fid");
            var fname = $(this).attr("fname");
           download(fid,fname) 
        })
    })
    
})
</script>

目的是在不暴露后台附件地址情况下前台利用附件id从pictures表里查询附件地址执行下载;
1.首先给模型添加单附件字段attachment
2.找到前台控制器HomeController.php里面栏目处理器函数function jizhi(){}里面的循环输出url的地方,加上处理附件信息

foreach($data as $k=>$v){
    if(!isset($v['url'])){
        $data[$k]['url'] = gourl($v,$v['htmlurl']);
    }
    //返回附件信息s
    if(!isset($v['fid'])){
        if(isset($v['attachment'])){
        $fres = M('pictures')->find(['litpic'=> $data[$k]['attachment']]);
        if($fres){
          $data[$k]['fid'] = $fres['id'];
          $data[$k]['ftype'] = $fres['filetype'];
          $data[$k]['ftime'] = date('Y-m-d',$fres['addtime']);
          $data[$k]['fsize'] =usize($fres['size']);
        }else{
          $data[$k]['fid'] = 0;  
        }
        }else{
          $data[$k]['fid'] = 0;     
        }
           
    }
    //返回附件信息e
}

3.在前台控制器添加下载处理函数

function download() {
    if($_POST){
        $id = $this->frparam('fid',1,'POST');
        $file_name =$this->frparam('file_name',1,'POST');
        if(!$id||!$file_name){
           http_response_code(405);
           //echo "错误:参数缺失";
           exit; 
        }
        if (!preg_match('/^[\w\x{4e00}-\x{9fa5}\-]+$/u', $file_name)) {
        http_response_code(405);
        //echo "错误:文件名包含非法字符";
        exit;
       }
        $fres = M('pictures')->find(['id'=> $id]);
        if($fres){
            $file_url = $fres['litpic'];
            $now =date('Ymd_His', time());
            $download_name = $file_name.$now. '.' . $fres['filetype'];
            if (file_exists(APP_PATH.$file_url) && is_file(APP_PATH.$file_url)) {
                $fileSize = filesize(APP_PATH.$file_url);
                        header('Content-Description: File Transfer');
                        header('Content-Type: application/octet-stream');
                        header('Content-Disposition: attachment; filename="' . basename($download_name) . '"');
                        header('Expires: 0');
                        header('Cache-Control: must-revalidate');
                        header('Pragma: public');
                        header('Content-Length: ' . $fileSize);
                readfile(APP_PATH.$file_url);
                exit;
            }else{
                http_response_code(404); 
                //echo "错误:文件不存在。";
                exit; 
            }
            
        }else{
          http_response_code(404);  
          //echo "错误:文件不存在。";
          exit;    
        }
     
    }else{
      http_response_code(405);  
      exit;
    }
} 

 // 获取access_token
    private function getAccessToken($url, $header)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        return curl_exec($curl);
    } 
  // 微信授权登录
 function wxAuthLogin()
    {
       // $param = $this->request->param();
        $code = $this->frparam('code',1,'','POST');
        $appid = 'appid';
        $secret = 'appSecrect';
        $url = "https://api.weixin.qq.com/cgi-bin/token?appid=$appid&secret=$secret&grant_type=client_credential";
        try {
            $header = array('Accept: application/json',);
            // 获取access_token
            $wx_access_token = json_decode($this->getAccessToken($url, $header), true);
 
            $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $wx_access_token['access_token'];
            $data = array('code' => $code); // 请确保$code变量已经定义
            $options = array(
                'http' => array(
                    'header' => "Content-Type: application/json\r\n",
                    'method' => 'POST',
                    'content' => json_encode($data)
                )
            );
            $context = stream_context_create($options);
            $response = file_get_contents($url, false, $context);
            $result = json_decode($response, true);
            if ($result['errcode'] != 0) {
                JsonReturn(["code" => 1, "msg" => '登录失败']);
            }else{
               $tel = $result['phone_info']['phoneNumber'];
               $m = M('member')->find(['tel'=>$w['tel']]);
              if($m){
                  //走登录流程
                  $update['logintime'] = time();
                   M('member')->update(array('id'=>$m['id']),$update);
                   
                   $payload = [
                        'userId' => $m['id'], 
                        'exp' => time() + 60,     // 1小时后过期
                        'tel' => $tel          // 自定义数据
                        ];
                   $userInfo['name']=$m['username'];
                   $userInfo['id']=$m['id'];
                   $userInfo['litpic']=$m['litpic'];
                   $token =TokenManager::generateToken($payload);
                  
                   JsonReturn(['code'=>0,'msg'=>'登录成功!','token'=>$token,userInfo=>$userInfo]);
               }else{
                   //新增用户
                     //$w['username'] = getRandChar(6);
                     $w['username'] = '微信用户';
                    $w['tel'] = $tel;
                    $w['gid'] = 1;
                    $w['litpic'] = 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132';
                    $w['regtime']=time();
                    $r = M('member')->add($w);  
                    if($r){
                        //走登录流程
                       $payload = [
                            'userId' => $r['id'], 
                            'exp' => time() + 60,     // 1小时后过期
                            'tel' => $tel          // 自定义数据
                            ];
                       $userInfo['name']=$w['username'];
                       $userInfo['id']=$r['id'];
                       $userInfo['litpic']=$w['litpic'];
                       $token =TokenManager::generateToken($payload);
                       JsonReturn(['code'=>0,'msg'=>'登录成功!','token'=>$token,userInfo=>$userInfo]); 
                            
                        
                    }
               }

              
            }
           

        } catch (Exception $exception) {
            return json(["code" => 0, "msg" => $exception->getMessage()]);
        }
    }