使用阿里云API管理域名解析


define('AccessKeyId', 'AccessKeyId');
define('AccessKeySecret', 'AccessKeySecret');

date_default_timezone_set('UTC');

/**
 *  获取请求签名
 */
function getSign($add)
{
    $nonce = time() . rand(11111, 99999);
    $time = date('Y-m-d') . 'T' . date('H:i:s') . 'Z';
    $data = array(
        'AccessKeyId' => AccessKeyId,
        'Format' => 'json',
        'SignatureMethod' => 'HMAC-SHA1',
        'SignatureNonce' => $nonce,
        'SignatureVersion' => '1.0',
        'Timestamp' => $time,
        'Version' => '2015-01-09',
    );
    $data = array_merge($data, $add);
    ksort($data);
    $format = http_build_query($data);
    $signUrl = 'GET&%2F&' . urlencode($format);
    $sign = urlencode(base64_encode(hash_hmac('sha1', $signUrl, AccessKeySecret . '&', true)));
    return array('url' => $format, 'sign' => $sign);
}

/**
 *  获取域名列表
 */
function getDomains()
{
    $sign = getSign(['Action' => 'DescribeDomains']);
    $url = 'https://alidns.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
    $data = json_decode(httpRequest($url));
    if (isset($data->Domains)) {
        return $data;
    } else {
        return false;
    }
}

/**
 *  获取域名解析记录
 */
function getDomainRecords($domain)
{
    $sign = getSign(['Action' => 'DescribeDomainRecords', 'DomainName' => $domain]);
    $url = 'https://alidns.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
    $data = json_decode(httpRequest($url));
    if (isset($data->DomainRecords)) {
        return $data;
    } else {
        return false;
    }
}

/**
 *  获取子域名解析记录
 */
function getSubDomainRecords($domain)
{
    $sign = getSign(['Action' => 'DescribeSubDomainRecords', 'SubDomain' => $domain]);
    $url = 'https://alidns.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
    $dns = json_decode(httpRequest($url));
    if (isset($dns->DomainRecords)) {
        return $dns;
    } else {
        return false;
    }
}

/**
 *  更新域名解析
 */
function updateSubDomainRecords($id, $name, $ip)
{
    $data = array(
        'Action' => 'UpdateDomainRecord',
        'RecordId' => $id,
        'RR' => $name,
        'Type' => 'A',
        'Value' => $ip,
    );
    $sign = getSign($data);
    $url = 'https://alidns.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
    return httpRequest($url);
}

/**
 *  发起 HTTP 请求
 */
function httpRequest($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);
    if ($error) {
        return $error;
    } else {
        return $data;
    }
}
发布于
归类为php

使用Google API获取谷歌相册的内容

首先要申请一个谷歌 Oauth2 应用的 ID 和密钥,然后用浏览器访问下面的地址获取授权码 code

https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http://localhost&response_type=code&client_id={ClientID}&scope=https://www.googleapis.com/auth/photoslibrary+https://www.googleapis.com/auth/drive&access_type=offline

获取到 code 以后,请求谷歌服务器换取 refresh_token

define('Client_ID', 'client_id');
define('Client_Secrec', 'client_secrec');

function getRefreshToken($code) {
    $params = ['grant_type' => 'authorization_code', 'code' => $code, 'client_id' => Client_ID, 'client_secret' => Client_Secrec, 'redirect_uri' => 'http://localhost'];
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v4/token');
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

用 refresh_token 获取 access_token

function getAccessToken($refresh_token) {
    $params = ['grant_type' => 'refresh_token', 'client_id' => 'client_id', 'client_secret' => 'client_secre', 'refresh_token' => $refresh_token];
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v4/token');
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}
发布于
归类为php

获取Google Oauth2 JWT签名

首先获取服务账号密钥文件 google-gce.json

use Google\Auth\OAuth2;

require 'vendor/autoload.php';

function getGoogleJWT($scopes, $jsonKey) {
    $jsonKey = json_decode(file_get_contents($jsonKey), true);
    $config = [
        'audience' => 'https://oauth2.googleapis.com/token',
        'issuer' => $jsonKey['client_email'],
        'scope' => $scopes,
        'signingAlgorithm' => 'RS256',
        'signingKey' => $jsonKey['private_key'],
        'sub' => NULL,
        'tokenCredentialUri' => 'https://oauth2.googleapis.com/token'
    ];
    $auth = new OAuth2($config);
    return $auth->toJWT();
}

$scopes = ['https://www.googleapis.com/auth/drive.readonly'];

echo getGoogleJWT($scopes, 'google-gce.json');

然后用 JWT 签名就可以获取 Access Token 密钥,有效期为一小时

function getAccessToken($jwt) {
    $params = ['grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwt];
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

$jwt = 'JWT';

echo getAccessToken($jwt);
发布于
归类为php

Cmder添加右键菜单,在指定目录打开

Cmder 是一个 Windows 平台下非常好用的终端软件,支持 Tab 自动完成等高级功能。默认打开 Cmder 的时候终端是在安装目录,如果想要在任意目录右键直接打开 Cmder ,就需要修改注册表。

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\cmder]
@="Cmder Here"
"NoWorkingDirectory"=""
"Icon"="D:\\Soft\\cmder\\icons\\cmder.ico"

[HKEY_CLASSES_ROOT\Directory\Background\shell\cmder\command]
@="\"D:\\Soft\\cmder\\Cmder.exe\" \"%V\""

将以上内容保存为 cmder.reg 文件,然后修改安装路径,双击执行就可以了。

发布于
归类为Windows

PHP独立使用Illuminate Database数据库组件

1 安装

composer require illuminate/database
composer require illuminate/events
composer require illuminate/container

2 使用

use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;

require 'vendor/autoload.php';

$capsule = new DB;

$capsule->addConnection([
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'test',
    'username'  => 'root',
    'password'  => '123456',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
]);

$capsule->setEventDispatcher(new Dispatcher(new Container));
$capsule->setAsGlobal();
$capsule->bootEloquent();

$data = DB::table('user')->select('*')->get();

var_dump($data);
发布于
归类为php

CentOS7使用Firewall屏蔽端口

1 安装 Firewalld

yum install -y firewalld

2 开启常用端口

firewall-cmd --add-service=ssh --permanent
firewall-cmd --add-service=http --permanent
firewall-cmd --add-service=https --permanent

3 特殊端口指定IP访问权限

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.0.0/16" port port="8080" protocol="tcp" accept'

4 只针对 IPV4 或者 IPV6 地址开放端口

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" port port="443" protocol="tcp" accept'

5 重新加载防火墙规则

firewall-cmd --reload
发布于
归类为Linux

WordPress 禁用 REST

添加以下代码到插件文件里,可以实现:

  1. 已登录用户可以正常使用 wp-json API
  2. 未登录用户禁止使用 wp-json API
/*
 *  disable rest api
 */
function disable_rest_api($access)
{
    if (is_user_logged_in()) {
        return $access;
    } else {
        return new WP_Error('rest_disabled', __('The REST API on this site has been disabled.'), ['status' => rest_authorization_required_code()]);
    }
}

add_filter('rest_authentication_errors', 'disable_rest_api');
发布于
归类为php

阿里云刷新CDN缓存

PHP版本的刷新阿里云CDN缓存最小SDK


define('DebugModel', true);
define('AccessKeyId', 'AccessKeyId');
define('AccessKeySecret', 'AccessKeySecret');

/**
 *  刷新网址
 */
function freshURL($urls = [], $type = 'File')
{
    $sign = getSign(['Action' => 'RefreshObjectCaches', 'ObjectPath' => formatURL($urls), 'ObjectType' => $type]);
    $url = 'https://cdn.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
    $request = json_decode(httpRequest($url));
    if (isset($request->Code) && $request->Code == 'OK') {
        return true;
    } else {
        if (DebugModel) {
            var_dump($request);
        }
        return false;
    }
}

/**
 *  格式化网址
 */
function formatURL($urls = [])
{
    $urls = array_map(function($v) {
        return str_replace(['http://', 'https://'], ['', ''], $v);
    }, $urls);
    return implode('\n', $urls);
}

/**
 *  获取签名
 */
function getSign($add)
{
    $data = array(
        "Version" => "2018-05-10",
        "SignatureMethod" => "HMAC-SHA1",
        "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
        "SignatureVersion" => "1.0",
        "AccessKeyId" => AccessKeyId,
        "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
        "Format" => "JSON",
    );
    $data = array_merge($data, $add);
    ksort($data);
    $format = http_build_query($data);
    $signUrl = 'GET&%2F&' . urlencode(str_replace(['+', '*', '%7E'], ['%20', '%2A', '~'], $format));
    $sign = urlencode(base64_encode(hash_hmac('sha1', $signUrl, AccessKeySecret . '&', true)));
    return array('url' => $format, 'sign' => $sign);
}

/**
 *  发起 HTTP 请求
 */
function httpRequest($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);
    if ($error) {
        return $error;
    } else {
        return $data;
    }
}

function main() {
    freshURL(['https://abc.com/login/', 'https://abc.com/user/12']);
}

main();
发布于
归类为php

Podman使用阿里云容器镜像

Podman 是一个开源的容器管理工具,语法兼容 Docker ,但是某些方面比原生 Docker 命令更好用,比如能够以非 root 用户的身份去运行容器,而且不需要守护进程。

Podman 引入了一个注册表的概念,注册表就是包括 docker.io 在内的多个容器镜像源,默认的有 redhat docker fedora centos quay

国内直接用 podman pull 拉取镜像会很慢,所以需要配置阿里云容器镜像来加速访问。

Podman 默认注册表配置文件在 /etc/containers/registries.conf

修改为以下内容:

unqualified-search-registries = ["docker.io"]

[[registry]]
prefix = "docker.io"
location = "******.mirror.aliyuncs.com"

把 location 对应的值修改为你的阿里云容器加速镜像地址就可以了,现在拉取镜像就是用的阿里云加速

发布于
归类为服务器

phpMyAdmin登录MySQL8

MySQL8使用了新的密码验证插件,所以pma不能直接登录,解决办法是创建一个旧验证方式的用户和密码,比如用户www密码123456,然后就可以登录了

CREATE USER 'www'@'%' IDENTIFIED WITH mysql_native_password BY '123456';
GRANT ALL PRIVILEGES ON *.* TO 'www'@'%';
FLUSH PRIVILEGES;
发布于
归类为php