标签 php 下的文章

ThinkPHP实现微信分享好友转发朋友圈自定义图片和文字的方法,在开始之前呢,我们需要准备好一些东西:

前期准备

  • 认证的公众号,订阅号或者服务号都可以,只要是认证过的就可以。
  • 公众号的AppID和AppSecret,登录微信公众平台,开发—基本配置,就可以看到啦。
  • 设置JSJS接口安全域名,登录微信公众平台,设置—公众号设置—功能设置里,填写就可以了。
  • 官方SDK,我们直接下载案例就可以,下载地址:http://demo.open.weixin.qq.com/jssdk/sample.zip里面包含php、java、nodejs以及python的示例代码。

服务端准备(ThinkPHP)

  • 将刚刚下载的jssdk.php文件重命名为Jssdk.php,然后和access_token.php、jsapi_ticket.php一起放入到ThinkPHP框架的第三方接口扩展目录下(extend/org/wechat/)。
  • 修改Jssdk.php文件

    1. 首先我们需要在构造函数中设置 $this->path = __DIR__ . DS; 即:

      namespace wechat;
      class Jssdk  {
       private $appId;
       private $appSecret;
       private $path;
       public function __construct($appId, $appSecret) {
       $this->appId = $appId;
       $this->appSecret = $appSecret;
       $this->path = __DIR__ . DS;
       }
       ...
      }
    2. get_php_file函数返回值中的$filename改为 $this->path.$filename ,即:

      private function get_php_file($filename) {
        return trim(substr(file_get_contents($this->path.$filename), 15));
      }
    3. 设置token的缓存,修改getAccessToken,加入cache

      private function getAccessToken() {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        // cache('at', ['access_token'=>'sss', 'expire_time' => '123']);
        // $data = json_decode($this->get_php_file("access_token.php"));
        $data = cache('at');
        if ($data['expire_time'] < time()) {
       // 如果是企业号用以下URL获取access_token
       // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
       $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
       $res = json_decode($this->httpGet($url));
       $access_token = $res->access_token;
       if ($access_token) {
         // $data->expire_time = time() + 7000;
         // $data->access_token = $access_token;
         cache('at', ['access_token'=>$access_token, 'expire_time' => time() + 7000]);
         // $this->set_php_file("access_token.php", json_encode($data));
       }
        } else {
       $access_token = $data['access_token'];
        }
        return $access_token;
      }
  • 在控制器里面调用

    1. 导入jssdk, use wechat\Jssdk;
    2. 传给前端

      $jssdk = new Jssdk($AppID, $AppSecret);
      $res = $jssdk->getSignPackage();
      $appId = $res['appId'];
      $timestamp = $res['timestamp'];
      $nonceStr = $res['nonceStr'];
      $signature = $res['signature'];
      $this->assign(
       array(
           'appId'=>$appId,
           'timestamp'=>$timestamp,
           'nonceStr'=>$nonceStr,
           'signature'=>$signature,
       )
      );

      网页端

  • 导入jssdk

    <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    
  • 设置分享内容

    <script type="text/javascript">
      var title = '分享标题';
      var imgUrl = '分享图片';
      var link = '分享地址';
      var desc = '分享描述';
     
      wx.config({
          debug: false,//开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
          appId: '{$appId}', // 必填,公众号的唯一标识
          timestamp: '{$timestamp}', // 必填,生成签名的时间戳
          nonceStr: '{$nonceStr}', //必填, 生成签名的随机串
          signature: '{$signature}', //必填,签名
          jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone'] //必填, JS接口列表,这里只填写了分享需要的接口
      })
      wx.ready(function () {
          wx.onMenuShareTimeline({
              title: title,
              link: link,
              desc:desc,
              imgUrl: imgUrl,
              success: function() {
                  // 用户确认分享后执行的回调函数
              },
              cancel: function() {
                  // 用户取消分享后执行的回调函数
              }
          });
          wx.onMenuShareAppMessage({
              title: title, // 分享标题
              desc: desc, // 分享描述
              link: link, // 分享链接
              imgUrl: imgUrl, // 分享图标
              type: 'link', // 分享类型,music、video或link,不填默认为link
              dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
              success: function() {
                  // 用户确认分享后执行的回调函数
              },
              cancel: function() {
                  // 用户取消分享后执行的回调函数
              }
          });
      })
    </script>

小编今天在使用MxSrvs运行thinPHP项目的时候,直接把项目目录直接放在了网站根目录里面,发现默认控制器的访问是没有问题的,但是其他的控制器以及直接输入默认的控制器全部显示的事404。后来发现其实是需要配置下的,而且也可以不放在网站根目录里面。
首先点击左侧的配置编辑--》再点击Nginx--》再点击最后一行的加号
1.png

然后就会弹出一个框,然后注入域名,项目名,项目目录就可以了。
2.png

这时候就会生成一个配置文件,然后在配置文件里面加入以下内容(是新弹出来的配置文件里面)

    location /
    {
        index index.php;
        #ThinkPHP REWRITE支持
        if (!-e $request_filename) {
            rewrite ^/(.*)$ /index.php?s=$1 last;
            break;
        }
    }

完整的就是

server {
    listen            80;
    server_name        devapi.sunxiaoning.com;
    root            /; # 自己的项目的位置
    #access_log        /; # 自己项目日志的位置
    include            vhosts/_nginx.vhost.fpm;
    location /
    {
        index index.php;
        #ThinkPHP REWRITE支持
        if (!-e $request_filename) {
            rewrite ^/(.*)$ /index.php?s=$1 last;
                        # rewrite ^/index.php/(.*)$ /index.php?s=$1 last; # 域名后面有index.php
            break;
        }
    }
}

然后在nginx的配置文件里面的PHP里面加入:

location ~ \.php$ {
            root           /Applications/MxSrvs/www;
            fastcgi_pass   127.0.0.1:10080;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_split_path_info ^(.+\.php)(.*)$;     #增加这一句  
            fastcgi_param PATH_INFO $fastcgi_path_info;    #增加这一句
            include        fastcgi_params;
        }

对于熟悉SEO的小伙伴都很清楚,静态网站的收录以及排名都比较好使。我们使用PHP开发网站的时候一般都使用的是伪静态,有些开源的程序都基本上可以开启伪静态,那么我们自己写的呢,怎么实现呢,小编今天在这里总结下TP3.2实现伪静态。

首先在使用大U方法进行传参的时候不要直接{:U('test')}?id=1这么写,我们要按照手册里面的写法去书写{:U('test',array('id'=>1))},这时候你就会发现直接是.html结尾了。

接下来我们要去除的是index.php

首先我们在网站的根目录里面新建.htaccess这个文件,记得前面有个点哦。然后填上以下内容。

<IfModule mod_rewrite.c>
  Options +FollowSymlinks
  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>

再然后我们打开项目的配置文件把URL_MODEL 改为 2,也就是 'URL_MODEL'=>'2'

最后我们就完美实现了。

利用PHP对文件进行下载:

  public function download(){
       $file = './public/Uploads/fileuri';   //下载文件存放目录  
       if (file_exists($file)) {
           header('Content-Description: File Transfer');
           header('Content-Type: application/octet-stream');
           header('Content-Disposition: attachment; filename="'.basename($file).'"');
           header('Expires: 0');
           header('Cache-Control: must-revalidate');
           header('Pragma: public');
           header('Content-Length: ' . filesize($file));
           readfile($file);
           exit;
       }else{
           echo "文件不存在";
       }

   }

获取当前时间戳

time();

时间戳转换成时间

date(format,timestamp)

参数:
format 必需。规定时间戳的格式。
timestamp 可选。规定时间戳。默认是当前时间和日期。
timestamp的参数

  • Y :年(四位数)
  • m : 月(两位数,首位不足补0)
  • d :日(两位数,首位不足补0)
  • H:小时,带有首位零的 24 小时小时格式
  • h :小时,带有首位零的 12 小时小时格式
  • i :带有首位零的分钟
  • s :带有首位零的秒(00 -59)
  • a:小写的午前和午后(am 或 pm)

日期转时间戳

strtotime

获取带有毫秒的时间戳

PHP默认是不带有直接获取带有毫秒的时间戳的,我们只能转换成粗略的带有毫秒的时间戳。

 function getMillisecond(){
        list($s1,$s2)=explode(' ',microtime());
        return (float)sprintf('%.0f',(floatval($s1)+floatval($s2))*1000);
    }

一个条件的时候,可以直接运用以下方法:

$map['miaoshu'] =array('like','%'.$sp.'%');
$result=M('shangpin')->where($map)->select();

多个查询条件的时候,

$map['spname | miaoshu'] =array('like','%'.$sp.'%');
$result=M('shangpin')->where($map)->select();

wphp中上传文件并保存的时候,在html表单中需要设置enctype="multipart/form-data",并且只能post方式 PHP接收文件可以通过$_FILES来获取。文件上传到服务器之后就会生成一个临时文件.tmp.tmp文件一会就被自动删除。服务器返回的内容中,有文件的名字以及上传文件保存的位置。如果让文件长期存储,我们将其移动到其他的位置即可。
html代码如下:

<form action='xx.php' method='post' enctype='multipart/form-data'>
    <input type='file' name='icon'>
    <input type='submit'>
</form>

服务器端代码:

<?php
// 可以打印 $_FILES的所有信息
print_r($_FILES);
move_uploaded_file($_FILES['photo']['tmp_name'], './images/test.jpg');
?>

注意:

  • $_FILES用法跟$_GET,$_POST类似,都是关系型数组。
  • #_FILE['key']:可以获取对应上传的文件,这里的key跟提交时的name相对应。
  • #_FILE['key']['name'] 可以获取上传的文件名。
  • #_FILE['key']['tmp_name']可以获取上传的文件保存的临时目录。

附录:move_uploaded_file(移动文件)
move_uploaded_file参数:
参数1:移动的文件
参数2:目标路径

php默认有上传文件大小的限制
我们只需要更改php.ini就可以修改基本配置

  • 设置文件最大上传限制(值的大小可以根据需求修改)

    file_uploads = On   ; 是否允许上传文件 On/Off 默认是On
    upload_max_filesize = 32M       ; 上传文件的最大限制
    post_max_size = 32M             ; 通过Post提交的最多数据
  • 考虑网络传输快慢,这里修改一些参数

    max_execution_time = 30000      ; 脚本最长的执行时间 单位为秒
    max_input_time = 600            ; 接收提交的数据的时间限制 单位为秒
    memory_limit = 1024M            ; 最大的内存消耗

  • 获得服务器的操作系统: <?PHP echo PHP_OS; ?>
  • 服务器端信息:<?PHP echo $_SERVER ['SERVER_SOFTWARE']; ?>
  • 服务器剩余空间大小:<?PHP echo disk_free_space("/目录"); ?>字节
  • 最大执行时间:<?PHP echo get_cfg_var("max_execution_time")."秒 "; ?>
  • 脚本运行占用最大内存:<?PHP echo get_cfg_var ("memory_limit")?get_cfg_var("memory_limit"):"无" ?>
  • 最大上传限制:<?PHP echo get_cfg_var ("upload_max_filesize")?get_cfg_var ("upload_max_filesize"):"不允许上传附件"; ?>
  • 服务器php版本:<?PHP echo PHP_VERSION; ?>
  • ZEND版本:<?PHP echo zend_version(); ?>
  • mysql版本:<?php @mysql_connect("127.0.0.1", "root", "root"); echo mysql_get_server_info(); ?>
  • MySQL最大连接数: <?php echo @get_cfg_var("mysql.max_links")==-1 ? "不限" : @get_cfg_var("mysql.max_links"); ?>
  • MySQL数据库持续连接:<?php echo @get_cfg_var("mysql.allow_persistent")?"是 ":"否"; ?>

附录:php中的header
浏览器访问http服务器,接收到响应时,会根据响应报文头的内容进行一些具体的操作,在php中,我们能够使用 header来设置这些内容

设置文本编码

设置编码格式为:utf-8
header('content-type:text/html; charset= utf-8');

设置页面跳转:设置跳转到百度首页
header('location:http://www.baidu.com');
设置页面间隔刷新
header('refresh:3; url=http://www.xiaomi.com');

第一步:下载Ueditor1.4.3

下载之后重命名为ueditor ,并放到项目的public目录下

第二步:引入

在视图文件里引入一下js文件

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>//也可以引用本地的
<js file="__ROOT__/Public/Ueditor/ueditor.config.js"/>  
<js file="__ROOT__/Public/Ueditor/ueditor.all.min.js"/>  
<js file="__ROOT__/Public/Ueditor/lang/zh-cn/zh-cn.js"/>  
<script type="text/javascript" charset="utf-8">  
   window.UEDITOR_HOME_URL = "__PUBLIC__/Ueditor/";  
    $(document).ready(function () {  
      UE.getEditor('info', {  
      initialFrameHeight: 500,  
      initialFrameWidth: 1100,  
      serverUrl: "{:U(MODULE_NAME.'/Index/save_info')}"  
    });  
  });    
</script>

在需要编辑器的地方写入以下代码

<textarea name="info" id="info" style="width:1024px;height:500px;"></textarea>  

第三步:控制器

在控制器中放入以下代码

public function save_info(){  
   $ueditor_config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "",     file_get_contents("./Public/Ueditor/php/config.json")), true);  
        $action = $_GET['action'];  
        switch ($action) {  
            case 'config':  
                $result = json_encode($ueditor_config);  
                break;  
                /* 上传图片 */  
            case 'uploadimage':  
                /* 上传涂鸦 */  
            case 'uploadscrawl':  
                /* 上传视频 */  
            case 'uploadvideo':  
                /* 上传文件 */  
            case 'uploadfile':  
                $upload = new \Think\Upload();  
                $upload->maxSize = 3145728;  
                $upload->rootPath = './Public/Uploads/';  
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');  
                $info = $upload->upload();  
                if (!$info) {  
                    $result = json_encode(array(  
                            'state' => $upload->getError(),  
                    ));  
                } else {  
                    $url = __ROOT__ . "/Public/Uploads/" . $info["upfile"]["savepath"] . $info["upfile"]['savename'];  
                    $result = json_encode(array(  
                            'url' => $url,  
                            'title' => htmlspecialchars($_POST['pictitle'], ENT_QUOTES),  
                            'original' => $info["upfile"]['name'],  
                            'state' => 'SUCCESS'  
                    ));  
                }  
                break;  
            default:  
                $result = json_encode(array(  
                'state' => '请求地址出错'  
                        ));  
                        break;  
        }  
        /* 输出结果 */  
        if (isset($_GET["callback"])) {  
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {  
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';  
            } else {  
                echo json_encode(array(  
                        'state' => 'callback参数不合法'  
                ));  
            }  
        } else {  
            echo $result;  
        }  
    }  

注意:文件默认目录为"Public/Uploads",如果没有就自己创建,也可以自己修改。

第一步:下载Page.class.php

把下载后的Page.class.php放入ThinkPHP/Extend/Library/ORG/Util/(如果该目录不存在就手动去创建)。

第二步:控制器

 

  $User = M('Goods');//实例化Goods数据对象  Goods是你的表名
  //p是前台传值过来的参数,也就是页码
    if($_GET['p']==NULL){
        $p=1;
    }else{
        $p=$_GET['p'];
    }
    $list = $User->order('id')->page($p.',10')->select();// 查询满足要求的总记录数
    $this->assign('list',$list);// 赋值数据集
    $count = $User->count();
    $Page = new \Think\Page($count,10);
    $show = $Page->show();
    $this->assign('page',$show);
    $this->display();

第三步:视图

<div class="result page">{$page}</div>

第四步:css

引入的样式小编感觉不是很好看,所以进行了一下美化,想要的童鞋可以拿走哦

.page{
    padding-top: 20px;
    padding-bottom: 15px;
    text-align: center;
    clear: both;
}
.num,.current,.prev,.next{
background-color: rgb(255, 255, 255);
border-bottom-color: rgb(226, 226, 226);
border-bottom-style: solid;
border-bottom-width: 0.666667px;
border-image-outset: 0;
border-image-repeat: stretch stretch;
border-image-slice: 100%;
border-image-source: none;
border-image-width: 1;
border-left-color: rgb(226, 226, 226);
border-left-style: solid;
border-left-width: 0.666667px;
border-right-color: rgb(226, 226, 226);
border-right-style: solid;
border-right-width: 0.666667px;
border-top-color: rgb(226, 226, 226);
border-top-style: solid;
border-top-width: 0.666667px;
box-sizing: content-box;
color: rgb(51, 51, 51);
display: inline-block;
font-family: Helvetica Neue, Helvetica, PingFang SC, 微软雅黑, Tahoma, Arial, sans-serif;
font-feature-settings: normal;
font-kerning: auto;
font-language-override: normal;
font-size: 12px;
font-size-adjust: none;
font-stretch: normal;
font-style: normal;
font-variant: normal;
font-variant-alternates: normal;
font-variant-caps: normal;
font-variant-east-asian: normal;
font-variant-ligatures: normal;
font-variant-numeric: normal;
font-variant-position: normal;
font-weight: 400;
height: 28px;
line-height: 28px;
margin-bottom: 5px;
margin-left: 0px;
margin-right: -1px;
margin-top: 0px;
padding-bottom: 0px;
padding-left: 15px;
padding-right: 15px;
padding-top: 0px;
position: relative;
text-align: left;
vertical-align: middle;
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
}
.current{
    background:orange;
}