分类目录归档:PHP

composer require 慢的解决办法

使用composer镜像

使用aliyun镜像

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

禁止安装时更新

composer require 添加 --no-update 参数

composer require packagename --no-update

PHP7.3 zts(线程安全)编译以及多线程(pthreads)使用

下载PHP

下载地址:https://www.php.net/downloads.php,开始下载:

su root
mkdir tmp
cd tmp
wget https://www.php.net/distributions/php-7.3.7.tar.bz2

编译安装PHP开启线程安全

tar -jxvf php-7.3.7.tar.bz2
cd php-7.3.7
yum -y install libxml2 libxml2-devel openssl openssl-devel curl-devel libjpeg-devel libpng-devel freetype-devel libicu-devel

编译

./configure \
--prefix=/usr/local/php-7.3.7-ts \
--enable-maintainer-zts \
--enable-fpm \
--with-fpm-user=www \
--with-fpm-group=www \
--enable-bcmath \
--enable-exif \
--enable-intl \
--enable-mbstring \
--enable-pcntl \
--with-pdo-mysql \
--enable-sockets \
--enable-mysqlnd \
--with-gd

然后:

make && make install

更新autoconf

Autoconf version 2.68 or higher is required错误是才需要此步骤

wget http://ftp.gnu.org/gnu/autoconf/autoconf-latest.tar.gz
tar -zxvf autoconf-latest.tar.gz 
cd autoconf-2.69/
.configure
make
make install
autoconf --version 

安装pthreads

git clone https://github.com/krakjoe/pthreads.git
cd pthreads
/usr/local/php-7.3.7-ts/bin/phpize
./configure --with-php-config=/usr/local/php-7.3.7-ts/bin/php-config
make
make install

修改 /usr/local/php-7.3.7-ts/lib/php.ini,增加 extension=pthreads

测试pthreads

/usr/local/php-7.3.7-ts/bin/php worker.php

<?php

class MyWorker extends Worker
{
    public $id;
    public $time;

    public function __construct($id, $time)
    {
        $this->id = $id;
        $this->time = $time;
    }

    public function run()
    {
        while (true) {
            echo sprintf(worker %s is running, %s\n, $this->id, date('Y-m-d H:i:s'));
            sleep($this->time);
        }
    }
}

class MyManager
{
    /**
     * @var MyWorker[]
     */
    protected $workers;

    public function add(MyWorker $work)
    {
        $this->workers[$work->id] = $work;
        echo 'add worker' . $work->id . \n;
    }

    public function run()
    {
        foreach ($this->workers as $id => $work) {
            echo 'run worker' . $work->id . \n;
            $work->start();
        }
    }
}

$manager = new MyManager();
$manager->add(new MyWorker('1', 1));
$manager->add(new MyWorker('2', 3));
$manager->run();

Imagick给图片加文字和二维码

    // 初始化画布
    set_time_limit(0);
    $bg_file = Yii::getAlias('@frontend/web/test/wxbg.jpg');
    $image = new \Imagick($bg_file);

    // 写字
    $font_file = Yii::getAlias('@frontend/web/test/msyhbd.ttc');
    $draw = new \ImagickDraw();
    $draw->setFillColor('#FF7F24');
    $draw->setFont($font_file);
    $draw->setFontSize(64);
    $draw->setTextKerning(5);
    $draw->setFontWeight(700);
    $draw->setTextEncoding('UTF-8');
    $metrics = $image->queryFontMetrics($draw, $name);
    $draw->annotation(158, 50 + $metrics['ascender'], $name);
    $image->drawImage($draw);

    // 二维码
    $qr_image = new \Imagick(Yii::getAlias('@frontend/web/test/qr.png'));
    $qr_image->scaleImage(248, 248);
    $image->compositeImage($qr_image, \Imagick::COMPOSITE_COPY, 254, 504);

    // 返回
    $response = Yii::$app->getResponse();
    $response->format = Response::FORMAT_RAW;
    $response->headers->set('Content-Type', 'image/jpeg');
    $response->data = $image->getImageBlob();
    return $response->send();

Yii2按需加载js,css文件,并自动加上时间戳

网上找遍了国内和国外的资料,没有能够为动态增加的文件加上时间戳的,进过分析Yii2源码,发现其实非常简单:

开启assetManager支持自动加上时间戳

修改main.php

    'assetManager' => [
        'appendTimestamp' => true,
    ],

视图层按需加载js,css

$bundle=AppAsset::register($this);
$bundle->js[]='js/windowview.js';
$bundle->css[]='css/robot.css';

yii gridview 使用target=”_blank”无效

解决办法是设置format为raw:

        [
            'attribute' => 'attribute',
            'format' => 'raw',
            'value' => function ($model, $key, $index, $column) {
                return  Html::a($model->title, ['view', 'id' => $model->id], ['target' => '_blank']);
            },
        ],

Yii2设置变量到布局layout

通过全局params配置

Yii::$app->params['myVar']

通过session

Yii::app()->session['myvar']

或者通过Flash Message

通过控制器传递变量方式

首先,需要再控制器添加参数

class SiteController extends CController {

    public $myvar;
//...

然后在layout/main.php获取控制器变量

$this->context->myvar
Yii::$app->controller->myvar

Yii2 文件上传扩展

官方指南

aminkt/yii2-upload-manager

Upload manager system based and inspired from WordPress upload manager.

yii2-image-manager

A module/widget for upload, manage and cropping images

yii2-attachments

Extension for file uploading and attaching to the models

yii2-widget-fileinput

An enhanced FileInput widget for Bootstrap 3.x with file preview, multiple selection, and more features

yii2-file-input-widget

Jasny File Input Bootstrap Widget + Local and Remote storage

yii2-file-upload

PHP library for uploading files to your server or Amazon S3

yii2-upload-file

Yii2 tools for upload file

给Yii composer提速

Yii 2 的 2.1x版本后,采用asset-packagist.org给bower提速,效果明显,旧版本Yii要升级到新版本可以采用以下步骤:

修改 composer.json

  "config": {
    "process-timeout": 1800,
    "fxp-asset": {
      "enabled": false
    }
  },
  "repositories": [
    {
      "type": "composer",
      "url": "https://asset-packagist.org"
    }
  ]

修改config/main.php

'aliases' => [
    '@bower' => '@vendor/bower-asset',
    '@npm'   => '@vendor/npm-asset',
],

清理composer并运行

composer clear-cache
composer install

解决nginx+php/java/go/python+mysql下time_wait连接数过多问题

公司服务器连接数超过10K了,查了下大多数是没有即时回收,采用tcp复用容易后程序出现了故障,以前一直看到说PHP持久连接有问题,所以没怎么用,最近有机会试了下。

非常香,连接数直接降低到几百了,目前观察数周没有问题。

查看连接数

netstat -n |  wc -l # 总连接数
netstat -n | grep -i time_wait | wc -l # time_wait 连接数
netstat -anp # 查看占用端口过多的程序

tcp复用解决方案

网上大部分解决方案是修改sysctl.conf回收重用ipv4连接,但是可能带来其他问题

net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_timestamps=1
net.ipv4.tcp_tw_reuse=1
net.ipv4.tcp_tw_recycle=1
net.ipv4.tcp_fin_timeout=30
net.ipv4.tcp_keepalive_time = 600

nginx fastcgi(php) 解决方案

修改nginx.conf

upstream fastcgi_backend {
    server 127.0.0.1:9000;
    keepalive 60;
}

location ~ \.php$ {
        fastcgi_pass  fastcgi_backend;
        fastcgi_keep_conn on;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
}

主要是 fastcgi_keep_conn onupstreamkeepalive

nginx + proxy (python/go/java) 解决方案

upstream wxpic {
    keepalive 60;
    server 127.0.0.1:xxx;
}

server {
    keepalive_requests 10000; # 默认100
    location / {
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

主要是 proxy_http_version, proxy_set_header Connection ""以及keepalive_requests

mysql数据库连接解决方案

修改yii数据库配置采用长链接

'db' => [ 
    'class' => 'yii\db\Connection',
    'dsn' => '*', 'username' => '*', 
    'password' => '*', 
    'charset' => 'utf8mb4', 
    'attributes' => [ 
       PDO::ATTR_PERSISTENT => true 
    ]
],

redis 连接数

php redis连接数过多解决办法(Yii,predis,phpredis等)

Yii2 composer安装慢的解决办法

修改fxp-asset为Asset Packagist

参考官方安装指南Yii advanced template installation提到:

It uses asset-packagist for managing bower and npm package dependencies through Composer. Also you can use asset-plugin, as in earlier versions, but it works slowly.

找到

"config": {
    "process-timeout": 1800,
    "fxp-asset":{
        "installer-paths": {
            "npm-asset-library": "vendor/npm",
            "bower-asset-library": "vendor/bower"
        }
    }
},
"replace": {
    "bower-asset/jquery": ">=1.11.0",
    "bower-asset/inputmask": ">=3.2.0",
    "bower-asset/punycode": ">=1.3.0",
    "bower-asset/yii2-pjax": ">=2.0.0"
}

修改为

"config": {
    "process-timeout": 1800,
    "fxp-asset": {
        "enabled": false
    }
},
"repositories": [
    {
        "type": "composer",
        "url": "https://asset-packagist.org"
    }
]

修改config/main.php

'aliases' => [
    '@bower' => '@vendor/bower-asset',
    '@npm'   => '@vendor/npm-asset',
],

Asset Packagist介绍

from https://asset-packagist.org/

Composer + Bower + NPM = friends forever!

This repository allows installation of Bower and NPM packages as native Composer packages.

NO plugins and NO Node.js are required.

At the moment we’ve added most popular Bower and NPM packages 4000+ each.

In case Composer fails to install some asset package, use the search line at the top of the page to check specific package health.

For NPM scoped packages use scope--package instead of @scope/package, e.g. npm-asset/pusher--chatkit.

Got tired of fxp/composer-asset-plugin.

Why Asset Packagist

Got tired of fxp/composer-asset-plugin.

It’s a good project with nice idea and good implementation. But it has some issues: it slows down composer update a lot and requires global installation, so affects all projects. Also there are Travis and Scrutinizer integration special problems, that are a bit annoying.