树莓派编译安装PHP7.4

首先安装依赖

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

下载源码并编译安装

wget https://www.php.net/distributions/php-7.4.15.tar.gz
tar zxf php-7.4.15.tar.gz
cd php-7.4.15

./configure \
--prefix=/usr/local/php \
--with-curl --with-freetype --with-gettext --with-iconv-dir --with-jpeg --with-libdir=lib64 --with-openssl --with-pear --with-readline --with-xmlrpc --with-zip --with-zlib \
--with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd \
--enable-bcmath --enable-calendar --enable-exif --enable-fpm --enable-ftp --enable-gd --enable-intl --enable-mbstring --enable-mysqlnd --enable-pcntl \
--enable-soap --enable-sockets
make -j8 && 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

树莓派自动解析IPV6地址

自动解析树莓派的 IPV6 地址到某个域名

<?php

// 调试模式
define('DebugModel', false);

// 域名
define('Domain', 'device.raspberrypi.org');

// Clouflare API 地址
define('ClouflareApiBase', 'https://api.cloudflare.com/client/v4');

// Clouflare API 密钥
define('ClouflareAuthKey', 'ClouflareAuthKey');

/**
 *  获取本机 IPV6 地址
 */
function getIPV6()
{
    if (!file_exists('/proc/net/if_inet6')) {
        throw new Exception("Get IPV6 Failed!");
    }
    $_ipv6 = explode(" ", file_get_contents('/proc/net/if_inet6'))[0];
    debug('Getting IPV6');
    return implode(':', str_split($_ipv6, 4));
}

/**
 *  获取顶级域名
 */
function getMainDomain($domain)
{
    $_domain = explode('.', $domain);
    $domain = [];
    $domain[] = array_pop($_domain);
    $domain[] = array_pop($_domain);
    debug('Getting Main Domain');
    return $domain[1] . '.' . $domain[0];
}

/**
 *  获取域名 Zone ID
 */
function getZoneID($domain)
{
    $mainDomain = getMainDomain($domain);
    $url = sprintf('%s/zones', ClouflareApiBase);
    debug('Send ZoneID Request');
    $dns = json_decode(httpRequest('GET', $url));
    debug('Get ZoneID Response');
    if (isset($dns->result)) {
        foreach ($dns->result as $v) {
            if ($v->name === $mainDomain) {
                return $v->id;
            }
        }
    } else {
        throw new Exception("Get ZoneID Failed!");
    }
}

/**
 *  获取域名 Record
 */
function getRecord($zoneID, $domain, $type = 'A')
{
    $url = sprintf('%s/zones/%s/dns_records', ClouflareApiBase, $zoneID);
    debug('Send RecordID Request');
    $dns = json_decode(httpRequest('GET', $url));
    debug('Get RecordID Response');
    if (isset($dns->result)) {
        foreach ($dns->result as $v) {
            if ($v->name === $domain && $v->type === $type) {
                return $v;
            }
        }
    }
    return false;
}

/**
 *  新增域名解析
 */
function setRecord($zoneID, $domain, $ipv6)
{
    $data = array(
        'name' => $domain,
        'type' => 'AAAA',
        'content' => $ipv6,
        'ttl' => 120
    );
    $url = sprintf('%s/zones/%s/dns_records', ClouflareApiBase, $zoneID);
    $response = json_decode(httpRequest('POST', $url, json_encode($data)));
    if (isset($response->result->id)) {
        return true;
    } else {
        return false;
    }
}

/**
 *  更新域名解析
 */
function updateRecord($zoneID, $recordID, $domain, $ipv6)
{
    $data = array(
        'name' => $domain,
        'type' => 'AAAA',
        'content' => $ipv6,
        'ttl' => 120
    );
    $url = sprintf('%s/zones/%s/dns_records/%s', ClouflareApiBase, $zoneID, $recordID);
    $response = json_decode(httpRequest('PUT', $url, json_encode($data)));
    if (isset($response->result->id)) {
        return true;
    } else {
        return false;
    }
}

/**
 *  发起 HTTP 请求
 */
function httpRequest($method = 'GET', $url, $post = '')
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . ClouflareAuthKey, 'Content-Type: application/json']);

    if ($method !== 'GET') {
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    }

    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);

    if ($error) {
        throw new Exception($error);
    } else {
        return $data;
    }
}

function debug($log)
{
    if (DebugModel) {
        $file = '/tmp/dns.log';
        $log = date('Y-m-d H:i:s') . "\t" . $log . "\n";
        echo $log;
        file_put_contents($file, $log, FILE_APPEND);
    }
}

function main($domain)
{
    $ipv6 = getIPV6();
    $zoneID = getZoneID($domain);
    $record = getRecord($zoneID, $domain, 'AAAA');
    if (isset($record->id)) {
        if ($record->content !== $ipv6) {
            debug('Update IPV6 Record');
            $update = updateRecord($zoneID, $record->id, $domain, $ipv6);
        } else {
            return debug('No Change IPV6 Record');
        }
    } else {
        debug('New IPV6 Record');
        $update = setRecord($zoneID, $domain, $ipv6);
    }
    if ($update) {
        debug('DNS Record Update Success!');
    } else {
        debug('DNS Record Update Failed!');
    }
}

main(Domain);

Hyperf 环境配置和安装

安装 PHP 环境

# PHP 7.3.19
# Swoole 4.5.2
# Composer 1.10.10

配置阿里云镜像源

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

安装 Hyperf

composer create-project hyperf/hyperf-skeleton

Docker 方式安装

docker run -v D:\wamp\www\html\hyperf:/hyperf-skeleton -p 9501:9501 -it --entrypoint /bin/sh hyperf/hyperf:latest
发布于
归类为php

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')
        ],
    ]
]);
发布于
归类为php

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
发布于
归类为php

Git 常用配置参数

Windows 开发环境:

# 忽略路径中的转义字符

git config --global core.protectNTFS false

# 禁用换行符转换

git config --global core.autocrlf false

发布于
归类为Linux

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
	}
}
发布于
归类为Linux

树莓派编译安装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
发布于
归类为Linux