Guzzle 使用文档

安装

composer require guzzlehttp/guzzle:7.0.1

发起 Get 请求

use GuzzleHttp\Client as guzzleClient;

$guzzleClient = new guzzleClient([
    'timeout' => 2.0
]);

// 同步请求方式
$response = $guzzleClient->get('http://api.org/get', ['headers' => ['User-Agent' => 'Guzzle'], 'http_errors' => false]);
$code = $response->getStatusCode();
$body = $response->getBody();
$content = $body->getContents();
// 异步请求方式
$promise = $guzzleClient->getAsync('http://api.org/get');
$promise->then(
    function (ResponseInterface $res) {
        echo $res->getStatusCode() . "\n";
    },
    function (RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);

发起 Post 请求

use GuzzleHttp\Client as guzzleClient;

$guzzleClient = new guzzleClient([
    'timeout' => 2.0
]);

// 原始类型
$response = $guzzleClient->post('http://api.org/post', [
    'body' => 'raw data'
]);

// json 类型 application/json
$response = $guzzleClient->post('http://api.org/post', [
    'json' => ['name' => 'admin']
]);

// 表单类型 application/x-www-form-urlencoded
$response = $guzzleClient->post('http://api.org/post', [
    'form_params' => [
        'username' => 'abc',
        'password' => '123'
    ]
]);

// 上传文件 multipart/form-data
$response = $guzzleClient->post('http://api.org/post', [
    'multipart' => [
        [
            'name'     => 'user',
            'contents' => 'admin'
        ],
        [
            'name'     => 'file',
            'contents' => fopen('/path/to/file', 'r')
        ],
    ]
]);

EasySwoole环境和框架安装

安装 PHP 环境

# PHP 7.3.19
# Swoole 4.5.2
# Composer 1.10.10

配置阿里云镜像源

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

安装 EasySwoole

composer require easyswoole/easyswoole=3.3.7
php vendor/easyswoole/easyswoole/bin/easyswoole install
composer dump-autoload

安装 RPC 组件

composer require easyswoole/rpc=4.0.10

启动 EasySwoole

php easyswoole start

Git 常用配置参数

Windows 开发环境:

# 忽略路径中的转义字符

git config --global core.protectNTFS false

# 禁用换行符转换

git config --global core.autocrlf false

CentOS7自动添加防火墙白名单

自动添加某域名对应的IP地址到防火墙里,允许此IP访问SSH服务

package main

import (
	"fmt"
	"net"
	"os/exec"
	"strings"
)

func main() {
	ip, err := net.ResolveIPAddr("ip4", "test.com")
	if err != nil {
		return
	}
	command, err := exec.Command("bash", "-c", "firewall-cmd --list-all").Output()
	if err != nil {
		return
	}
	if strings.Contains(string(command), ip.String()) {
		return
	}
	comm := `firewall-cmd --add-rich-rule='rule family="ipv4" source address="` + ip.String() + `" port port="22" protocol="tcp" accept'`
	_, err = exec.Command("bash", "-c", comm).Output()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
}

树莓派编译安装PHP7.3

首先安装依赖

apt install -y libxml2 libxml2-dev libjpeg-dev libcurl4-openssl-dev libreadline-dev libzip-dev libfreetype6-dev

下载源码并安装

wget https://www.php.net/distributions/php-7.3.15.tar.gz
tar zxf php-7.3.15.tar.gz
cd php-7.3.15
./configure \
--prefix=/usr/local/php \
--with-apxs2=/usr/local/apache/bin/apxs \
--with-curl --with-gettext --with-iconv-dir --with-gd --with-jpeg-dir --with-openssl --with-openssl-dir=/usr/local/openssl --with-pear --with-readline --with-xmlrpc --with-zlib \
--with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd \
--enable-bcmath --enable-calendar --enable-exif --enable-fpm --enable-ftp --enable-intl --enable-mbstring --enable-mysqlnd \
--enable-soap --enable-sockets --enable-zip
make -j4 && make install

配置文件

cp php.ini-production /usr/local/php/lib/php.ini
sed -i 's/post_max_size = 8M/post_max_size = 50M/g' /usr/local/php/lib/php.ini
sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 50M/g' /usr/local/php/lib/php.ini
sed -i 's/;date.timezone =/date.timezone = PRC/g' /usr/local/php/lib/php.ini
sed -i 's/expose_php = On/expose_php = Off/g' /usr/local/php/lib/php.ini

配置 Apache 支持 PHP

echo "AddType application/x-httpd-php .php" >> /usr/local/apache/conf/httpd.conf

增加软连接

ln -s /usr/local/php/lib/php.ini /etc/php.ini
ln -s /usr/local/php/bin/php /usr/local/bin/
ln -s /usr/local/php/bin/phpize /usr/local/bin/
ln -s /usr/local/php/bin/pecl /usr/local/bin/
ln -s /usr/local/php/bin/php-config /usr/local/bin/

树莓派编译安装Apache2.4

首先安装基础依赖库

apt install libpcre3 libpcre3-dev libssl-dev libexpat1-dev

下载源码并安装

cd /usr/local/src
wget http://mirrors.tuna.tsinghua.edu.cn/apache//httpd/httpd-2.4.41.tar.gz
wget https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-1.7.0.tar.gz
wget https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-util-1.6.1.tar.gz
tar zxf httpd-2.4.41.tar.gz
tar zxf apr-1.7.0.tar.gz
tar zxf apr-util-1.6.1.tar.gz
mv apr-1.7.0 httpd-2.4.41/srclib/apr
mv apr-util-1.6.1 httpd-2.4.41/srclib/apr-util
cd httpd-2.4.41
./configure \
--prefix=/usr/local/apache \
--enable-so --enable-mime-magic --enable-rewrite --enable-deflate \
--with-included-apr --with-mpm=prefork \
--disable-autoindex --disable-status --disable-env --disable-alias --disable-version
make -j4 && make install

修改配置文件

sed -i 's/^#ServerName www.example.com:80/ServerName localhost:80/' /usr/local/apache/conf/httpd.conf
sed -i 's/^#LoadModule expires_module/LoadModule expires_module/' /usr/local/apache/conf/httpd.conf
sed -i 's/^#LoadModule rewrite_module/LoadModule rewrite_module/' /usr/local/apache/conf/httpd.conf
sed -i 's/^#LoadModule deflate_module/LoadModule deflate_module/' /usr/local/apache/conf/httpd.conf

增加软连接

ln -s /usr/local/apache/conf/httpd.conf /etc/
ln -s /usr/local/apache/conf/extra/httpd-vhosts.conf /etc/
ln -s /usr/local/apache/bin/apachectl /usr/local/sbin/

启动 Apache

apachectl

完整脚本

apt update
apt install -y libpcre3-dev libexpat1-dev

# 下载源码
wget https://mirrors.tuna.tsinghua.edu.cn/apache//httpd/httpd-2.4.41.tar.gz
wget https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-1.7.0.tar.gz
wget https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-util-1.6.1.tar.gz

# 解压
tar zxf httpd-2.4.41.tar.gz
tar zxf apr-1.7.0.tar.gz
tar zxf apr-util-1.6.1.tar.gz
mv apr-1.7.0 httpd-2.4.41/srclib/apr
mv apr-util-1.6.1 httpd-2.4.41/srclib/apr-util

# 编译安装
cd httpd-2.4.41
./configure \
--prefix=/usr/local/apache \
--enable-so --enable-mime-magic --enable-rewrite --enable-deflate --enable-ssl \
--with-ssl=/usr/local/openssl \
--with-included-apr --with-mpm=prefork \
--disable-autoindex --disable-status --disable-env --disable-alias --disable-version
make -j4 && make install

# 修改Apache配置文件
sed -i 's/^#ServerName www.example.com:80/ServerName localhost:80/' /usr/local/apache/conf/httpd.conf
sed -i 's/^#LoadModule expires_module/LoadModule expires_module/' /usr/local/apache/conf/httpd.conf
sed -i 's/^#LoadModule rewrite_module/LoadModule rewrite_module/' /usr/local/apache/conf/httpd.conf
sed -i 's/^#LoadModule deflate_module/LoadModule deflate_module/' /usr/local/apache/conf/httpd.conf
sed -i 's/^#Include conf\/extra\/httpd-vhosts.conf/Include conf\/extra\/httpd-vhosts.conf/' /usr/local/apache/conf/httpd.conf
sed -i 's/DirectoryIndex index.html/DirectoryIndex index.php index.html index.htm/g' /usr/local/apache/conf/httpd.conf

# 配置虚拟主机
mkdir /www/html -p
cat > /usr/local/apache/conf/extra/httpd-vhosts.conf<<EOF

<VirtualHost *:80>
    DocumentRoot "/usr/local/apache/htdocs"
    ServerName localhost
</VirtualHost>

<Directory "/www/">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<VirtualHost *:80>
    DocumentRoot "/www/html"
    ServerName localhost
    ErrorLog "logs/error.log"
    CustomLog "logs/access.log" common
</VirtualHost>

EOF

# Apache安全设置
echo "ServerTokens Prod" >> /usr/local/apache/conf/httpd.conf
echo "TraceEnable off" >> /usr/local/apache/conf/httpd.conf

# 创建Apache配置文件快捷方式
ln -s /usr/local/apache/bin/httpd /usr/local/bin/
ln -s /usr/local/apache/bin/apachectl /usr/local/bin/
ln -s /usr/local/apache/conf/httpd.conf /etc/httpd.conf
ln -s /usr/local/apache/conf/extra/httpd-vhosts.conf /etc/vhosts.conf

Linux取消自动绑定ipv4端口

目前比较新的 Linux 发行版都有一个默认配置,就是在同时支持 IPV4 和 IPV6 的服务器上,监听 IPV6 地址端口的时候,系统会自动监听对应的 IPV4 端口。

# 查看 bindv6only 的值
cat /proc/sys/net/ipv6/bindv6only 

默认为0,就是自动绑定 IPV4 和 IPV6

取消自动绑定

sysctl -w net.ipv6.bindv6only=1
echo "net.ipv6.bindv6only = 1" >> /etc/sysctl.d/net-sysctl.conf

PHP实现Base16编码算法

我们经常使用的 Base64 编码用来对字符串或者字节数组进行编码转换,以方便存储。可是Base64 编码的结果可能会带有特殊字符,应用场景有限。

而 Base16 编码生成的结果是用[0-9A-F]十六个字符表示,可以用来生成字符索引和文件名等,应用范围比 Base64 要大的多。

缺点的话 Base16 编码的结果字符串比 Base64 编码的结果字符串要长, Base64 大概是1.3倍长,而 Base16 是原长度的两倍。

Base16 编码的原理是先获取字符串每个字节的二进制值,高位用0补充到8位。然后每4比特分割成一组,每组的二进制值转换成十进制,然后再对应到[0-9A-F],对应的结果就是编码的值。

PHP 官方并没有 Base16 的编码实现,使用下面的函数就可以实现Base16的编码和解码。

function base16_encode($string)
{
    $encode = '';
    $chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
    for ($i = 0; $i < strlen($string); $i++) {
        $encode .= $chars[(ord($string[$i]) & 0b11110000) >> 4] . $chars[ord($string[$i]) & 0b00001111];
    }
    return $encode;
}

function base16_decode($encode)
{
    $result = '';
    for ($i = 0; $i < strlen($encode) / 2; $i++) {
        $result .= chr(intval(substr($encode, $i * 2, 2), 16));
    }
    return $result;
}

MacOS编译安装nginx

#!/bin/bash

curl -O http://nginx.org/download/nginx-1.16.1.tar.gz
tar zxf nginx-1.16.1.tar.gz

curl -O http://zlib.net/zlib-1.2.11.tar.gz
tar zxf zlib-1.2.11.tar.gz

curl -O https://ftp.pcre.org/pub/pcre/pcre-8.44.tar.gz
tar zxf pcre-8.44.tar.gz

cd nginx-1.16.1
sed -i '' 's/CFLAGS="$CFLAGS -g"/# CFLAGS="$CFLAGS -g"/g' auto/cc/gcc
./configure --prefix=/usr/local/nginx \
--with-zlib=../zlib-1.2.11 --with-pcre=../pcre-8.44
--with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-http_sub_module \
--with-stream --with-stream_ssl_module --with-http_v2_module \
--with-http_mp4_module --with-http_secure_link_module --with-http_auth_request_module
make
sudo make install