【php】TP5 Mysql版Session驱动 DownLoad

Continue Read..
  CREATE TABLE `think_session` (
      `session_id` VARCHAR(255) NOT NULL,
      `session_expire` INT(11) UNSIGNED NOT NULL,
      `session_data` BLOB NULL,
      UNIQUE INDEX `session_id` (`session_id`)
  )
  COLLATE='utf8_general_ci'

  ENGINE=InnoDB;



'session'                => [
  'type'              => 'driver\session\Mysql', // 驱动方式 支持redis memcache memcached
  'auto_start'        => true,        // 是否自动开启 SESSION
  // Session驱动设置
  'session_expire'    => 3600,        // Session有效期 单位:秒
  'session_prefix'    => 'think_',    // Session前缀
  'table_name'        => 'session',   // 表名(不包含表前缀)
  'database'          =>  [
      'hostname'  => '127.0.0.1',     // 服务器地址
      'database'  => 'test',         // 数据库名
      'username'  => 'root',        // 用户名
      'password'  => '',    // 密码
      'hostport'  => '3306',          // 端口
      'prefix'    => '',            // 表前缀(默认为空)
      'charset'   => 'utf8',          // 数据库编码
  ]
],

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【php】excel数据导入 日期格式化

Continue Read..
 /**
   * 判断字符串是否是日期格式
   * @param $date 
   * @param $format
   * @return bool
   */
  function is_date($date, $format = 'Y-m-d')
  {
    if (!$date || $date == '0000-00-00') return false;
    $unix_time_1 = strtotime($date);
    if (!is_numeric($unix_time_1)) return false; //非数字格式
    $format_date = date($format, $unix_time_1);
    $unix_time_2 = strtotime($format_date);
    return ($unix_time_1 == $unix_time_2);
  }

  /**
   * excel数据导入  日期格式化
   * @param $date
   * @return false|string
   */
  function get_date_by_excel($date)
  {
    if (!$date || $date == '0000-00-00') return null;

    $unix_time = \PHPExcel_Shared_Date::ExcelToPHP($date);

    return ($unix_time < 0) ? date('Y-m-d H:i:s', $unix_time) : date('Y-m-d H:i:s', strtotime(gmdate('Y-m-d H:i:s', $unix_time)));
  }

  /**
   * 获取excel日期格式化结果
   * @param $date string excel日期单元格字符串
   * @param $default string  $date未非日期时返回默认日期
   * @return string
   */
  function excel_date_format($date, $default = '')
  {
    if ($default == '') $default = date('Y-m-d H:i:s');

    if ($this->is_date($date)) return $date;

    return $this->get_date_by_excel($date) ?: $default;
  }






^ "44441.976770833"
^ "2021-09-02 23:26:33"
^ "2021-09-03 15:12:34"

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【nginx】得到IP地址

Continue Read..

nginx 

  proxy_set_header X-Real-IP $remote_addr;

  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

  proxy_set_header Host $host;

  real_ip_header    X-Forwarded-For;

  real_ip_recursive on;

 

php 

<?php

echo long2ip(_get_ip());

function _get_ip($full = false) {

        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {

            if ($full == true)

                return sprintf("%u\n", ip2long($_SERVER["HTTP_X_FORWARDED_FOR"]));

            $tmp_ips = explode(',', $_SERVER["HTTP_X_FORWARDED_FOR"]);

            $ip = array_shift($tmp_ips);

        }

        else if (isset($_SERVER["HTTP_CLIENT_IP"]))

            $ip = $_SERVER["HTTP_CLIENT_IP"];

        else if (isset($_SERVER["REMOTE_ADDR"]))

            $ip = $_SERVER["REMOTE_ADDR"];

        else if (getenv("HTTP_X_FORWARDED_FOR"))

            $ip = getenv("HTTP_X_FORWARDED_FOR");

        else if (getenv("HTTP_CLIENT_IP"))

            $ip = getenv("HTTP_CLIENT_IP");

        else if (getenv("REMOTE_ADDR"))

            $ip = getenv("REMOTE_ADDR");

        else

            $ip = "Unknown";

        return sprintf("%u\n", ip2long($ip));

    }


声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【thinkphp5】ThinkPHP5如何使用build.php

Continue Read..

进入application

php ../think build --config ..\build.php

 

 

build.php里面写需要生成的配置

 

 

return [
    // 生成应用公共文件
    '__file__' => ['common.php''config.php''database.php'],

    // 定义demo模块的自动生成 (按照实际定义的文件名生成)
    'xxx'     => [
        '__file__'   => ['common.php'],
        '__dir__'    => ['behavior''controller''model''view'],
        'controller' => ['Index''Test''UserType'],
        'model'      => ['User''UserType'],
        'view'       => ['index/index'],
    ],
    // 其他更多的模块定义
];

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【php】RabbitMQ+supervisord+php消息队列

Continue Read..
CentOS7安装RabbitMQ

由于rabbitmq是基于erlang语言开发的,所以必须先安装erlang。
安装依赖
yum -y install gcc glibc-devel make ncurses-devel openssl-devel xmlto perl wget gtk2-devel binutils-devel

erlang官网:

https://www.erlang.org/downloads

下载(会比较慢,请耐心等待)

wget http://erlang.org/download/otp_src_22.0.tar.gz

移走

mv otp_src_22.0 /usr/local/

切换目录

cd /usr/local/otp_src_22.0/
 

创建即将安装的目录

mkdir ../erlang
 

配置安装路径

./configure --prefix=/usr/local/erlang

如果遇到这个错 你就假装没看到

点击查看原图
安装

make install

 

查看一下是否安装成功

ll /usr/local/erlang/bin
 

添加环境变量

echo 'export PATH=$PATH:/usr/local/erlang/bin' >> /etc/profile
 

刷新环境变量

source /etc/profile
 

甩一条命令

erl
 
点击查看原图
瞬间进入了一个未知的世界

在里面输入halt().命令退出来(那个点号别忘记)

点击查看原图



安装RabbitMQ
rabbitmq下载地址:

https://github.com/rabbitmq/rabbitmq-server/releases/tag/v3.7.15

 

下载

wget https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.7.15/rabbitmq-server-generic-unix-3.7.15.tar.xz
 

由于是tar.xz格式的所以需要用到xz,没有的话就先安装 

yum install -y xz
 

第一次解压

/bin/xz -d rabbitmq-server-generic-unix-3.7.15.tar.xz
 

第二次解压

tar -xvf rabbitmq-server-generic-unix-3.7.15.tar
 

移走

mv rabbitmq_server-3.7.15/ /usr/local/
 

改名

mv /usr/local/rabbitmq_server-3.7.15  rabbitmq
 

配置环境变量

echo 'export PATH=$PATH:/usr/local/rabbitmq/sbin' >> /etc/profile
 

刷新环境变量

source /etc/profile
 

创建配置目录

mkdir /etc/rabbitmq
 

回到顶部
启动命令
启动:

rabbitmq-server -detached
 

停止:

rabbitmqctl stop
 

状态:

rabbitmqctl status
 

防火墙之类的请自行处理(5672和15672端口),反正我是从来不开防火墙。

 

回到顶部
WEB管理
开启web插件

rabbitmq-plugins enable rabbitmq_management
 

访问:http://127.0.0.1:15672/
点击查看原图 

默认账号密码:guest guest(这个账号只允许本机访问)

 

回到顶部
用户管理
查看所有用户

rabbitmqctl list_users
 

添加一个用户

rabbitmqctl add_user admin 123456
 

配置权限

rabbitmqctl set_permissions -p "/" admin ".*" ".*" ".*"
 

查看用户权限

rabbitmqctl list_user_permissions admin
 

设置tag

rabbitmqctl set_user_tags admin administrator
 

删除用户(安全起见,删除默认用户)

rabbitmqctl delete_user guest
 

回到顶部
登陆
配置好用户之后重启一下rabbit

然后就可以用新账号进行登陆

点击查看原图

 

 

安装supervisord

yum install epel-release

yum install -y supervisor

 

#yum -y install python-setuptools zlib

easy_install supervisor

echo_supervisord_conf > /etc/supervisord.conf

 

mkdir -p /data/etc/supervisord/

mkdir -p /data2/logs/supervisord/

chmod 777 /data2/logs/supervisord/

 

修改 /etc/supervisord.conf

sed -i -e "s#logfile=/tmp/supervisord.log#logfile=/data2/logs/supervisord/supervisord.log#g" /etc/supervisord.conf

sed -i -e "s#file=/tmp/supervisor.sock#file=/var/run/supervisor.sock#g" /etc/supervisord.conf

sed -i -e "s#pidfile=/tmp/supervisord.pid#pidfile=/var/run/supervisord.pid#g" /etc/supervisord.conf

sed -i -e "s#serverurl=unix:///tmp/supervisor.sock#serverurl=unix:///var/run/supervisor.sock#g" /etc/supervisord.conf

echo "[include]" >> /etc/supervisord.conf

echo "files = /data/www/supervisord/*.ini" >> /etc/supervisord.conf

 

 

 

操作脚本:

vi /usr/lib/systemd/system/supervisord.service

 

#输入下面内容,并保存

[Unit]

Description=Supervisord

After=network.target

 

[Service]

Type=forking

PIDFile=/var/run/supervisord.pid

ExecStart=/usr/bin/supervisord -c /etc/supervisord.conf

ExecStop=/bin/kill -TERM $MAINPID

ExecReload=/bin/kill -HUP $MAINPID

Restart=always

 

[Install]

WantedBy=multi-user.target

保存

 

#修改权限

chmod +x /usr/lib/systemd/system/supervisord.service

 

systemctl enable supervisord.service

启用:systemctl start supervisord

 

#其它控制命令

systemctl stop supervisord

systemctl reload supervisord

 

查看进程列表:

systemctl status supervisord

#supervisorctl status

停止进程 mq_test_worker:

supervisorctl stop mq_test_worker:

开始进程 mq_test_worker::

supervisorctl start mq_test_worker:

 

 

启动程序如果提示:Starting supervisor: Error: Another program is already listening on a port that one of our HTTP servers is configured to use.  Shut this program down first before starting supervisord.

unlink /var/run/supervisor.sock

 

 

 

sudo chmod 777 /run

sudo chmod 777 /var/log

sudo touch /var/run/supervisor.sock

sudo chmod 777 /var/run/supervisor.sock

supervisord -c /etc/supervisord.conf

ps aux | grep supervisord

 

 

 

最后效果

supervisord -c /etc/supervisord.conf 开启supervisord服务

supervisorctl start mq_test_worker 开启需要常驻的脚本服务

执行脚本test.php

然后tail -f mq_test_worker.log 里面可以看到队列的数据

 

点击查看原图

 

 

代码附件 : msg_broker.zip

 

 参考网站

RabbitMQ:https://www.cnblogs.com/fengyumeng/p/11133924.html

supervisord(碰到的坑):

https://www.missshi.cn/api/view/blog/5aafcf405b925d681e000000

https://www.cnblogs.com/ruanraun/p/supervisor.html

https://blog.csdn.net/weixin_41762173/article/details/88901970

 

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【php】win修改php-cgi.exe启动接口

Continue Read..
1、先要运行起php的cgi,由于本人用的win7系统,所以cmd先进的c盘(之前全扔c盘这就简单了~),访问到php路径中,输入
php-cgi.exe -b 127.0.0.1:9000
注意这里的-b 127.0.0.1:9000是指定cgi的监听端口,与上文中的Nginx配置要一致,如果有其他配置不记得之前php-cgi是那个端口,可以使用php-cgi.exe -h命令来查看配置(查看-b 后面的<address:port>)。想要查看所有被监听的端口则输入netstat -na

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【php】mysql跨库回滚

Continue Read..
CREATE TABLE afu.`test2` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE trade.`test2` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
<?php
/**
 * Created by PhpStorm.
 * User: cuzn
 * Date: 2018/12/28
 * Time: 19:10
 */


namespace app\afu\cron\department;

use app\afu\api\model\afu\Test2Model;
use app\afu\api\model\trade\Test1Model;
use PhpOffice\PhpSpreadsheet\Exception;

require_once __DIR__ . '/../../conf/config.inc.php';

echo "exec at " . date('Y-m-d H:i:s') . "\n";


$Test1Model = Test1Model::getInstance();


function addTest2($isBack = false){
    $Test2Model = Test2Model::getInstance();
    try {
        $Test2Model->begin();
    
        $ret = $Test2Model->insert([
            'name' => 'bbbbbbb'
        ]);
        if (!$isBack) {
            $Test2Model->commit();
            return true;
        } else {
            $Test2Model->rollback();
            return false;
        }
    } catch (Exception $e) {
        $Test2Model->rollback();
        throw $e;
        //return false;
    }
}


try {
    $Test1Model->begin();
    
    $ret = $Test1Model->insert([
        'name' => 'aaaaaa'
    ]);
    $ret2 = addTest2(false);
    var_dump($ret, $ret2);
    if ($ret && $ret2) {
        $Test1Model->commit();
    }else {
        $Test1Model->rollback();
    }
} catch (Exception $e) {
    //addTest2(1);
    $Test1Model->rollback();
    throw $e;
}

 

 

 function x1()
  {
    $x1 = db1("x1", 1);
    $x2 = db2("x2");
    $x1->startTrans();
    try {
      $x1->find();
      $ret1 = $x1->where(['id' => 1])->update(['title' => "x1_11"]);
      if($ret1){
        $x2->startTrans();
        try {
          $x2->find();
          $ret2 = $x2->where(['id' => 1])->update(['title' => "x1_111"]);
          if ($ret1 && $ret2) {
            dump(1);
            $x1->commit();
            $x2->commit();
          }else{
            dump(2);
            $x1->rollback();
            $x2->rollback();
          }
        } catch (\Exception $e) {
          // 回滚事务
          dump(3);
          $x1->rollback();
          $x2->rollback();
          echo "x2 : " . $e->getMessage();
        }
      }else{
        dump(4);
        $x1->rollback();
      }
    } catch (\Exception $e) {
      // 回滚事务
      dump(5);
      $x1->rollback();
      echo "x1 : " . $e->getMessage();
    }
  }

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【PHP】mysql嵌套事物

Continue Read..

公司的一个项目需要在一个函数里面的调用多个函数,但是每个函数都用到了mysql事物,按照原生的mysql事物,只有一层

也就是说 A函数包含了B函数,如果B函数事物成功,A再没有commit的时候也能提交事物,这样就不对了

 

直接上代码

 

写一个class

定义一个静态变量

//事物laravel

static private $transactions = 0;

 

public function begin() {
        ++self::$transactions;
        if (self::$transactions == 1) {
            $sql = 'BEGIN';
            $conn = $this->getMasterConn();
            
            return DBMysqli::execute($conn, $sql);
        }
	}

	/**
	 * 提交事务
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function commit() {
        if (self::$transactions == 1) {
            $sql = 'COMMIT';
            $conn = $this->getMasterConn();
            
            return DBMysqli::execute($conn, $sql);
        }
        --self::$transactions;
	}

	/**
	 * 回滚事务
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function rollback() {
        if (self::$transactions == 1) {
            self::$transactions = 0;
            $sql = 'ROLLBACK';
            $conn = $this->getMasterConn();
    
            return DBMysqli::execute($conn, $sql);
        } else {
            --self::$transactions;
        }
	}

参考网站 https://blog.csdn.net/hello_katty/article/details/45220825

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【PHP】php 返回数组中指定多列的方法

Continue Read..
function array_columns($input, $column_keys=null, $index_key=null){ $result = array(); $keys =isset($column_keys)? explode(',', $column_keys) : array(); if($input){ foreach($input as $k=>$v){ // 指定返回列 if($keys){ $tmp = array(); foreach($keys as $key){ $tmp[$key] = $v[$key]; } }else{ $tmp = $v; } // 指定索引列 if(isset($index_key)){ $result[$v[$index_key]] = $tmp; }else{ $result[] = $tmp; } } } return $result; }

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【php】excel导出分sheet

Continue Read..
    /**
     * 导出export 生成多个sheet
     * $data = [
     *      'sheet1'=>[
     *          'header'=>['k'=>v],
     *          'date'=>['k'=>v],
     *      ]
     *      'sheet2'=>[
     *          'header'=>['k'=>v]
     *          'data'=>['k'=>v]
     *      ]
     * ]
     * header和data 用k 关联
     * @param unknown $data
     * @param string $user
     * @param string $format
     * @param string $title
     * @return multitype:mixed
     */  
    public function multiExportSheet($data, $user = 'admin', $format = false, $title = ''){
        require_once __DIR__.'/PHPExcel.php';
        $objPHPExcel = new \PHPExcel();
        $j = 0;
        foreach ($data as $dk=>$dv){
            if($j==0){
                $objPHPExcel->setActiveSheetIndex($j); //设置第一个工作表为活动工作表
                $objPHPExcel->getActiveSheet()->setTitle($dk); //设置工作表名称
            }else{
                $msgWorkSheet = new \PHPExcel_Worksheet($objPHPExcel, $dk); //创建一个工作表
                $objPHPExcel->addSheet($msgWorkSheet); //插入工作表
                $objPHPExcel->setActiveSheetIndex($j); //切换到新创建的工作表
            }
            
            $arrHeader = $dv['header'];
            $arrBody = $dv['data'];
            $newdata = [];
            
            $i = 0;
            foreach ($arrBody as $k=>$v){
                foreach ($arrHeader as $kk=>$vv){
                    if(!empty($v[$kk])){
                        if($kk == 'idcard' || $kk == 'bank_card'){
                            $newdata[$i][$kk] = $v[$kk]."\t";
                        }else{
                            $newdata[$i][$kk] = $v[$kk];
                        }
                    }else{
                        $newdata[$i][$kk] = "";
                    }
                }
                $i++;
            }
            $hd[0] = $arrHeader;
            $arrExcelInfo = array_merge($hd, $newdata);
            $objPHPExcel->getActiveSheet()->fromArray(
                $arrExcelInfo, // 赋值的数组
                NULL, // 忽略的值,不会在excel中显示
                'A1' // 赋值的起始位置
            );
            
            unset($arrExcelInfo);
            unset($hd);
            unset($arrHeader);
            unset($arrBody);
            unset($newdata);
            $j++;
        }
        
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    
        $result=[];
        $path = 'down/'.md5($user.'down').'/';
        $rootPath = $this->mkdirPath($path);
        $date = date('YmdHis');
    
        $title = $date.rand(10000,99999);
        $outputFileName = $rootPath.$title.".xlsx";
        $objWriter->save($outputFileName);
        $result[]= str_replace(APP_PATH, '', $outputFileName);
        return $result;
    }


声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权