<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>运达&#039;s  blog &#187; php技术</title>
	<atom:link href="https://www.yunda51.com/?cat=7&#038;feed=rss2" rel="self" type="application/rss+xml" />
	<link>https://www.yunda51.com</link>
	<description>运达的博客</description>
	<lastBuildDate>Wed, 12 Nov 2025 07:58:26 +0000</lastBuildDate>
	<language>zh-CN</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.0.19</generator>
	<item>
		<title>Laravel10使用JWT生成Token及验证Token实现登录功能</title>
		<link>https://www.yunda51.com/?p=2016</link>
		<comments>https://www.yunda51.com/?p=2016#comments</comments>
		<pubDate>Fri, 12 Jul 2024 09:38:02 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>
		<category><![CDATA[Jwt]]></category>
		<category><![CDATA[laravel]]></category>
		<category><![CDATA[nginx]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=2016</guid>
		<description><![CDATA[我的PHP版本为PHP8.3，nginx版本为1.25，所以官方默认下载4.0版本 1、首先安装JWT扩展包：<a href="https://www.yunda51.com/?p=2016" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<p>我的PHP版本为PHP8.3，nginx版本为1.25，所以官方默认下载4.0版本<br />
1、首先安装JWT扩展包：这里安装的4.0的，其他版本请查看JWT官网：<a href="https://jwt.io/libraries">https://jwt.io/libraries</a></p>
<pre class="wp-code-highlight prettyprint">
composer require lcobucci/jwt
</pre>
<p>2、封装类：JwtUtil.php<br />
在项目http目录下创建JwtAuth目录，并创建JwtUtil.php文件</p>
<pre class="wp-code-highlight prettyprint">
&lt;?php
namespace App\Http\JwtAuth;

use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;

/**
 * 单例模式
 * Class JwtUtil
 * @package App\JwtAuth\JwtUtil
 */
class JwtUtil
{
    private $config;
    private $key = &quot;Ge1KCTRhdVsmUUZY0GrwgEvLubPvLOCM&quot;;
    private $iss = &quot;tpxhm.com&quot;;//颁发者(iss声明)
    private $aud = &quot;tpxhmauth.com&quot;;//访问群体(aud声明)
    private $jti = &quot;5t6y9400453&quot;; //id（jti声明）
    private $expTime = 1;//令牌有效时间,单位小时
    private static $instance;// 单例模式JwtAuth句柄

    // 获取JwtAuth的句柄
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 构造
     */
    public function __construct()
    {
        self::init();
    }

    /**
     * 初始化
     */
    private function init()
    {
        $config = Configuration::forSymmetricSigner(
            new Sha256(),
            InMemory::base64Encoded($this-&gt;key)
        );
        $this-&gt;config = $config;
    }

    /**
     * 创建JWT
     * @param array $arrClaim
     * @return string
     * @throws \Exception
     * @author 简忆博客
     */
    public function createToken(array $arrClaim)
    {
        $config = $this-&gt;config;
        assert($config instanceof Configuration);
        if (is_array($arrClaim) &amp;&amp; count(array_filter(array_keys($arrClaim),&#039;is_string&#039;))&gt;0) {
            //是关联数组
        } else {
            //不是关联数组
            throw new \Exception(&quot;claim参数必须为关联数组&quot;);
        }

        $now = new \DateTimeImmutable();

        $token = $config-&gt;builder()
            // 配置颁发者（iss声明）
            -&gt;issuedBy($this-&gt;iss)
            // 配置访问群体（aud声明）
            -&gt;permittedFor($this-&gt;aud)
            // 配置id（jti声明）
            -&gt;identifiedBy($this-&gt;jti)
            // 配置令牌发出的时间（iat声明）
            -&gt;issuedAt($now)
            // 配置令牌的过期时间（exp claim）
            -&gt;expiresAt($now-&gt;modify(&quot;+{$this-&gt;expTime} hour&quot;));
        //claim
        foreach ($arrClaim as $k =&gt; $item) {
            $token = $token-&gt;withClaim($k, $item);
        }
        // 生成新令牌
        $token = $token-&gt;getToken($config-&gt;signer(), $config-&gt;signingKey());
        return $token-&gt;toString();
    }

    /**
     * 解析token
     * @param string $jwt
     * @return mixed
     * @author 简忆博客
     */
    public function parseToken(string $jwt)
    {
        $config = $this-&gt;config;
        $token = $config-&gt;parser()-&gt;parse($jwt);
        return $token-&gt;claims();
    }


    /**
     * 验证令牌
     * @param $jwt
     * @return mixed
     * @throws \Exception
     * @author 简忆博客
     */
    public function validatorToken($jwt)
    {
        $config = $this-&gt;config;
        $token = $config-&gt;parser()-&gt;parse($jwt);
        $claims = $token-&gt;claims();
        $jti = (string)$claims-&gt;get(&#039;jti&#039;);
        $iss = (string)$claims-&gt;get(&#039;iss&#039;);
        $aud = $claims-&gt;get(&#039;aud&#039;);
        $exp = $claims-&gt;get(&#039;exp&#039;);
        $now = new \DateTimeImmutable();
        // 是否过期
        if ($exp &lt; $now) {
            throw new \Exception(&quot;身份已过期&quot;);
        }
        //验证jwt id是否匹配
        $validate_jwt_id = new \Lcobucci\JWT\Validation\Constraint\IdentifiedBy($jti);
        // 验证签发人url是否正确
        $validate_issued = new \Lcobucci\JWT\Validation\Constraint\IssuedBy($iss);
        // 验证客户端url是否匹配
        $validate_aud = new \Lcobucci\JWT\Validation\Constraint\PermittedFor($aud[0]);
        $config-&gt;setValidationConstraints($validate_jwt_id, $validate_issued, $validate_aud);
        $constraints = $config-&gt;validationConstraints();
        //验证
        if (!$config-&gt;validator()-&gt;validate($token, ...$constraints)) {
            throw new \Exception(&quot;非法的请求&quot;);
        }
        return $claims;
    }
}
</pre>
<p>3、创建middleware中间件</p>
<pre class="wp-code-highlight prettyprint">
&lt;?php
namespace App\Http\Middleware;
use App\Http\JwtAuth\JwtUtil;
use App\Http\Response\ApiErrDesc;
use App\Http\Response\ResponseJson;
use Closure;
use Illuminate\Http\Request;

class CheckLogins
{
  use ResponseJson;

  /**
   * Handle an incoming request.
   *
   * @param \Illuminate\Http\Request $request
   * @param \Closure $next
   * @return mixed
   */
  public function handle(Request $request, Closure $next)
  {
    $token =!empty($_SERVER[&#039;HTTP_TOKEN&#039;]) ? $_SERVER[&#039;HTTP_TOKEN&#039;] : &#039;&#039;;
    if ($token) {
      //检验token
      $jwtAuth = JwtUtil::getInstance();
      $jwtAuth = $jwtAuth-&gt;validatorToken($token);
      if($jwtAuth){
        return $next($request);
      }else {
        return $this-&gt;jsonData(ApiErrDesc::EXPIRES_TIME[0], ApiErrDesc::EXPIRES_TIME[1]);
      }
    } else {
      return $this-&gt;jsonData(ApiErrDesc::LOGIN_TOKEN[0], ApiErrDesc::LOGIN_TOKEN[1]);
    }

  }
}
</pre>
<p>4、创建登录控制器：LoginController.php</p>
<pre class="wp-code-highlight prettyprint">
&lt;?php
namespace App\Http\Controllers\Admin;

use App\Http\JwtAuth\JwtUtil;
use App\Http\Response\ApiErrDesc;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\CheckCaptcha;
use App\Http\Response\ResponseJson;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{
  use ResponseJson;
  /*
   * 用户登录
   *
   * @param Request $request
   * @return false|string
   * */
  public function login(Request $request){
    //获取客户端传递的参数
    $name = $request-&gt;input(&#039;username&#039;);
    $password = $request-&gt;input(&#039;password&#039;);
    try {
      //去数据库中查询改用户信息
      $res=DB::table(&#039;sys_admin&#039;)-&gt;where(array(&#039;name&#039;=&gt;$name,&#039;stop&#039;=&gt;0))-&gt;first();
      if(!$res){
        return $this-&gt;jsonData(ApiErrDesc::NO_USER[0],ApiErrDesc::NO_USER[1]);
      }
    }catch (\Illuminate\Database\QueryException $exception){
      return $this-&gt;jsonData(ApiErrDesc::ERROR[0],$exception-&gt;getMessage());
    }

    //password_hash()
    $userPasswordHash = $res-&gt;password;
    if(!password_verify($password,$userPasswordHash)){
      return $this-&gt;jsonData(ApiErrDesc::ERR_PASSWORD[0],ApiErrDesc::ERR_PASSWORD[1]);
    }
    //验证成功，生成jwt返回
    $token = JwtUtil::getInstance()-&gt;createToken([&#039;uid&#039; =&gt; $res-&gt;id]);

    //登录成功
    return $this-&gt;jsonData(ApiErrDesc::LOGIN_SUCCESS[0],ApiErrDesc::LOGIN_SUCCESS[1],$token);
  }
}
5、查询用户信息
&lt;?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;

use App\Http\JwtAuth\JwtAuth;
use App\Http\JwtAuth\JwtUtil;
use App\Http\Response\ApiErrDesc;
use App\Http\Response\ResponseJson;

class PictureController extends Controller
{
  use ResponseJson;
  public function info(){
    //检验token
    $token =!empty($_SERVER[&#039;HTTP_TOKEN&#039;]) ? $_SERVER[&#039;HTTP_TOKEN&#039;] : &#039;&#039;;
    if (!$token){
      return $this-&gt;jsonData(ApiErrDesc::LOGIN_TOKEN[0], ApiErrDesc::LOGIN_TOKEN[1]);
    }
    $jwtAuth = JwtUtil::getInstance();
    $claims = $jwtAuth-&gt;validatorToken($token);
    //得到用户id
    $uid = $claims-&gt;get(&#039;uid&#039;);

    $user = DB::table(&#039;sys_admin&#039;)-&gt;where(&#039;id&#039;,$uid)-&gt;first();
    if(!$user){
      return $this-&gt;jsonData(ApiErrDesc::NO_USER[0],ApiErrDesc::NO_USER[1]);
    }
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=2016</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>如何实现全国快递物流查询</title>
		<link>https://www.yunda51.com/?p=1970</link>
		<comments>https://www.yunda51.com/?p=1970#comments</comments>
		<pubDate>Sun, 26 Nov 2023 15:02:31 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[快递查询]]></category>
		<category><![CDATA[物流查询]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1970</guid>
		<description><![CDATA[PHP如何实现全国快递物流查询-快递查询 以下代码是测试好的，可以拿去直接使用。 &#60;?php error<a href="https://www.yunda51.com/?p=1970" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<p>PHP如何实现全国快递物流查询-快递查询<br />
以下代码是测试好的，可以拿去直接使用。</p>
<pre class="wp-code-highlight prettyprint">
&lt;?php
	error_reporting(E_ALL || ~E_NOTICE);
	$host = &quot;https://wuliu.market.alicloudapi.com&quot;;//api访问链接
	$path = &quot;/kdi&quot;;//API访问后缀
	$method = &quot;GET&quot;;
	$appcode = &quot;d923462151414d73a4a16f6a7730bb68&quot;;//开通服务后 买家中心-查看AppCode
	$headers = array();
	array_push($headers, &quot;Authorization:APPCODE &quot; . $appcode);
	// $querys = &quot;no=462319523534879&amp;type=YUNDA&quot;;  //参数写在这里
	$querys = &quot;no=JDVE09474960402&quot;;  //参数写在这里
	$bodys = &quot;&quot;;
	$url = $host . $path . &quot;?&quot; . $querys;
	// echo $url;die;
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($curl, CURLOPT_FAILONERROR, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_HEADER, true);
	if (1 == strpos(&quot;$&quot; . $host, &quot;https://&quot;)) {
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	}
	$out_put = curl_exec($curl);

	$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
	list($header, $body) = explode(&quot;\r\n\r\n&quot;, $out_put, 2);
	if ($httpCode == 200) {
	    print(&quot;正常请求计费(其他均不计费)&lt;br&gt;&quot;);
	    print($body);
	} else {
	    if ($httpCode == 400 &amp;&amp; strpos($header, &quot;Invalid Param Location&quot;) !== false) {
	        print(&quot;参数错误&quot;);
	    } elseif ($httpCode == 400 &amp;&amp; strpos($header, &quot;Invalid AppCode&quot;) !== false) {
	        print(&quot;AppCode错误&quot;);
	    } elseif ($httpCode == 400 &amp;&amp; strpos($header, &quot;Invalid Url&quot;) !== false) {
	        print(&quot;请求的 Method、Path 或者环境错误&quot;);
	    } elseif ($httpCode == 403 &amp;&amp; strpos($header, &quot;Unauthorized&quot;) !== false) {
	        print(&quot;服务未被授权（或URL和Path不正确）&quot;);
	    } elseif ($httpCode == 403 &amp;&amp; strpos($header, &quot;Quota Exhausted&quot;) !== false) {
	        print(&quot;套餐包次数用完&quot;);
	    } elseif ($httpCode == 403 &amp;&amp; strpos($header, &quot;Api Market Subscription quota exhausted&quot;) !== false) {
	        print(&quot;套餐包次数用完，请续购套餐&quot;);
	    } elseif ($httpCode == 500) {
	        print(&quot;API网关错误&quot;);
	    } elseif ($httpCode == 0) {
	        print(&quot;URL错误&quot;);
	    } else {
	        print(&quot;参数名错误 或 其他错误&quot;);
	        print($httpCode);
	        $headers = explode(&quot;\r\n&quot;, $header);
	        $headList = array();
	        foreach ($headers as $head) {
	            $value = explode(&#039;:&#039;, $head);
	            $headList[$value[0]] = $value[1];
	        }
	        print($headList[&#039;x-ca-error-message&#039;]);
	    }
	}
?&gt;
</pre>
<p><strong>详见：</strong><br />
阿里全国物流接口链接：https://market.aliyun.com/products/57126001/cmapi021863.html?userCode=dligum2z</p>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1970</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>检测身份证号与姓名是否匹配（阿里云API接口）</title>
		<link>https://www.yunda51.com/?p=1968</link>
		<comments>https://www.yunda51.com/?p=1968#comments</comments>
		<pubDate>Sun, 26 Nov 2023 14:57:42 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[身份证号检测]]></category>
		<category><![CDATA[阿里云Api]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1968</guid>
		<description><![CDATA[直接上代码： /** * 检测身份证号与姓名是否匹配（阿里云API接口） * @return void * @<a href="https://www.yunda51.com/?p=1968" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<p>直接上代码：</p>
<pre class="wp-code-highlight prettyprint">
/**
 * 检测身份证号与姓名是否匹配（阿里云API接口）
 * @return void
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
public function is_card(){
     $data = $this-&gt;request-&gt;post();
     $host = &quot;https://lfeid.market.alicloudapi.com&quot;;
	 $path = &quot;/idcheck/lifePost&quot;;
	 $method = &quot;POST&quot;;
	 $appcode = &quot;d923462151414d73a4a16f6a7730bb68&quot;;
	 $headers = array();
	 array_push($headers, &quot;Authorization:APPCODE &quot; . $appcode);
	 //根据API的要求，定义相对应的Content-Type
	 array_push($headers, &quot;Content-Type&quot;.&quot;:&quot;.&quot;application/x-www-form-urlencoded; charset=UTF-8&quot;);
	 $querys = &quot;&quot;;
	 $bodys = &quot;cardNo=&#039;&quot;.$data[&#039;cardNo&#039;].&quot;&#039;&amp;realName=&#039;&quot;.$data[&#039;realName&#039;].&quot;&#039;&quot;;
	 $bodys = str_replace(&quot;&#039;&quot;, &#039;&#039;, $bodys);
	// $bodys = &quot;cardNo=130432199206170113&amp;realName=刘运达&quot;;
	 $url = $host . $path;
	 $curl = curl_init();
	 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
	 curl_setopt($curl, CURLOPT_URL, $url);
	 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	 curl_setopt($curl, CURLOPT_FAILONERROR, false);
	 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	 curl_setopt($curl, CURLOPT_HEADER, true);
	 if (1 == strpos(&quot;$&quot;.$host, &quot;https://&quot;))
	 {
	     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	 }
	 curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
	 var_dump(curl_exec($curl));
}
</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1968</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>手机端的H5页面自定义分享到微信朋友、朋友圈</title>
		<link>https://www.yunda51.com/?p=1966</link>
		<comments>https://www.yunda51.com/?p=1966#comments</comments>
		<pubDate>Sun, 26 Nov 2023 14:53:17 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>
		<category><![CDATA[H5]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[微信]]></category>
		<category><![CDATA[朋友圈]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1966</guid>
		<description><![CDATA[最近在工作中遇到了一个功能，需要将我们手机端的H5页面自定义分享到微信朋友、朋友圈、QQ和QQ空间。 下面是我<a href="https://www.yunda51.com/?p=1966" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<p>最近在工作中遇到了一个功能，需要将我们手机端的H5页面自定义分享到微信朋友、朋友圈、QQ和QQ空间。<br />
下面是我自己百度，然后自己亲身测试得到的一个方法；下面分享给大家，相互学习。<br />
实现原理：H5的自定义分享需要用到微信公众平台的分享接口，也就是微信网页开发中的JSSDK,【具体的说明文档：https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html】使用微信的SDK中的分享接<br />
示例：https://m.php.cn/faq/538242.html<br />
获取流程：<br />
1、获取 access_token<br />
2、通过access_token换取 jsapi_ticket<br />
3、签名算法<br />
签名生成规则如下：参与签名的字段包括noncestr（随机字符串）, 有效的jsapi_ticket, timestamp（时间戳）, url（当前网页的URL，不包含#及其后面部分） 。对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1&#038;key2=value2…）拼接成字符串string1。这里需要注意的是所有参数名均为小写字符。对string1作sha1加密，字段名和字段值都采用原始值，不进行URL 转义。<br />
因为获取access_token不能请求，请求次数过多微信会把IP禁用，所以需要把access_token缓存起来，要不存到数据库里，两种方法，看自己选择。<br />
<strong>二、在数据库中添加access_token表：</strong></p>
<pre class="wp-code-highlight prettyprint">
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for access_token
-- ----------------------------
DROP TABLE IF EXISTS access_token;
CREATE TABLE access_token (
id int(11) NOT NULL AUTO_INCREMENT,
access_token char(64) NOT NULL COMMENT &#039;令牌-唯一标识&#039;,
expires_time varchar(64) DEFAULT NULL COMMENT &#039;过期时间&#039;,
ticket char(64) NOT NULL COMMENT &#039;临时票据&#039;,
ticket_expires_time varchar(64) DEFAULT NULL COMMENT &#039;过期的票据时间&#039;,
PRIMARY KEY (id)
</pre>
<p><strong>三、具体实现方式</strong><br />
1、获取access_token（access_token 的有效时间是7200s，故可以采用文件存储的方法进行保存，避免多次请求；）</p>
<pre class="wp-code-highlight prettyprint">
/**
* 添加微信分享接口
* 第一步：获取access token
*/
public function getAccessToken(){
$appid = &#039;wx207546bd5b43c838&#039;;
$secret = &#039;0ea9ee069f0dee52861aa460bed26452&#039;; //用户唯一凭证密钥
$time = time()+7000; //当前时间+2小时等于过期时间
$res = file_get_contents(&#039;https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&amp;appid=&#039; .$appid.&#039;&amp;secret=&#039;. $secret);
$res = json_decode($res, true);
$token = $res[&#039;access_token&#039;];
if($token){
$insert_data[&#039;access_token&#039;] = $token;
$insert_data[&#039;expires_time&#039;] = $time;
//把获得的token存储到数据库中
$model = Db::table(&quot;access_token&quot;)-&gt;insert($insert_data);
}
return $token;
</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1966</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>linux下Thinkphp6+workerman+gateway基本简介与环境搭建</title>
		<link>https://www.yunda51.com/?p=1942</link>
		<comments>https://www.yunda51.com/?p=1942#comments</comments>
		<pubDate>Tue, 13 Sep 2022 10:57:11 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>
		<category><![CDATA[Thinkphp]]></category>
		<category><![CDATA[socket]]></category>
		<category><![CDATA[Thinkphp6]]></category>
		<category><![CDATA[workman]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1942</guid>
		<description><![CDATA[1、Composer安装与基本使用 https://docs.phpcomposer.com/00-intro<a href="https://www.yunda51.com/?p=1942" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<h2>1、Composer安装与基本使用</h2>
<p><a href="https://docs.phpcomposer.com/00-intro.html">https://docs.phpcomposer.com/00-intro.html</a></p>
<p>1）、下载</p>
<pre class="wp-code-highlight prettyprint"># curl -sS https://getcomposer.org/installer | php
</pre>
<p>或者</p>
<pre class="wp-code-highlight prettyprint"># php -r &quot;copy(&#039;https://install.phpcomposer.com/installer&#039;, &#039;composer-setup.php&#039;);
# php composer-setup.php
</pre>
<p>2）、移动 composer.phar，以便 composer 能进行全局调用：</p>
<pre class="wp-code-highlight prettyprint"># mv composer.phar /usr/local/bin/composer
</pre>
<p>3）、切换为国内镜像：</p>
<pre class="wp-code-highlight prettyprint"># composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
</pre>
<p>4）、更新 composer：</p>
<pre class="wp-code-highlight prettyprint"># composer selfupdate
</pre>
<p>https://docs.phpcomposer.com/01-basic-usage.html</p>
<p><strong>2、安装thinkphp6</strong></p>
<p>安装稳定版</p>
<pre class="wp-code-highlight prettyprint">composer create-project topthink/think tp6
</pre>
<p><a href="http://www.yunda51.com/wp-content/uploads/2022/09/1.png"><img class="alignnone size-full wp-image-1943" src="http://www.yunda51.com/wp-content/uploads/2022/09/1.png" alt="1" width="830" height="160" /></a><br />
查看配置文件是否禁用了proc_open函数</p>
<p>putenv</p>
<hr />
<p><a href="http://www.yunda51.com/wp-content/uploads/2022/09/2.png"><img class="alignnone size-full wp-image-1944" src="http://www.yunda51.com/wp-content/uploads/2022/09/2.png" alt="2" width="830" height="386" /></a><br />
<a href="http://www.yunda51.com/wp-content/uploads/2022/09/3.png"><img class="alignnone size-full wp-image-1945" src="http://www.yunda51.com/wp-content/uploads/2022/09/3.png" alt="3" width="830" height="838" /></a></p>
<p><strong>安全PHP要求&gt;=7.1.0</strong></p>
<p><strong>3、Workerman简介与安装</strong></p>
<pre class="wp-code-highlight prettyprint">简介：引用官方的
Workerman是一款纯PHP开发的开源高性能的PHP socket 服务器框架。被广泛的用于手机app、手游服务端、网络游戏服务器、聊天室
服务器、硬件通讯服务器、智能家居、车联网、物联网等领域的开发。 支持TCP长连接，支持Websocket、HTTP等协议，支持自定义协议。
基于workerman开发者可以更专注于业务逻辑开发，不必再为PHP Socket底层开发而烦恼。
</pre>
<p>其它介绍</p>
<p>http://doc.workerman.net/</p>
<p>http://doc2.workerman.net/</p>
<p>https://web.popoim.cn/im/web</p>
<p>https://demo.popoim.cn/im/h5/</p>
<p>安装：</p>
<pre class="wp-code-highlight prettyprint">composer require topthink/think-worker
</pre>
<p>安装gateway-worker<br />
<a href="http://www.yunda51.com/wp-content/uploads/2022/09/4.png"><img src="http://www.yunda51.com/wp-content/uploads/2022/09/4.png" alt="4" width="828" height="146" class="alignnone size-full wp-image-1946" /></a></p>
<p>须要安装fileinfo扩展<br />
<a href="http://www.yunda51.com/wp-content/uploads/2022/09/5.png"><img src="http://www.yunda51.com/wp-content/uploads/2022/09/5.png" alt="5" width="830" height="582" class="alignnone size-full wp-image-1947" /></a></p>
<p><strong>4、运行workerman作为服务端（socketServer）</strong></p>
<pre class="wp-code-highlight prettyprint">
php think worker:server
</pre>
<p><a href="http://www.yunda51.com/wp-content/uploads/2022/09/6.png"><img src="http://www.yunda51.com/wp-content/uploads/2022/09/6.png" alt="6" width="830" height="492" class="alignnone size-full wp-image-1948" /></a></p>
<p>pcntl相关函数</p>
<p>https://www.php.net/manual/zh/book.pcntl.php</p>
<p><strong>5、连接websocket</strong><br />
客户端代码 ：</p>
<pre class="wp-code-highlight prettyprint">
ws = new WebSocket(&quot;ws://xxx.xxx.xxx.xxx:9999&quot;);
ws.onopen = function() {
    alert(&quot;连接成功&quot;);
    ws.send(&#039;tom&#039;);
    alert(&quot;给服务端发送一个字符串：tom&quot;);
};
ws.onmessage = function(e) {
    alert(&quot;收到服务端的消息：&quot; + e.data);
};

</pre>
<p>连接不上的原因十有八九<br />
防火墙命令：<br />
查看状态：systemctl status firewalld.service<br />
关闭firewall：systemctl stop firewalld.service<br />
启动：systemctl start firewalld.service<br />
重启：systemctl restart firewalld.service</p>
<p>查看已开放端口：<br />
firewall-cmd --list-ports<br />
开放端口：<br />
firewall-cmd --zone=public --add-port=9999/tcp --permanent</p>
<pre class="wp-code-highlight prettyprint">
–zone #作用域
–add-port=80/tcp #添加端口，格式为：端口/通讯协议
–permanent #永久生效，没有此参数重启后失效
</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1942</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP生成8位单个邀请码/8位卡密</title>
		<link>https://www.yunda51.com/?p=1917</link>
		<comments>https://www.yunda51.com/?p=1917#comments</comments>
		<pubDate>Tue, 13 Sep 2022 08:12:29 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[Mysql]]></category>
		<category><![CDATA[php技术]]></category>
		<category><![CDATA[8位卡密]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[邀请码]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1917</guid>
		<description><![CDATA[/**PHP生成8位单个邀请码/8位卡密 * @return string **/ public functi<a href="https://www.yunda51.com/?p=1917" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<pre class="wp-code-highlight prettyprint">/**PHP生成8位单个邀请码/8位卡密
 * @return string
**/
    public function make_invite_code(){
        $code=&quot;ABCDEFGHIGKLMNOPQRSTUVWXYZ&quot;;
        $rand=$code[rand(0,25)].strtoupper(dechex(date(&#039;m&#039;))).date(&#039;d&#039;).substr(time(),-5).substr(microtime(),2,5).sprintf(&#039;%02d&#039;,rand(0,99));
        for(
                $a = md5( $rand, true ),
                $s = &#039;0123456789ABCDEFGHIJKLMNOPQRSTUV&#039;,
                $d = &#039;&#039;,
                $f = 0;
                $f &amp;lt; 8;
                $g = ord($a[$f]), // ord（）函数获取首字母的 的 ASCII值
                $d .= $s[($g ^ ord( $a[ $f + 8 ] ) ) - $g &amp;amp; 0x1F ],  //按位亦或，按位与。
                $f++
        );
        return $d;
    }
 
</pre>
<pre class="wp-code-highlight prettyprint">   
 /**
 * 生成不重复的随机数字(不能超过10位数，否则while循环陷入死循环)
 * @param  int $start 需要生成的数字开始范围
 * @param  int $end 结束范围
 * @param  int $length 需要生成的随机数个数
 * @return number      生成的随机数
 */
function getRandNumber($start = 0, $end = 9, $length = 8)
{
    //初始化变量为0
    $count = 0;
    //建一个新数组
    $temp = array();
    while ($count &amp;lt; $length) {
        //在一定范围内随机生成一个数放入数组中
        $temp[] = mt_rand($start, $end);
        //$data = array_unique($temp);
        //去除数组中的重复值用了“翻翻法”，就是用array_flip()把数组的key和value交换两次。这种做法比用 array_unique() 快得多。
        $data = array_flip(array_flip($temp));
        //将数组的数量存入变量count中
        $count = count($data);
    }
    //为数组赋予新的键名
    shuffle($data);
    //数组转字符串
    $str = implode(&quot;,&quot;, $data);
    //替换掉逗号
    $number = str_replace(&#039;,&#039;, &#039;&#039;, $str);
    return $number;
}
 
echo getRandNumber(0, 9, 8).&quot;
&quot;;

</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1917</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP如何实现图片添加文字，生成新图片</title>
		<link>https://www.yunda51.com/?p=1904</link>
		<comments>https://www.yunda51.com/?p=1904#comments</comments>
		<pubDate>Tue, 13 Sep 2022 07:48:21 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1904</guid>
		<description><![CDATA[/* **生成证书图片 **$BlockHash 区块hash ** */ public function c<a href="https://www.yunda51.com/?p=1904" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<pre class="wp-code-highlight prettyprint">
/*
**生成证书图片
**$BlockHash 区块hash
**
*/
public function createNewPic($mer_id,$mer_name,$BlockHash,$TxID){
    //背景图片
    $path_1 = &#039;img/background_code.png&#039;;
    //照片
    $path_2= &#039;img/1.png&#039;;
    //建立图片对象
    $image_1 = imagecreatefrompng($path_1);
    $image_2 = imagecreatefrompng($path_2);
    //合成图片
    imagecopymerge($image_1, $image_2, 0, 0, 10, 10, imagesx($image_2), imagesy($image_2), 100);
    //这是要插入到图片的文字
    $data=date(&#039;ymd&#039;,time());
    $pad=str_pad(1,4,&quot;0&quot;,STR_PAD_LEFT);
    $str=mt_rand(10000000,99999999);
    $number=$data.$pad.$subtle.$str; 
    $prove=&quot;兹证明：\n\n美嘉兔科技有限公司，产品符合溯源规范，认证内容如下：\n特授权期产品在元一众享溯源商城出售&quot;;  
    $prove=&quot;兹证明：&quot;;  
    $mer_name = &quot;中国溯源旗舰店&quot;;
    $merName = $mer_name.&quot;，产品符合溯源规范，\n认证内容如下：\n特授权其产品在元一众享溯源商城出售!&quot;; 
    $hash = &quot;930faf66cc24e7a5af56fcdee7c9b726c5869cd763ba5166a22de5f34c3570d5&quot;;
    $hash = wordwrap($hash,45,&quot;\n&quot;,TRUE);
    $authorization_time = date(&#039;Y/m/d&#039;,time());
    $valid_time = date(&quot;Y/m/d&quot;,strtotime(&quot;+1years&quot;,strtotime(date(&#039;Y/m/d&#039;,time()))));
    //设置文字颜色
    $black = imagecolorallocate($image_1, 0, 0, 0 );
    $blue = imagecolorallocate($image_1, 27,142,187);
    //写的文字用到的字体
    $font = &#039;img/msyh.ttf&#039;;
    $font2= &#039;img/msyhbd.ttf&#039;;

    //在图片里插入文字$black
    imagettftext($image_1, 20, 0, 290, 340, $black,$font, &quot;证书编号：&quot;.$number);
    imagettftext($image_1, 20, 0, 150, 450, $black,$font, $prove);
    imagettftext($image_1, 20, 0, 200, 500, $black,$font, $merName);
    imagettftext($image_1, 20, 0, 140, 730, $blue,$font, &quot;交易哈希：\n&quot;.$hash);
    imagettftext($image_1, 20, 0, 570, 1050, $black,$font, &quot;授权时间：&quot;.$authorization_time);
    imagettftext($image_1, 20, 0, 570, 1100, $black,$font, &quot;有效期至：&quot;.$valid_time);

    //这是合成后的图片保存的路径
    $upload_dir = &quot;pic/&quot;;
    //文件名
    $filename=&quot;YY&quot;;
    $data=date(&#039;ymd&#039;,time());
    $pad=str_pad(1,2,&quot;0&quot;,STR_PAD_LEFT);
    $str=mt_rand(100000,999999);
    $subtle = microtime()*1000000;
    $jobnumber=$data.$pad.$subtle.$str;
    $picture=$upload_dir.$filename.$jobnumber.&#039;.png&#039;;
    imagepng($image_1,$picture);
    $url = &#039;http://&#039;.$_SERVER[&#039;HTTP_HOST&#039;].&#039;/&#039;.$picture;
    return  $url;
}
</pre>
<p>如果添加的文字过长可使用wordwrap()函数进行设置换行。<br />
例如：</p>
<pre class="wp-code-highlight prettyprint">
$BlockHash = wordwrap($result[&#039;data&#039;][&#039;blockhash&#039;],42,&quot;\n&quot;,TRUE);
</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1904</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP 构造模拟http请求https_request支持GET和POST</title>
		<link>https://www.yunda51.com/?p=1902</link>
		<comments>https://www.yunda51.com/?p=1902#comments</comments>
		<pubDate>Tue, 13 Sep 2022 07:39:44 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[HTTP协议]]></category>
		<category><![CDATA[php技术]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1902</guid>
		<description><![CDATA[/* **PHP 构造 模拟 http 请求 https_request 支持GET和POST */ func<a href="https://www.yunda51.com/?p=1902" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<pre class="wp-code-highlight prettyprint">
/*
**PHP 构造 模拟 http 请求 https_request 支持GET和POST
*/
function https_request($url, $data = null)
{
    $curl = curl_init();//初始化
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);//允许 cURL 函数执行的最长秒数。
    /*if (!empty($port)) {
        curl_setopt($curl, CURLOPT_PORT, $port);//可选的用来指定连接端口，默认80端口可不写
    }*/
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(&#039;Content-type: application/json;charset=UTF-8&#039;));//设置请求目标url头部信息
    if (!empty($data)) {
        //$data不为空，发送post请求
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); //$data：数组
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);//执行命令
    $error = curl_error($curl);//错误信息
    if ($error || $output == FALSE) {
        //报错信息
        return &#039;ERROR &#039; . curl_error($curl);
    }
    curl_close($curl);
    return $output;
}

</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1902</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Laravel配置路由出现404解决办法</title>
		<link>https://www.yunda51.com/?p=1771</link>
		<comments>https://www.yunda51.com/?p=1771#comments</comments>
		<pubDate>Thu, 25 May 2017 09:46:27 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>
		<category><![CDATA[laravel]]></category>
		<category><![CDATA[nginx]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1771</guid>
		<description><![CDATA[环境：Lnmp（nginx+php+mysql） 今天在搭建Laravel框架的时候访问显示空白页： 解决如下<a href="https://www.yunda51.com/?p=1771" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<p>环境：Lnmp（nginx+php+mysql）<br />
今天在搭建Laravel框架的时候访问显示空白页：<br />
解决如下：</p>
<pre class="wp-code-highlight prettyprint">
cd laravel
chmod -R 777 storage
</pre>
<p><strong>在配置Laravel路由的时候报了404错误</strong><br />
首先分析下问题：一般出现这种情况的都是apache或者nginx配置出现问题</p>
<p>nginx解决办法</p>
<p>    在location里面加上　try_files $uri $uri/ /index.php?$query_string;</p>
<p>    如果配置文件中存在　try_files $uri $uri/ =404;需要将它注释掉或者删掉，否则会报错</p>
<p><strong>鄙人的nginx配置如下：</strong></p>
<pre class="wp-code-highlight prettyprint">
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
#   include       /app/soft/nginx/conf/vhost/*.conf;
    default_type  application/octet-stream;
    client_max_body_size 50m;
    client_header_buffer_size 50M;
    large_client_header_buffers 4 50M;
    log_format main &#039;$server_name $remote_addr - $remote_user [$time_local] &quot;$request&quot; &#039;
    &#039;$status $body_bytes_sent &quot;$http_referer&quot; &#039;
    &#039;&quot;$http_user_agent&quot; &quot;$http_x_forwarded_for&quot; &#039;
    &#039;$ssl_protocol $ssl_cipher $upstream_addr $request_time $upstream_response_time&#039;;
    sendfile        on;
    keepalive_timeout  65;

server {
        listen       80;
        server_name  localhost;
        send_timeout 60;

        location / {
            root   /app/www/laravel/public;
            access_log  /app/log/access.log;
            error_log   /app/log/error.log debug;
	    try_files $uri $uri/ /index.php?$query_string; 
            index  index.php index.html index.htm;

        }

        location ~ \.php$ {
        root   /app/www/laravel/public;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
        fastcgi_buffers 8 128k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
        include        fastcgi_params;
        }
    }
</pre>
<p>这样就ok了，现在可以开启你的laravel模式了~~</p>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1771</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>php 判断http还是https，以及获得当前url的方法</title>
		<link>https://www.yunda51.com/?p=1746</link>
		<comments>https://www.yunda51.com/?p=1746#comments</comments>
		<pubDate>Fri, 17 Feb 2017 08:07:18 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>
		<category><![CDATA[http://]]></category>
		<category><![CDATA[https://]]></category>
		<category><![CDATA[SSL]]></category>
		<category><![CDATA[SSL数字证书]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1746</guid>
		<description><![CDATA[服务器安装SSL数字证书访问URL地址是https，所以在无论是https://访问还是http://访问通行<a href="https://www.yunda51.com/?p=1746" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<p>服务器安装SSL数字证书访问URL地址是https，所以在无论是https://访问还是http://访问通行！</p>
<pre class="wp-code-highlight prettyprint">
$http_type = ((isset($_SERVER[&#039;HTTPS&#039;]) &amp;&amp; $_SERVER[&#039;HTTPS&#039;] == &#039;on&#039;) || (isset($_SERVER[&#039;HTTP_X_FORWARDED_PROTO&#039;]) &amp;&amp; $_SERVER[&#039;HTTP_X_FORWARDED_PROTO&#039;] == &#039;https&#039;)) ? &#039;https://&#039; : &#039;http://&#039;;  
echo $http_type . $_SERVER[&#039;HTTP_HOST&#039;] . $_SERVER[&#039;REQUEST_URI&#039;]; ?&gt;  
</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1746</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
