Coder Social home page Coder Social logo

生成数据字典 about mingyun.github.io HOT 5 OPEN

mingyun avatar mingyun commented on July 1, 2024
生成数据字典

from mingyun.github.io.

Comments (5)

mingyun avatar mingyun commented on July 1, 2024

MySQL中的那些坑 http://zsuil.com/?p=1568
https://www.zhihu.com/question/22108510

null和空字符串的区别。null和任何值既不相等,也不不相等。null的判断只能通过is null, is not null. oracle中也一样会出现这样的结果
select * from users where app_id=16519794949 and openid='sadfasdf' limit 1
select * from users where app_id='16519794949' and openid='sadfasdf' limit 1
第二个走索引,第一个不走索引,就是因为app_id是varchar类型当然这不能关不怪mysql,当mysql遇到php这个语言就悲剧了,php里面采用pdo绑定生成的sql语句里面会自动判断你绑定的数据类型生成有引号还是没有引号可是php一个不小心app_id就被隐式的转换为整型了,如$arr = ["app_id"=>"16519794949"];
$arr2[$arr['app_id']] = [.....]

然后app_id就坑爹了
我的id字段是字符串型,当我用整数型0作为where条件去与其比对时,字符串id被自动转为整数型,也就成了0。自然就把所有记录都给匹配出来了 给0加上了单引号,sql语句变为
select * from user where id='0'
执行之后,bug成功解决
 导出 excel 错误

PHPExcel_Calculation_Exception: Q5!A65  Formula Error: An unexpected error occured in /application/www/web_git-pull/vendor/phpoffice/phpexcel/Classes/PHPExcel/Cell.php:291

在excel中一个单元格如果是以“=”开头,则说明这个单元格是根据其他单元格的值算出来的,“=”后面必须跟着一个合法的表达式

而那个字符串是用户的输入,很明显不应该是一个合法的表达式,所以应该在代码中过滤掉或者 $str = \t.$str;

https://github.com/Maatwebsite/Laravel-Excel/issues/506

https://stackoverflow.com/questions/11189145/formula-error-in-phpexcel
如果数据库字段是字符串,
和字符比较,就按照字符串比较规则。
和数字比较,字符串转为数字比较。

如果字段是int,
和int比较,这个没什么问题。
和字符串比较,也是字符串截取前面的数字,转换成int,再比较。

字符串转数字的规则是截取开头的数字变成数字。
123abc就转成123,abc就转换成0,abc123也是0。
所以,我查资料的时候也看到有人踩坑。说用where xx=0去比较一个非数字的字符串字段xx的时候,是查到所有数据。
想写一个SQL语句,把任务按价格分组,然后统计每一个价格的任务的完成的数目。

SELECT SUM (`completed`=1) AS completed  FROM `data` GROUP BY `price`
然后就报错
FUNCTION math.SUM does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual

SUM明明是MySQL内置函数,为什么不存在呢?

百度一下,在知道找到答案:

SUM后面,不能有空格……

最后,删除SUM的空格,这句SQL就顺利执行了

SELECT SUM(`completed`=1) AS completed  FROM `data` GROUP BY `price`http://dingdingblog.com/article/58
mysql踩坑系列之查询空格https://qixiaobo.github.io/2017/08/11/mysql%E8%B8%A9%E5%9D%91%E7%B3%BB%E5%88%97%E4%B9%8B%E6%9F%A5%E8%AF%A2%E7%A9%BA%E6%A0%BC/
某个业务去重失败导致db中重复插入数据。mysql中默认情况下查询的时候都会去掉末尾的空格匹配,这个和sql mode没有关系。mysql在varchar char text的字段中匹配会忽略大小写和末尾空格 以前使用like都是做匹配的,一般要求做前缀匹配,比如通配符不允许出现最左侧等等,现在对于varchar char 等类型字段使用like直接匹配效果更逼真!
那些年,我们踩过的PHP的坑https://zhuanlan.zhihu.com/p/28490854
$trMap = [ 
        'baidu' => '百度',
        'sougou' => '搜狗',
        '360' => '360',
        'google' => '谷歌'
    ];  360变成了int类型
360的hex表示是0x168,所以当你这样调用时,它能匹配translate("\x1\x68")
那么正确的写法是怎么样的呢?稍加改动即可strpos($keyword, $key) //改为 strpos($keyword, (string) $key)
$ret2 = [
    'choices' => [],
    'answers' => (object) [],
];
>>> json_encode($ret2)
=> "{\"choices\":[],\"answers\":{}}"
http://blog.xiayf.cn/2015/09/05/php-trap-and-tip/ 
// php版本
function base64_URL_encode($data) {
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64_URL_decode($data) {
  return base64_decode(str_pad(strtr($data, '-_', '+/'), 
                            strlen($data) % 4, '=', STR_PAD_RIGHT));
}Base64编码原理与应用http://blog.xiayf.cn/2016/01/24/base64-encoding/
踩到一个MySQL的坑,它选择了错误的索引https://github.com/ericdum/mujiang.info/issues/5
MySQL把你坑了http://www.jianshu.com/p/ccbdee173a1e
据说是有个包含了auto_increment的表,放在事务里面操作,虽然事务回滚了,但是这个自增列自增后的值并没有回滚。
事务的回滚,回滚的其实是数据库写入的值,而对于下一个自增id的值这种东西,其实不算数据库写入值的一部分。我们只是想当然的认为它该回滚而已,但其实它不回退回去也不是一个违反了定义的事。

其实如果知道了这个实现方式之后,很多关于自增列的特性也就不难理解了。比如先插入再删除,自增id是不会回去的,但重启了mysql之后就可以了。
http://www.jianshu.com/p/7410bc3b3f0e 第二次实例化DB的时候,载入的config是true,而不是数组。这是因为require_once在第二次载入同一个文件的时候,就会直接返回true了。>>> $b=['x'=>false,'y'=>'','z'=>null]
=> [
       "x" => false,
       "y" => "",
       "z" => null
   ]
>>> http_build_query($b)
=> "x=0&y="  foreach($b as $k=>$v){$r.=$k.'='.$v.'&';}
https://blog.lilydjwg.me/2015/1/25/nine-pitfalls-of-mysql.77680.html  连接 localhost 等同于连接默认 socket 文件
http://www.jianshu.com/p/78ec7b7c35cf
youtube-dl -F --proxy "https://127.0.0.1:1080"; https://www.youtube.com/watch?v=yotaHv7-5a4&t=125s  you-get -x 127.0.0.1:1080 [url]
由于国内视频网站经常更改算法,导致You-Get、youtube-dl等脚本经常下载不了国内网站的视频。
这里推荐使用猎影+WWQ解析插件来下载优酷视频,链接:http://pan.baidu.com/s/1hsysCug 密码:5hmx
在线视频下载方法小结 http://www.jianshu.com/p/c739b19bce9b? 
ffmpeg -i "M3U8_URL" -c copy VIDEO_NAME.ts 下载后用 vlc 播放 然后转换为 mp4
pip install livestreamer  sudo pip install streamlink
我在北京一家公司打工两个月,昨夜露宿街头
http://www.jianshu.com/p/fbdf228d64e8?url_type=39&object_type=webpage&pos=1
$a = "1234567";
var_dump($a['test']);
==> 1  //坑爹的等同于$a[0], php5.4会给出一个非法索引warning,但是仍然返回1,php5.3则连warning都没有。
var_dump(isset($a['test']));https://jingxin.me/blog/blog/2013/05/10/xi-shu-php-zhong-de-na-xie-keng/
==> true  //这是一个完全错误的结果,在php5.4中得到修复
var_dump(in_array(0, array('xxx')));
==> true  //这也是一个令人费解的bug,暂且还是理解为php将'xxx'转化成0了吧
var_dump(in_array(false, array('xxx')));
==> false  //与之相对的,这个结果确是符合预料的。问题是,在php中0==false呀。

严格的来说,PHP中的==符号完全没有作用,因为'string' == true,而且'string' == 0,但是,true != 0
然后是123 == "123foo",但是当你用引号将123包起来以明确说明这是一个字符串时,'123' != "123foo",但是在现实中,谁会用常量比较呢,这个123换成了一个变量,而根据php的哲学,谁会在意这个变量是什么类型
"133" == "0133";
133 == "0133";
133 == 0133;    //因为0133是一个八进制数,转成十进制是91
"0133" != 91;   //字符串中的数字始终是十进制的,这个也可以理解
"0x10" == 16;   //但是!,在十六进制中上面的说法又不成立了
"1e3" == 1000;  //科学计数表示也一样
$a = null;
$a ++;  // $a == 1, 可以理解
$a = null;
$a --;  // $a == null, 凌乱了 解决这种++和--中的不一致的办法就是根本不用它们,用+=和-=代替。
array_filter($input, $callback)和array_map($callback, $input)两个方法的回调方法位置正好相反
 烦是涉及到centos 7 ,什么毛病也没有,就是访问出错的时候,一定要想到selinux

from mingyun.github.io.

mingyun avatar mingyun commented on July 1, 2024
<?php
class VerifyPic {
    
    protected $image;
    protected $width;
    protected $height;
    protected $backimg;
    protected $fonts = array(
        'STXINGKA.TTF'
    );
    protected $verify;
    protected $sourcedir;
    
    public function __construct($width, $height) {
        $this->sourcedir = './';
        $image = imagecreatetruecolor($width, $height);
        $backimg = imagecreatefrompng($this->sourcedir . '4.png');
        imagecopy($image, $backimg, 0, 0, 0, 0, $width, $height);
        $this->width = $width;
        $this->height = $height;
        $this->image = $image;
        $this->backimg = $backimg;
    }
    
    public function genCode($n = 4) {
        $dict = 'ABCDEFGHIJKLNMPQRSTUVWXYZ123456789';
        $dictlen = strlen($dict);
        $image = $this->image;
        $verify = '';
        $fontfile = $this->sourcedir . $this->fonts[0];
        $colors = array(
            imagecolorallocate($image, 255, 0, 0) , //红
            imagecolorallocate($image, 0, 0, 255) , //蓝
            imagecolorallocate($image, 0, 0, 0) , //黑
        );
        for ($i = 0;$i < $n;$i++) {
            $verify.= $code = substr($dict, mt_rand(0, $dictlen - 1) , 1);
            imagettftext($image, 20, mt_rand(-15, 15) , ($i * 15) + 3, mt_rand(20, 25) , $colors[array_rand($colors) ], $fontfile, $code);
        }
        return $this;
    }
    
    public function genHanzi($n = 2) {
        $dict = "的一是在了不和有大这主中人上为们地个用工时要动国产以我到他会作来分生对于学下级就年阶义发成部民可出能方进同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批如应形想制心样干都向变关点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫康遵牧遭幅园腔订香肉弟屋敏恢忘衣孙龄岭骗休借丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩";
        $dictlen = mb_strlen($dict, 'UTF-8');
        $image = $this->image;
        $fontfile = $this->sourcedir . $this->fonts[array_rand($this->fonts) ];
        $color = imagecolorallocate($image, 0, 0, 0);
        $verify = '';
        for ($i = 0;$i < $n;$i++) {
            $verify.= $word = mb_substr($dict, mt_rand(0, $dictlen - 1) , 1, 'UTF-8');
            imagettftext($image, rand(18, 22) , rand(-20, 20) , 5 + $i * 25, 25, $color, $fontfile, $word);
        }
        $this->verify = $verify;
        return $this;
    }
    
    public function genFomula() {
        $symbols = array(
            '+' => '+',
            '-' => '-',
            '×' => '*',
            '加' => '+',
            '减' => '-',
            '乘' => '*'
        );
        $numbers = array(
            '0' => 0,
            '1' => 1,
            '2' => 2,
            '3' => 3,
            '4' => 4,
            '5' => 5,
            '6' => 6,
            '7' => 7,
            '8' => 8,
            '9' => 9,
            '零' => 0,
            '四' => 4,
            '五' => 5,
            '六' => 6,
            '七' => 7,
            '八' => 8,
            '九' => 9,
            '壹' => 1,
            '贰' => 2,
            '叁' => 3,
            '肆' => 4,
            '伍' => 5,
            '陆' => 6,
            '柒' => 7,
            '捌' => 8,
            '玖' => 9,
        );
        $image = $this->image;
        $fontfile = $this->sourcedir . $this->fonts[array_rand($this->fonts) ];
        $numidx1 = array_rand($numbers);
        $num1 = $numbers[$numidx1];
        $symbol = array_rand($symbols);
        $color = imagecolorallocate($image, 0, 0, 0);
        while (1) {
            $numidx2 = array_rand($numbers);
            $num2 = $numbers[$numidx2];
            if ($symbols[$symbol] != '-' || $num2 <= $num1) { //减法结果不为负数
                break;
            }
        }
        eval("\$verify = " . "$num1" . $symbols[$symbol] . "$num2;");
        $verify = intval($verify);
        $codelist = array(
            $numidx1,
            $symbol,
            $numidx2,
            '='
        );
        foreach ($codelist as $i => $code) {
            imagettftext($image, mt_rand(14, 16) , mt_rand(-15, 15) , ($i * 18) + 3, mt_rand(20, 25) , $color, $fontfile, $code);
        }
        return $this;
    }
    
    /**
     * 动画
     */
    public function genCodeAnimate($n = 4, $flags = 40) {
        $dict = 'ABCDEFGHIJKLNMPQRSTUVWXYZ123456789';
        $dictlen = strlen($dict);
        $verify = '';
        $fontfile = $this->sourcedir . $this->fonts[0];
        $colors = array(
            imagecolorallocate($this->image, 255, 0, 0) , //红
            imagecolorallocate($this->image, 0, 0, 255) , //蓝
            imagecolorallocate($this->image, 0, 0, 0) , //黑
        );
        $fontColors = array();
        $fontSizes = array();
        $gifs = array();
        for ($i = 0;$i < $n;$i++) {
            $verify.= substr($dict, mt_rand(0, $dictlen - 1) , 1);
            $fontColors[$i] = $colors[array_rand($colors) ];
            $fontSizes[$i] = rand(18, 22);
        }
        for ($f = 0;$f < $flags;$f++) {
            $image = $this->imgClone($this->image);
            $angle = - 15 + abs($f - $flags / 2) * 2; //角度
            $y = 20 + abs($f - $flags / 2) * 0.5;
            for ($i = 0;$i < $n;$i++) {
                $code = substr($verify, $i, 1);
                imagettftext($image, $fontSizes[$i], $angle, ($i * 15) - 20 + abs($f - $flags / 2) * 5, $y, $fontColors[$i], $fontfile, $code);
            }
            header("Content-type: image/gif");
            imagegif($image);
            imagedestroy($image);
            $gifs[] = ob_get_contents();
            ob_clean();
        }
        ob_start();
        $gifEncoder = new GIFEncoder($gifs, 100, 0, 1, 0, 0, 1, 'bin');
        header('Content-type: image/gif');
        echo $gifEncoder->GetAnimation();
        return $verify;
    }
    
    public function flush() {
        header('Content-type: image/png');
        imagepng($this->image);
        imagedestroy($this->image);
        imagedestroy($this->backimg);
        return $this->verify;
    }
    
    /**
     * 扭曲
     */
    public function twist() {
        $distImage = imagecreatetruecolor($this->width, $this->height);
        imagecopy($distImage, $this->backimg, 0, 0, 0, 0, $this->width, $this->height);
        for ($x = 0;$x < $this->width;$x++) {
            for ($y = 0;$y < $this->height;$y++) {
                $rgb = imagecolorat($this->image, $x, $y);
                imagesetpixel($distImage, (int)($x + sin($y / $this->height * 2 * M_PI - M_PI * 0.1) * 4) , $y, $rgb);
            }
        }
        $this->image = $distImage;
        return $this;
    }
    
    /**
     * 加噪点
     */
    public function addNoise($n = 50) {
        $image = $this->image;
        $color = imagecolorallocate($image, 0, 0, 0);
        for ($i = 0;$i < $n;$i++) { //噪声点
            imagesetpixel($image, mt_rand(0, $this->width) , mt_rand(0, $this->height) , $color);
        }
        return $this;
    }
    
    /**
     * 加噪音线
     */
    public function addLine($n = 1) {
        $image = $this->image;
        $color = imagecolorallocate($image, 0, 0, 0);
        for ($i = 0;$i < $n;$i++) {
            imagearc($image, rand(-10, $this->width + 10) , rand(-10, 0) , rand($this->width * 2 + 10, $this->width * 2 + 40) , rand($this->height, $this->height + 20) , 0, 360, $color);
        }
        return $this;
    }
    
    public function imgClone($image) {
        $copy = imagecreatetruecolor($this->width, $this->height);
        imagecopy($copy, $image, 0, 0, 0, 0, $this->width, $this->height);
        return $copy;
    }
    
}

Class GIFEncoder {
    
    var $GIF = "GIF89a"; /* GIF header 6 bytes        */
    var $VER = "GIFEncoder V2.06"; /* Encoder version                */
    var $BUF = Array();
    var $LOP = 0;
    var $DIS = 2;
    var $COL = - 1;
    var $IMG = - 1;
    var $ERR = Array(
        'ERR00' => "Does not supported function for only one image!",
        'ERR01' => "Source is not a GIF image!",
        'ERR02' => "Unintelligible flag ",
        'ERR03' => "Could not make animation from animated GIF source",
    );
    
    /*
      :::::::::::::::::::::::::::::::::::::::::::::::::::
      ::
      ::        GIFEncoder...
      ::
    */
    
    function GIFEncoder($GIF_src, $GIF_dly, $GIF_lop, $GIF_dis, $GIF_red, $GIF_grn, $GIF_blu, $GIF_mod) {
        if (!is_array($GIF_src) && !is_array($GIF_tim)) {
            printf("%s: %s", $this->VER, $this->ERR['ERR00']);
            exit(0);
        }
        $this->LOP = ($GIF_lop > - 1) ? $GIF_lop : 0;
        $this->DIS = ($GIF_dis > - 1) ? (($GIF_dis < 3) ? $GIF_dis : 3) : 2;
        $this->COL = ($GIF_red > - 1 && $GIF_grn > - 1 && $GIF_blu > - 1) ? ($GIF_red | ($GIF_grn << 8) | ($GIF_blu << 16)) : -1;
        
        for ($i = 0;$i < count($GIF_src);$i++) {
            if (strToLower($GIF_mod) == "url") {
                $this->BUF[] = fread(fopen($GIF_src[$i], "rb") , filesize($GIF_src[$i]));
            } else if (strToLower($GIF_mod) == "bin") {
                $this->BUF[] = $GIF_src[$i];
            } else {
                printf("%s: %s ( %s )!", $this->VER, $this->ERR['ERR02'], $GIF_mod);
                exit(0);
            }
            if (substr($this->BUF[$i], 0, 6) != "GIF87a" && substr($this->BUF[$i], 0, 6) != "GIF89a") {
                printf("%s: %d %s", $this->VER, $i, $this->ERR['ERR01']);
                exit(0);
            }
            for ($j = (13 + 3 * (2 << (ord($this->BUF[$i] {
                10
            }) & 0x07))) , $k = TRUE;$k;$j++) {
                switch ($this->BUF[$i] {
                        $j
                }) {
                    case "!":
                        if ((substr($this->BUF[$i], ($j + 3) , 8)) == "NETSCAPE") {
                            printf("%s: %s ( %s source )!", $this->VER, $this->ERR['ERR03'], ($i + 1));
                            exit(0);
                        }
                    break;
                    case ";":
                        $k = FALSE;
                    break;
                }
            }
        }
        GIFEncoder::GIFAddHeader();
        for ($i = 0;$i < count($this->BUF);$i++) {
            GIFEncoder::GIFAddFrames($i, $GIF_dly[$i]);
        }
        GIFEncoder::GIFAddFooter();
    }
    
    /*
      :::::::::::::::::::::::::::::::::::::::::::::::::::
      ::
      ::        GIFAddHeader...
      ::
    */
    
    function GIFAddHeader() {
        $cmap = 0;
        
        if (ord($this->BUF[0] {
            10
        }) & 0x80) {
            $cmap = 3 * (2 << (ord($this->BUF[0] {
                10
            }) & 0x07));
            
            $this->GIF.= substr($this->BUF[0], 6, 7);
            $this->GIF.= substr($this->BUF[0], 13, $cmap);
            $this->GIF.= "!\377\13NETSCAPE2.0\3\1" . GIFEncoder::GIFWord($this->LOP) . "\0";
        }
    }
    
    /*
      :::::::::::::::::::::::::::::::::::::::::::::::::::
      ::
      ::        GIFAddFrames...
      ::
    */
    
    function GIFAddFrames($i, $d) {
        
        $Locals_str = 13 + 3 * (2 << (ord($this->BUF[$i] {
            10
        }) & 0x07));
        
        $Locals_end = strlen($this->BUF[$i]) - $Locals_str - 1;
        $Locals_tmp = substr($this->BUF[$i], $Locals_str, $Locals_end);
        
        $Global_len = 2 << (ord($this->BUF[0] {
            10
        }) & 0x07);
        $Locals_len = 2 << (ord($this->BUF[$i] {
            10
        }) & 0x07);
        
        $Global_rgb = substr($this->BUF[0], 13, 3 * (2 << (ord($this->BUF[0] {
            10
        }) & 0x07)));
        $Locals_rgb = substr($this->BUF[$i], 13, 3 * (2 << (ord($this->BUF[$i] {
            10
        }) & 0x07)));
        
        $Locals_ext = "!\xF9\x04" . chr(($this->DIS << 2) + 0) . chr(($d >> 0) & 0xFF) . chr(($d >> 8) & 0xFF) . "\x0\x0";
        
        if ($this->COL > - 1 && ord($this->BUF[$i] {
            10
        }) & 0x80) {
            for ($j = 0;$j < (2 << (ord($this->BUF[$i] {
                10
            }) & 0x07));$j++) {
                if (ord($Locals_rgb{3 * $j + 0}) == ($this->COL >> 0) & 0xFF && ord($Locals_rgb{3 * $j + 1}) == ($this->COL >> 8) & 0xFF && ord($Locals_rgb{3 * $j + 2}) == ($this->COL >> 16) & 0xFF) {
                    $Locals_ext = "!\xF9\x04" . chr(($this->DIS << 2) + 1) . chr(($d >> 0) & 0xFF) . chr(($d >> 8) & 0xFF) . chr($j) . "\x0";
                    break;
                }
            }
        }
        switch ($Locals_tmp{0}) {
            case "!":
                $Locals_img = substr($Locals_tmp, 8, 10);
                $Locals_tmp = substr($Locals_tmp, 18, strlen($Locals_tmp) - 18);
            break;
            case ",":
                $Locals_img = substr($Locals_tmp, 0, 10);
                $Locals_tmp = substr($Locals_tmp, 10, strlen($Locals_tmp) - 10);
            break;
        }
        if (ord($this->BUF[$i] {
            10
        }) & 0x80 && $this->IMG > - 1) {
            if ($Global_len == $Locals_len) {
                if (GIFEncoder::GIFBlockCompare($Global_rgb, $Locals_rgb, $Global_len)) {
                    $this->GIF.= ($Locals_ext . $Locals_img . $Locals_tmp);
                } else {
                    $byte = ord($Locals_img{9});
                    $byte|= 0x80;
                    $byte&= 0xF8;
                    $byte|= (ord($this->BUF[0] {
                        10
                    }) & 0x07);
                    $Locals_img{9} = chr($byte);
                    $this->GIF.= ($Locals_ext . $Locals_img . $Locals_rgb . $Locals_tmp);
                }
            } else {
                $byte = ord($Locals_img{9});
                $byte|= 0x80;
                $byte&= 0xF8;
                $byte|= (ord($this->BUF[$i] {
                    10
                }) & 0x07);
                $Locals_img{9} = chr($byte);
                $this->GIF.= ($Locals_ext . $Locals_img . $Locals_rgb . $Locals_tmp);
            }
        } else {
            $this->GIF.= ($Locals_ext . $Locals_img . $Locals_tmp);
        }
        $this->IMG = 1;
    }
    
    /*
      :::::::::::::::::::::::::::::::::::::::::::::::::::
      ::
      ::        GIFAddFooter...
      ::
    */
    
    function GIFAddFooter() {
        $this->GIF.= ";";
    }
    
    /*
      :::::::::::::::::::::::::::::::::::::::::::::::::::
      ::
      ::        GIFBlockCompare...
      ::
    */
    
    function GIFBlockCompare($GlobalBlock, $LocalBlock, $Len) {
        
        for ($i = 0;$i < $Len;$i++) {
            if ($GlobalBlock{3 * $i + 0} != $LocalBlock{3 * $i + 0} || $GlobalBlock{3 * $i + 1} != $LocalBlock{3 * $i + 1} || $GlobalBlock{3 * $i + 2} != $LocalBlock{3 * $i + 2}) {
                return (0);
            }
        }
        
        return (1);
    }
    
    /*
      :::::::::::::::::::::::::::::::::::::::::::::::::::
      ::
      ::        GIFWord...
      ::
    */
    
    function GIFWord($int) {
        
        return (chr($int & 0xFF) . chr(($int >> 8) & 0xFF));
    }
    
    /*
      :::::::::::::::::::::::::::::::::::::::::::::::::::
      ::
      ::        GetAnimation...
      ::
    */
    
    function GetAnimation() {
        return ($this->GIF);
    }
    
}
// https://jingxin.me/blog/blog/2013/01/13/php-yan-zheng-ma/
$vp = new VerifyPic(70, 30);
// $vp->genHanzi()->twist()->flush();
// $vp->genFomula()->twist()->flush();
$vp->genCodeAnimate()->twist()->flush();

from mingyun.github.io.

mingyun avatar mingyun commented on July 1, 2024

https://e.msxiaobing.com/Home/Content 微软小冰商业解决
将图片转换为assic字符 https://packagist.org/packages/aizuyan/img2ascii
select id,username from userinfo where id in (select author_id from article where type = 1); http://www.yunweipai.com/archives/13002.html
select id,username from userinfo

where id in (select author_id from

(select author_id from article where type = 1) as tb);
select a.id,a.username from userinfo a, article b

where a.id = b.author_id and b.type = 1;
https://github.com/chenjiandongx/bili-spider B 站全站视频信息爬虫

$balance = array(1000,2000,3000,4000);
$sum = 0;
foreach($balance as &$val){
    if($val >= 2000){
        $sum ++; 
        $val-= 2000;
    } 
}
$val = "test";
print_r($balance);//http://www.likuli.com/tech/lang/php/132.html
${'test'} = 'this is ok';https://github.com/hax/hax.github.com/issues/38
$x = function () use ($test) {}; // this is ok...
$x = function () use (${'test'}) {}; // this is NOT ok...
$a = 1;
$b = '1a';
var_dump($a == $b);//true
var_dump($a === $b);//false
如果要用字符串跟数字进行比较,那么PHP 会先将字符串转换为数字,然后再进行比较。(MD5 返回值是一个字符串)

即:若字符串的开始字符为非数字字符,那么字符的转型结果为0 
echo ip2long('58.99.11.1'),"<br/>";   //输出是979569409 
echo ip2long('58.99.011.1'),"<br/>";  //输出是979568897 
echo ip2long('058.99.11.1'),"<br/>";//输出是空 Ip2long对于部分ip在32位会溢出,所以使用时一般使用sprintf(“%u”,),注意一下就好了
var_dump(in_array(0, array('s'))); 
var_dump(0 == "string");
var_dump("1111" == "1112");
var_dump("111111111111111111" == "111111111111111112");
$str = 'string';
var_dump($str['aaa']);

32位bool(true) bool(true) bool(false) bool(true) string(1) "s" 
64位bool(true)bool(true)bool(false)bool(false)string(1) "s"
https://juejin.im/entry/5896d2ed8d6d81006c5c1b20
32
$a = array(2355199999 => 1, 2355199998 => 1);
var_dump($a);
array(2) { [-1939767297]=> int(1) [-1939767298]=> int(1) } 

$b = array(2355199999, 2355199998);
var_dump($b);
array(2) { [0]=> float(2355199999) [1]=> float(2355199998) } 
var_dump(array_flip($b));
Warning: array_flip() Can only flip STRING and INTEGER values!

$c = array();
foreach($b as $key => $value) {
    $c[$value] = $key;
}
var_dump($c);
  因为key只能为string或者interger,在32位机器上,大于21亿就成为了float,所以如果强行拿float去做key,会溢出变成类似负数等等~这里如果将大于21亿的数加上引号才可以
https://www.hellojava.com/article/242 如何使用javascript来获取QQ空间最近访客好友
http://blog.csdn.net/wolehao/article/details/51187427
/**
 * 解析命令行
 * @param  string     $str 命令行字符串
 * @return array/bool      解析结果数组 失败返回false
 */
function exp_command($str)
{
    // 正则表达式
    $regEx = '#(?:(?<s>[\'"])?(?<v>.+?)?(?:(?<!\\\\)\k<s>)|(?<u>[^\'"\s]+))#';
    // 匹配所有
    if(!preg_match_all($regEx, $str, $exp_list)) return false;
    // 遍历所有结果
    $cmd = array();
    foreach ($exp_list['s'] as $id => $s) {
        // 判断匹配到的值
        $cmd[] = empty($s) ? $exp_list['u'][$id] : $exp_list['v'][$id];
    }
    return $cmd;
}
// 命令行字符串
$str = 'cmd -n "rel\'o\"a d" \'te"s\' t\'    upload ""';
$cmd = exp_command($str);
print_r($cmd);
/* 打印输出结果
Array
(
    [0] => cmd
    [1] => -n
    [2] => rel'o\"a d
    [3] => te"s
    [4] => t
    [5] => upload
    [6] => 
)
*/
https://www.qs5.org/Post/651.html https://www.bejson.com/othertools/finddif/
程序员:同步与异步、阻塞与非阻塞 http://yogoup.sinaapp.com/ https://www.kancloud.cn/kkk1/cnqf/444618 
http://www.yihaoqu.com/article/4  empty("0")应该返回false才是,然而这里会返回true
if (is_array($arr) && !empty($arr)) {
    //code
}

echo date('Y-m-d', strtotime('-1 month', strtotime('2017-07-31')));
-1 month 是减 30 天,即使使用 Datetime 类也会有类似的问题出现。
$_REQUEST获取的参数 和URL中的不一致 打印EGPCS时发现cookie  get中有相同的变量,原来是cookie中的参数覆盖了get中的参数
$_GET里面有个 $_GET['id']=2 , $_POST 里有一个 $_POST['id'] =3
如果request_order = “PG”的形式设置,那么 $_REQUEST['id']=2
如果request_order = “GP”的形式设置,则 $_REQUEST['id']=3
https://github.com/rickbergfalk/sqlpad  npm install sqlpad -g 

https://jiachuhuang.github.io/2017/08/08/PHP%E5%B9%B6%E5%8F%91%E6%9F%A5%E8%AF%A2MySQL/  
PHP并发查询MySQL https://github.com/jiachuhuang/async_mysql
https://github.com/RunnerLee/api-watcher  
http://myrock.github.io/2014/09/24/in-and-range/
https://juejin.im/post/598bcc69f265da3e22053e11?
https://my.oschina.net/goal/blog/201032?p=2&temp=1472117779104#blog-comments-list  
JavaScript: 详解Base64编码和解码 http://www.jianshu.com/u/d286ee5ad51e
 https://jecvay.com/archive
http://www.likuli.com/programmer/464.html
setnx来实现锁的功能 https://jiachuhuang.github.io/2017/07/06/%E8%AF%B4%E8%AF%B4Redis%E7%9A%84setnx/
MySQL · 捉虫动态· InnoDB自增列重复值问题  http://www.csdn.net/article/2015-01-16/2823591
看到插入了(2,2),而如果我没有重启,插入同样数据我们得到的应该是(4,2) 上面的测试反映了MySQLd重启后,InnoDB存储引擎的表自增id可能出现重复利用的情况。

自增id重复利用在某些场景下会出现问题。依然用上面的例子,假设t1有个历史表t1_history用来存t1表的历史数据,那么MySQLd重启前,ti_history中可能已经有了(2,2)这条数据,而重启后我们又插入了(2,2),当新插入的(2,2)迁移到历史表时,会违反主键约束。
AUTO_INCREMENT是实时存储内存中的。那么,MySQLd 重启后,从哪里得到AUTO_INCREMENT呢? 内存值肯定是丢失了。实际上MySQL采用执行类似select max(id)+1 from t1;方法来得到AUTO_INCREMENT。而这种方法就是造成自增id重复的原因。
MyISAM是没有这个问题的。myisam会将这个值实时存储在.MYI文件中(mi_state_info_write)。MySQLd重起后会从.MYI中读取AUTO_INCREMENT值(mi_state_info_read)。因此,MyISAM表重启是不会出现自增id重复的问题。
对于InnoDB表,重启通过select max(id)+1 from t1得到AUTO_INCREMENT值,如果id上有索引那么这个语句使用索引查找就很快。那么,这个可以解释MySQL 为什么要求自增列必须包含在索引中的原因。 如果没有指定索引,则报如下错误,

ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key 而myisam表竟然也有这个要求,感觉是多余的。

就把官方文档看一遍,再把其他全家桶(路由和vuex)了解哈。

然后github一个stat比较高的 项目到本地,学习一下,就可以上手了 vue会了之后,微信小程序开发也就会了。如果要学习vue,就把官方文档打开
https://jsfiddle.net/chrisvfritz/50wL7mdz/   tcp 三次握手是常识吧。 连array_merge都不会用的人,要他干啥。
$x = 5;
echo $x+++$x++
推荐 https://deployer.org/ 
MySQL 中的 SELECT FOR UPDATE  注1: FOR UPDATE 仅适用于InnoDB,且必须在事务区块(BEGIN/COMMIT)中才能生效。 https://sphenginx.github.io/2016/09/18/select-for-update/ 
在参数里面添加时间戳,最好精确到毫秒,然后把时间戳、user_id和接口方法作为唯一值检验,相同的值只能一次有效。  来源正确,身份正确,内容正确,请求正确,信息安全  阿里云托管所有的主机,阿里云RDS托管数据,阿里云OSS数据备份,阿里云ODPS大数据计算,七牛云文件存储和文件CDN,云片发SMS短信,Send Cloud发送邮件通知。
Y分钟学会Python(译) http://blog.xiayf.cn/2013/06/29/learn-python-in-y-minutes/ 
微信服务号开发笔记 http://blog.xiayf.cn/2014/06/14/wechat-service-account-development/  https://github.com/netputer/wechat-php-sdk 

codepen.io https://codesandbox.io/

from mingyun.github.io.

mingyun avatar mingyun commented on July 1, 2024

https://www.shiyanlou.com/courses/983/labs/3953/document
#!/usr/bin/env python3
其中第一行的前两个字符 #! 称为 Shebang ,目的是告诉 shell 使用 Python 3 解释器执行其下面的代码
给脚本通过 Linux 的 chmod a+x XXX.py 命令增加了执行权限,则可以使用 ./XXX.py 这种方式直接执行脚本,否则需要用 python3 XXX.py 这种方式执行

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', '
def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'retu
rn', 'try', 'while', 'with', 'yield']

Python 3 中,包括以下几种基本数据类型:

整数:例如 100-200,0 
布尔数:True  False
浮点数:小数,例如 1.5,2.5
None:空值,注意与0是不同的,可以理解为未定义的值。
```str6 = """ hello, 
shiyanlou """
str1.strip('ab') 则只会删除 str1 字符串中头尾部的 a 和 b 字符
w = 100
while w > 10:
    print(w)
    w -= 10
最常见的异常类:

NameError 访问一个未定义的变量
SyntaxError 语法错误,这个严格讲算是程序的错误
IndexError 对于一个序列,访问的索引超过了序列的范围(序列的概念会在后续实验中讲到),可以理解为我的序列里只有三个元素,但要访问第4个
KeyError 访问一个不存在的字典 Key,字典也会在下一节实验中详细讲到,Key 如果不存在字典就会抛出这个异常
ValueError 传入无效的参数
AttributeError 访问类对象中不存在的属性
try:
    有可能抛出异常的代码
except 异常类型名称:
    处理代码
except 异常类型名称:
    处理代码
filename = input("Enter file path:")
try:
    f = open(filename)
    print(f.read())
    f.close()
except FileNotFoundError:
    print("File not found")
filename = '/etc/protocols'
f = open(filename)
try:
    f.write('shiyanlou')
except:
    print("File write error")
finally:
    print("finally")
    f.close()
finally 关键字是用来进行清理工作,经常和 except 一起使用,即无论是正常还是异常,这段代码都会执行。raise ValueError() 外部的代码就可以使用 except ValueError 进行捕获和处理了

每个 XXX.py 文件都是一个 Python 模块,文件的内容会在 import XXX 的时候直接执行。对于文件夹,Python 中可以识别成一个包,前提是这个文件夹中有一个 __init__.py 文件,文件中可以不用写任何内容。
创建一个目录 shiyanlou,在这个目录下有 __init__.py 和 louplus.py 两个代码文件,我们想要引入 louplus.py 文件就可以用 import shiyanlou.louplus 这种代码来引入,前提是 shiyanlou 目录已经放到了 Python 模块搜索的默认路径下了  sys.path
sys.argv[0] 为脚本名称, sys.argv[1] 为第一个参数 
python3 argtest.py 这样执行时可以执行到 if __name__ == '__main__': 这个代码块中 for 循环的内容,当通过 import argtest 作为模块导入到其他代码文件时不会执行if __name__ == '__main__':中的内容。
format(1.2345, ".2f") 得到的就是有两位小数的字符串 '1.23'

 
https://raw.githubusercontent.com/youngsterxyf/youngsterxyf.github.com/master/assets/uploads/pics/High-performance-php-app.png  php高性能
https://raw.githubusercontent.com/youngsterxyf/youngsterxyf.github.com/master/assets/uploads/pics/An-Introduction-to-APIs.png 
print(" The {} set is often represented as { {0} } ".format("empty"))
>>> The empty set is often represented as {0}
可以使用如下字母来将数字转换成字母代表的进制,decimal,hex,octal, binary。

print("{0:d} - {0:x} - {0:o} - {0:b} ".format(21))
>>> 21 - 15 - 25 -10101

Base64编码原理与应用  http://blog.xiayf.cn/2016/01/24/base64-encoding/ 
基于Github的pull request流程做开源贡献  http://blog.xiayf.cn/2016/01/18/github-fork-pull-request/ 
现代化 php https://raw.githubusercontent.com/youngsterxyf/youngsterxyf.github.com/master/assets/uploads/pics/modern-php.png 
php 调试手册 http://blog.xiayf.cn/assets/uploads/files/PHP-Debug-Manual-public.pdf
每台Web服务器上开启12个PHP-FPM实例,并配置到Nginx的upstream,每个实例最多可以开启10个子进程
“Database Proxy”的代理规则为:写操作及事务中的所有SQL操作都交给主MySQL处理,其余的读操作都交给任意一台从MySQL处理 http://blog.xiayf.cn/2015/10/02/note-of-a-system-fault/ 
SHOW PROCESSLIST(查看当前MySQL实例运行着哪些线程) 
由于这条SQL查询需耗费较长时间,并且被频繁执行,涉及该SQL的请求需要较长时间完成,大量SQL线程排队无响应,阻塞了大量PHP-FPM进程,在某些时候会达到PHP-FPM并发子进程数上限(更何况某个会被频繁访问的页面请求涉及该SQL,导致情况更糟),PHP-FPM无法处理新的请求,对于已有的请求也会因为超时导致Nginx响应502。
netstat -napo |grep "php-fpm" | wc -l 查看一下当前fastcgi进程个数,如果个数接近conf里配置的上限,就需要调高进程数。  nginx出现502有很多原因,但大部分原因可以归结为资源数量不够用,也就是说后端php-fpm处理有问题,nginx将正确的客户端请求发给了后端的php-fpm进程,但是因为php-fpm进程的问题导致不能正确解析php代码,最终返回给了客户端502错误。

以Nginx为例,对于从C转发到A、B的请求,如果A、B要拿到请求的真实来源IP,则需要对A、B及C的Nginx做特殊配置。为解决这个问题,Nginx提供了一个额外的模块ngx_http_realip_module,这个模块默认没有编译在Nginx中,需以额外参数--with-http_realip_module进行编译。
// 每个IP一分钟10次 http://blog.xiayf.cn/2016/06/05/frequency-limitation/
$limit = 10;

$cache = new Memcached();
$cache->addServer('127.0.0.1', 11211);

$key = __FUNCTION__.$_SERVER['REMOTE_ADDR'];
$requestNum = $cache->get($key);

if ($requestNum !== FALSE && $requestNum > 10) {
    echo json_encode(array(
        'code' => 403,
        'message' => '请求太频繁,请一分钟后再试',
    ));
    return;
}

$cache->add($key, 0, time()+60);
$cache->increment($key, 1);
Windows上安装PHP开发测试环境 http://blog.xiayf.cn/2013/04/15/install-php-development-environment-on-windows/
流行PHP项目的phpmetrics分析  http://blog.xiayf.cn/2014/09/22/phpmetrics-of-popular-php-projects/ 
http://www.phpmetrics.org/ 
基于Github的pull request流程做开源贡献 http://blog.xiayf.cn/2016/01/18/github-fork-pull-request/
如何方便地删除某目录下所有空文件?
find . -size 0 -exec rm {} \;  find . -size 0 | xargs rm -f

find默认会递归遍历所有子目录,如果想只在当前目录查找,可以添加参数-prune
通过ps aux | grep [进程名]找到该进程的进程号,然后ls -la /proc/[进程号]/fd,输出不仅包含打开的普通文件。

另一种不太直观的方法是使用lsof,lsof -c [进程名],但这个命令的输出包含进程打开的各种类型的文件,可以简单过滤一下lsof -c [进程名] | grep REG
kill -USR2 $(cat php-fpm.pid)  先ps aux | grep php-fpm找到php-fpm主进程的进程号,然后kill -USR2 [进程号]
Xhprof安装与使用 http://blog.xiayf.cn/2015/09/15/xhprof-installation-and-usage/
mysql 面试题 http://zhangxihai.cn/archives/149

from mingyun.github.io.

mingyun avatar mingyun commented on July 1, 2024
<?php
//jssdk 分享 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115 需要先登录获取
use RedisFacade;
class WxShare {
  private $appId;
  private $appSecret;

  public function __construct($appId, $appSecret) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
  }

  public function getSignPackage() {
    $jsapiTicket = $this->getJsApiTicket();

    // 注意 URL 一定要动态获取,不能 hardcode.
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

    $timestamp = time();
    $nonceStr = $this->createNonceStr();

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    $signature = sha1($string);

    $signPackage = array(
      "appId"     => $this->appId,
      "nonceStr"  => $nonceStr,
      "timestamp" => $timestamp,
      "url"       => $url,
      "signature" => $signature,
      "rawString" => $string
    );
    return $signPackage; 
  }

  private function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }

  private function getJsApiTicket() {
    // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
    $key_ticket = 'wechatshare_ticket';
    $jsondata = RedisFacade::get($key_ticket);
    if (empty($jsondata)) {
      $accessToken = $this->getAccessToken();
      // 如果是企业号用以下 URL 获取 ticket
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
      $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
      $res = json_decode($this->httpGet($url));
      $ticket = $res->ticket;
      if ($ticket) {
        $jsondata = json_encode($ticket);
        RedisFacade::set($key_ticket,$jsondata);
        RedisFacade::expire($key_ticket, 1800);
      }
    } else {
      //$ticket = $data->jsapi_ticket;
      $ticket = json_decode($jsondata, true);
    }

    return $ticket;
  }

  private function getAccessToken() {
    // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
    $key_token = 'wechatshare_token';
    $jsondata = RedisFacade::get($key_token);
    if (empty($jsondata)) {
      // 如果是企业号用以下URL获取access_token
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
      $res = json_decode($this->httpGet($url));
      $access_token = $res->access_token;
      if ($access_token) {
        $jsondata = json_encode($access_token);
        RedisFacade::set($key_token,$jsondata);
        RedisFacade::expire($key_token, 7000);
      }
    } else {
      $access_token = json_decode($jsondata, true);
    }
    return $access_token;
  }

  private function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
  }
}
顿悟数学,美在编程——探究什么是好代码?微信号
fangtalk

from mingyun.github.io.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.