Skip to content

Instantly share code, notes, and snippets.

@Phalacrocorax
Last active August 14, 2020 17:09
Show Gist options
  • Save Phalacrocorax/25e3ff5a3b9669fbab701ae1ac4db5f5 to your computer and use it in GitHub Desktop.
Save Phalacrocorax/25e3ff5a3b9669fbab701ae1ac4db5f5 to your computer and use it in GitHub Desktop.
[snippets] php+mysql+apahce
public function csvToArray($filename = '', $delimiter = ',') {
if (!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}

php _http_post

    private function _http_post($url, $data) {
        $json_data = json_encode($data);

        $options = array(
          'http' => array(
            'ignore_errors' => true,
            'method'=> 'POST',
            'header'=> 'Content-type: application/json; charset=UTF-8',
            'content' => $json_data
          )
        );

        $context = stream_context_create($options);
        $contents = file_get_contents($url, false, $context);

        log_message('debug', 'contents:' . $contents);
        log_message('debug', 'http_response_header:' . print_r($http_response_header, true));

        preg_match('/HTTP\/1\.[0|1|x] ([0-9]{3})/', $http_response_header[0], $matches);

        $code = $matches[1];
        log_message('debug', 'code:' . $code);
        $msg_err = [
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Time-out',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Large',
            415 => 'Unsupported Media Type',
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Time-out',
            505 => 'HTTP Version not supported',
        ];
        $msg_unexpected = 'Unexpected Error';
        $msg = array_key_exists($code, $msg_err) ? $msg_err[$code] : $msg_unexpected;
        if($code >= 400 && $code <= 500) {
            log_message('WARN', __METHOD__.' Response Code='.$code.' Message='.$msg);
        }
        return json_decode($contents, true);
    }

CLI COMMAND

lsof -i:8080 //lookup port

AWS HTTP ERROR 500

在做AWS的时候遇到过很多问题,经常是代码pull,访问500错误。数据库遇到的最多,因为password和本地不一样,没有用config区分开的话就很容易出错。 还有一些重要的vendor没有提交到master也会有这样的错误

解决办法

情况1 数据库 库名or密码错误

情况2 文件 core file缺失or没有读写权限

总的权限需要sudo chown -R root:www /var/www。

cache类似直接sudo chmod 777 var -R。 团队开发注意先设置git config core.filemode false

另外注意查看服务器日志👌

sudo tail -10 /var/log/httpd/error_log

ERR_CONNECTION_REFUSED

This site can’t be reached whatcode.cc refused to connect. 这是 sudo service httpd stop 的结果,应该就是服务器启动失败了,最近每次想要restart httpd必然出现的结果= =。 先查看配置文件

/usr/sbin/httpd -S

如果配置文件中有语法错误也会显示出来,然后可以看的DocumentRoot 以及ErrorLog地址。 seg fault or similar nasty error detected in the parent process sudo apachectl stop / sudo apachectl start / sudo apachectl graceful

ERR_EMPTY_RESPONSE

用gulp开发着,突然一刷新就出现这个错误,有点懵逼。难道是刚下的vueDraggable的错, 于是马上 npm unintsall然后git reset --hard

...没用, 访问localhost都不行,

sudo apachectl restart
Address already in use: make_sock: could not bind to address //= = 端口占用?
lsof -i | grep :80 //查一查
Shadowsoc TCP *:8090 (LISTEN) 

没想到是shadowsocks,为了看Nokisaka Official@youtube的视频, 把VPN调到日本然后开了Global Mode... 居然是这个锅。

#1045 无法登录 MySQL 服务器

在AWS EC2上的blog,试着用phpmyadmin

@Phalacrocorax
Copy link
Author

Phalacrocorax commented Feb 19, 2017

Some GIT dishes

学习git flow之前可以看看这篇文章: 如何部署软件
3 Git Commands I Use Every Day

  • git add -p | interactively review changes
  • git commit --amend --no-edit

然后是gitconfig

  • git config core.filemode false #文件权限不关心

发现自己常用的的git cherry-pick主要是运用在不同版本之间的功能增加上。不如想为v2.0增加v3.0的一个功能。

  • git cherry-pick // cherry-pick -n 更实用~

  • git merge --squash //判断是否使用--squash选项最根本的标准是,待合并分支上的历史是否有意义。

@Phalacrocorax
Copy link
Author

Phalacrocorax commented Apr 12, 2017

PHP

WebServer与PHP通信姿势

CGI是什么? Fast-CGI是什么? php-fpm是什么?
php-fpm跟Fast-CGI有什么关系?
php的生命周期
Nginx是怎么跟php进行通信的?
Apache是怎么跟php进行通信的?
.用其他语言实现一个WebServer(golang ? php ?)
LNMP配置调优

[PHP built-in web server]

Designed to aid application development, as of PHP 5.4.0, the CLI SAPI provides a built-in web server.

 php -S localhost:8000 -c php.ini -t foo/ 

PHP ini

//for PHP: 
date_default_timezone_set('PRC');
error_reporting(E_ALL);
header("Content-Type: text/html;charset=utf-8");
$img = $this->get('img');
$saveFile = 'upload/thumb/'.$img;
if (!is_file($saveFile)) {
	$this->load(LIBRARY.'PHPThumb/', 'ThumbLib.inc');
	$thumb = PhpThumbFactory::create('upload/'.$img);
	$thumb->resize(300);
	mkdir(APP_WEBROOT.'upload/thumb/'.dirname($img),0777,true);
	$thumb->save( 'upload/thumb/'.$img);
}
header('Location: upload/thumb/'.$img);

PHP去掉nbsp
preg_replace("/(\s|\&nbsp\;| |\xc2\xa0)/", " ", strip_tags($item.content))

PHP验证码

不知道为什么,有一个项目的验证码始终显示不出来:
php_info() gd库已经加载了,代码测试:

header("Content-type: image/jpeg");
        error_reporting(E_ALL ^ E_NOTICE);
        $rand=null;
        for($i=0;$i<4;$i++)
        {
            $rand.=dechex(rand(1,15)); //生成随机数
        }
        $image = imagecreatetruecolor(100,30); //生成图片
        $color = imagecolorallocate($image, 255,255,255);
        imagestring($image,6,rand(0,65),rand(0,15),$rand,$color); //把随机数画进图片
        imagejpeg($image);

还是没有,原来是ob_clean();这里的问题。 | 解决

PHP CLASS&LIBRARY

意外的发现澳新的json_class确实很实用,因为json_encode本身不支持中文的,php版本大于5.4.0,可以用 json_encode($data,JSON_UNESCAPED_UNICODE);,低版本的则可以再用preg_replace处理:preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $result);;

@Phalacrocorax
Copy link
Author

Phalacrocorax commented May 1, 2017

MYSQL

CREATE TABLE `tb_withdraw_log` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',
  `user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
  `amount` decimal(12,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '金额',
  `balance` decimal(12,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '余额',
  `status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '-1失败,0未处理,1处理中,2成功',
  `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '添加时间',
  `updated` TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否删除:1,是;0,否',
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='代理商|经理人提现记录日志';

CREATE TABLE IF NOT EXISTS `tb_case` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL COMMENT '标题',
  `cover` varchar(255) NOT NULL COMMENT '封面',
  `content` text NOT NULL COMMENT '内容',
  `create_time` datetime NOT NULL COMMENT '发布时间',
  `visibility` tinyint(1) NOT NULL DEFAULT '1' COMMENT '是否显示 0:不显示,1:显示',
  `sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
  PRIMARY KEY (`id`),
  KEY `sort` (`sort`),
  KEY `category_id` (`category_id`,`visibility`),
  KEY `visibility` (`visibility`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='文章表' AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `tb_help` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(250) NOT NULL COMMENT '标题',
  `content` text NOT NULL COMMENT '内容',
  `category_id` int(11) unsigned NOT NULL COMMENT '分类ID',
  `create_time` datetime NOT NULL COMMENT '发布时间',
  `visibility` tinyint(1) NOT NULL DEFAULT '1' COMMENT '是否显示 0:不显示,1:显示',
  `sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
  PRIMARY KEY (`id`),
  KEY `sort` (`sort`),
  KEY `category_id` (`category_id`,`visibility`),
  KEY `visibility` (`visibility`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='文章表' AUTO_INCREMENT=1 ;


CREATE TABLE IF NOT EXISTS `tb_help_category` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL COMMENT '分类名称',
  `sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
  PRIMARY KEY (`id`),
  KEY `sort` (`sort`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='文章分类' AUTO_INCREMENT=1 ;

update & insert

INSERT INTO
    table (
        id,
        category_name,
        update_count
    ) VALUES (
        1,
        'カテゴリー1',
        1
    ) ON DUPLICATE KEY UPDATE
        category_name = 'カテゴリー1',
        update_count = update_count + 1

@Phalacrocorax
Copy link
Author

Phalacrocorax commented May 10, 2017

APACHE

apachectl(Apache control interface)是用来控制Apache HTTP服务器的程序。是slackware内附Apache HTTP服务器的script文件,可供管理员控制服务器,但有些Linux的Apache HTTP服务器不一定有这个文件。

  • configtest 检查设置文件中的语法是否正确。用于修改了配置文件后进行测试是否有误。
  • fullstatus 显示服务器完整的状态信息。
  • graceful 重新启动Apache服务器,但不会中断原有的连接。用于修改了配置文件后进行重新读取配置文件。
  • help 显示帮助信息。
  • restart 重新启动Apache服务器。 = httpd -k restart
  • start 启动Apache服务器。
  • status 显示服务器摘要的状态信息。
  • stop 停止Apache服务器。

apache再起動 in centOS
sudo /etc/init.d/httpd restart

  • check vhost /usr/sbin/httpd -S

@Phalacrocorax
Copy link
Author

Phalacrocorax commented Jun 12, 2017

MAC

homebrew doc

brew search

BASH

linux下查找字符串的命令

 grep -r "string" dir //目录下查找有“string”的文件

@Phalacrocorax
Copy link
Author

Phalacrocorax commented Jan 11, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment