DBに現在時刻を5分区切りの単位で入れたい時

### フォーム入力
1. フォームから時間を入力する場合はselect文で5分単位で選べるように、5分単位のテーブルを作る
insert into minutes (name) values (’00’);
insert into minutes (name) values (’05’);
insert into minutes (name) values (’10’);
insert into minutes (name) values (’15’);
insert into minutes (name) values (’20’);
insert into minutes (name) values (’25’);
insert into minutes (name) values (’30’);
insert into minutes (name) values (’35’);
insert into minutes (name) values (’40’);
insert into minutes (name) values (’45’);
insert into minutes (name) values (’50’);
insert into minutes (name) values (’55’);

2. select文では、minutesテーブルから値を呼び込む

{!! Form::select('start', $minutes, 1, ['class' => 'form-control']) !!}

### 現在時刻を5分単位でDBに入力

$minute = date('i');

        $minute_margin = 5;
        if($minute % $minute_margin){
            $minute += $minute_margin - ($minute % $minute_margin);
        }

例: 43分の時:43 + (5-3) = 45

上記は端数があった場合繰り上がりですが、$minute -= $minute % $minute_margin とすれば、繰り下がりになる筈です。

あ。。。55〜00分の処理忘れてた。。
### 追加

$hour = date('H');
        $minute = date('i');


        $minute_margin = 5;
        if($minute % $minute_margin){
            if($minute > 55){
                $hour = date('H',strtotime("+1 hour"));
                $minute = 00;
            } else {
                $minute += $minute_margin - ($minute % $minute_margin);
            }          

        }

mysqlからカラム名も取得してfputcsvによる帳票出力

### データ作成
create database universe;
use universe;
create table planets(
id int primary key auto_increment,
name varchar(255),
diameter float,
mass float
);
describe planets;
insert into planets(name, diameter, mass) values (‘Sun’,’110′,’330000′);
insert into planets(name, diameter, mass) values (‘Mercury’,’0.38′,’0.06′);
insert into planets(name, diameter, mass) values (‘Venus’,’0.95′,’0.82′);
insert into planets(name, diameter, mass) values (‘Earth’,’1′,’1′);
insert into planets(name, diameter, mass) values (‘Mars’,’0.53′,’0.11′);
insert into planets(name, diameter, mass) values (‘Jupiter’,’11’,’320′);
insert into planets(name, diameter, mass) values (‘Saturn’,’9.5′,’95’);
insert into planets(name, diameter, mass) values (‘Uranus’,’4′,’15’);
insert into planets(name, diameter, mass) values (‘Neptune’,’3.9′,’17’);
select * from planets;

### データ出力
var_dumpでテストしてから、出力します。

try {
$dbh = new PDO('mysql:host=localhost;dbname=universe;charset=utf8','root','hogehoge', array(PDO::ATTR_EMULATE_PREPARES => false));
} catch(PDOException $e){
    exit('データベース接続失敗。'.$e->getMessage());
}

$export_sql = "select * from planets";

// $stmt = $dbh->query($export_sql);
// $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
// var_dump($row);

$file_path = "csv/planets.csv";
$export_csv_title = ["id","name","diameter","mass"];

foreach($export_csv_title as $key => $val){
	$export_header[] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8');
	}

	if(touch($file_path)){
		$file = new SplFileObject($file_path, "w");

		$file->fputcsv($export_header);
		$stmt = $dbh->query($export_sql);

		while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
			$file->fputcsv($row);
		}
		$dbh = null;

	}

echo "done";

### カラム名も取得したい場合
show columnsとして配列を取得して、その中からFieldを取り出す

$export_column = "show columns from planets";
$stmt = $dbh->query($export_column);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
	$field[] = $row["Field"];
}

つなげると

try {
$dbh = new PDO('mysql:host=localhost;dbname=universe;charset=utf8','root','hogehoge', array(PDO::ATTR_EMULATE_PREPARES => false));
} catch(PDOException $e){
    exit('データベース接続失敗。'.$e->getMessage());
}

$export_column = "show columns from planets";
$stmt = $dbh->query($export_column);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
	$field[] = $row["Field"];
}

$export_sql = "select * from planets";
$file_path = "csv/planets.csv";
$export_csv_title = $field;

foreach($export_csv_title as $key => $val){
	$export_header[] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8');
	}

	if(touch($file_path)){
		$file = new SplFileObject($file_path, "w");

		$file->fputcsv($export_header);
		$stmt = $dbh->query($export_sql);

		while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
			$file->fputcsv($row);
		}
		$dbh = null;

	}

echo "done";

カラム名だけ取得のニーズはあるので、その命令文を作っても良いように思ったが、、、
MySQL8.0のGithubレポを見ると軽々しく言えんな。。
https://github.com/mysql/mysql-server/blob/8.0/sql/sql_select.cc

slackに脆弱性情報をpost

function send_to_slack($message){
	$webhook_url = 'https://hooks.slack.com/services/hogehoge';
	$options = array(
		'http' => array(
		'method' => 'POST',
		'header' => 'Content-Type: application/json',
		'content' => json_encode($message),
	  )
	);
	$response = file_get_contents($webhook_url, false, stream_context_create($options));
	return $response === 'ok';
}

$message = array(
	'channel' => '#general',
	'username' => '脆弱性情報',
	'icon_emoji' => ':warning:',
	'text' => $string,
);

send_to_slack($message);

おおおおおおお、できたー

とりあえず、リファクタリングしよう

ipa RSSを取得

<?php 
$target_day = date('Y/m/d', strtotime('-1 day'));
$xml = "https://jvndb.jvn.jp/ja/rss/jvndb_new.rdf";

$xmlData = simplexml_load_file($xml);
foreach ($xmlData->item as $entry){
  $dc = $entry->children('http://purl.org/dc/elements/1.1/');
  $day = date('Y/m/d', strtotime($dc->date));
  if($day == $target_day){
      $string.= date('Y/m/d h:i', strtotime($dc->date))."<br>";
      $string.= $entry->title."<br>";
      $string.= $entry->link."<br>";
  }
}
?>
<html>
<body>
	<?php echo $string; ?>
</body>
</html>

OK、次はslack webhook

php.ini session.save_handler

/etc/php.ini

[Session]
; Handler used to store/retrieve data.
; http://php.net/session.save-handler
session.save_handler = files

session.save_hanlder defines the hanlder to use when saving and retrieving data related to the session. The default is files. Npte that each extension can use its own save_handler.

先ほどElastiCacheで作成したmemcacheのエンドポイントをphp.iniに設定する

;session.save_handler = files
;session.save_path = "/tmp"
session.save_handler = "memcached"
session.save_path = "php-session.xxxxx.cfg.apne1.cache.amazonaws.com:11211""

続いて動作確認

session_start();
echo "This is Web Server 1<br>";

if (isset($_SESSION["username"])){
	echo $_SESSION["username"];
} else {
	$_SESSION["username"] = "hoge";
}

なるほど、sessionを共有する両方のphp.iniファイルで、エンドポイントを指定して共有しているのね。

$m = new Memcached();
$m->addServer('localhost', 11211);
$m->set('foo', 'var',60);
var_dump($m->get('foo'));
$m->add('hoge', 'fuga', 60);
$m->add('hoge', 'piyo', 60);
var_dump($m->get('hoge'));
$m->flush();
var_dump($m->get('foo'));

Mcrypt

This function is an extensive block algorithm such as CBC, OFB, CFB, ECB cipher modes DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST. Interface to the mcrypt library to support. In addition, it supports RC6 and IDEA, which are described as “not free”.

php zip

インストール済みを確認します。
[vagrant@localhost ~]$ yum list installed | grep zip
bzip2.x86_64 1.0.5-7.el6_0 @anaconda-CentOS-201605220104.x86_64/6.8
bzip2-devel.x86_64 1.0.5-7.el6_0 @base
bzip2-libs.x86_64 1.0.5-7.el6_0 @anaconda-CentOS-201605220104.x86_64/6.8
gzip.x86_64 1.3.12-24.el6 @base
libzip5.x86_64 1.5.2-1.el6.remi @remi-safe
php-pecl-zip.x86_64 1.15.3-1.el6.remi.7.1 @remi-php71
unzip.x86_64 6.0-5.el6 @base

ん?
php-pecl-zipか??

[vagrant@localhost ~]$ php –ri zip

zip

Zip => enabled
Zip version => 1.15.3
Libzip headers version => 1.5.1
Libzip library version => 1.5.2

はいってるっぽいですね。
これのこと?

php70-zipとphp-pecl-zipの違いが分からんぞ。

fsockopen – smtp

Open an internet connection or Unix domain socket connection.

$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if(!$fp){
	echo "$errstr ($errno)<br>\n";
} else {
	$out = "GET / HTTP/1.1\r\n";
	$out .= "Host: www.example.com\r\n";
	$out .= "Connection: Close\r\n\r\n";
	fwrite($fp, $out);
	while (!feof($fp)){
		echo fget($fp, 128);
	}
	fclose($fp);
}

Laravelでindexを作成、追加する方法

Schma::create('books', function(Blueprint $table){
	$table->increments('id');
	$table->string('title')->index();
	$table->string('isbn')->unique();
	$table->integer('price');
	$table->integer('author_id');
	$table->timestamps();
});


Schema::table('books', function(Blueprint $table){
	$table->index('title');
});

Schema::table('author_book', function(Blueprint $table){
	$table->index(['author_id', 'book_id']);
});

$table->dropIndex('books_title_index');