[CodeIgniter]BaseController

共通関数を設定する時は必要。
各ControllerはこのBaseControllerをextendsする。しなくてもよい。

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class BaseController extends CI_Controller {

	public function __construct(){
		parent::__construct();

		if(!isset($_SERVER['PATH_INFO'])){
			$_SERVER['PATH_INFO'] = strtok($_SERVER['REQUEST_URI'],'?');
		}
		$this->data['class'] = $this->router->class;
		$this->data['method'] = $this->router->method;
		$this->data['uri'] = uri_string();

		//ログインしている
		if($this->session->userdata("is_logged_in")){
			//ログインページの時 -> ホームへリダイレクト
			if(in_array($this->data['class'],array('login'))){
				redirect('/');
			}

		//ログインしてない
		}else{
			//ログインページではない && 登録ページではない -> ログインページへリダイレクト
			if (!in_array($this->data['class'], array('login', 'regist'))) {
				redirect('/login/');
			}
		}
	}
	protected function get_template_name($name='')
	{
		return $this->get_class_method_string($name, '/', 2);
	}
	protected function get_class_method_string($name = '',$delimiter = '/',$backtrace_count = 1)
	{
		if(!empty($name)){
			return strtolower(get_class($this)) . $delimiter . $name;
		}
		$backtraces = debug_backtrace($limit=2);
		return strtolower(get_class($this)) . $delimiter . $backtraces[$backtrace_count]['function'];
	}
	protected function has_post_data()
	{
		return !empty($this->input->post());
	}
	protected function post($index = NULL, $xss_clean = NULL, $default = '')
	{
		$data = $this->input->post($index, $xss_clean);
		return empty($data) ? $default : $data;
	}
	public function view($template='',$data=[],$header='common/header',$footer='common/footer'){
		$this->load->view($header, $data);
		if(is_array($template)){
			foreach($template as $tmpl){
				$this->load->view($tmpl, $data);
			}
		}else {
			$this->load->view($template, $data);
		}
		$this->load->view($footer,$data);
	}
	protected function var_dump($data = null)
	{
		echo '<pre>';
		if(empty($data)){
			var_dump($this->data);
		}else{
			var_dump($data);
		}
		echo '</pre>';
	}
}

[PHP,MySQL]生年月日から年齢を算出する

生年月日から年齢を算出する

■PHP

$birth = '1952-01-26 00:00:00';
$age = (int) ((date('Ymd') - preg_replace('/([\- ]|[0-9]{2}:[0-9]{2}:[0-9]{2})/','',$birth)) / 10000);
echo $age;

結果

65

■MySQL

new_users

id name birth
1 1-名前 1941-01-26 17:30:56
2 2-名前 1952-07-07 00:30:56
3 3-名前 1976-09-02 17:30:56
4 4-名前 1990-05-13 05:00:00
5 5-名前 2016-11-26 17:30:56
6 6-名前 1999-04-01 11:11:11

SQL

SELECT
id,
name,
birth,
DATE_FORMAT(birth, '%Y%m%d') AS tmp_birth,
DATE_FORMAT(NOW(), '%Y%m%d') AS now_date,
FLOOR((DATE_FORMAT(NOW(), '%Y%m%d') - DATE_FORMAT(birth, '%Y%m%d')) / 10000) AS age
FROM new_users
ORDER BY id ASC

結果

id name birth tmp_birth now_date age
1 1-名前 1941-01-26 17:30:56 19410126 20170126 76
2 2-名前 1952-07-07 00:30:56 19520707 20170126 64
3 3-名前 1976-09-02 17:30:56 19760902 20170126 40
4 4-名前 1990-05-13 05:00:00 19900513 20170126 26
5 5-名前 2016-11-26 17:30:56 20161126 20170126 0
6 6-名前 1999-04-01 11:11:11 19990401 20170126 17

[CakePHP 3.x]独自findメソッド2パターン

controller

$this->AdAddress = TableRegistry::get('AdAddress');
$this->AdAddress->find('jeff',['limit' => 30]);
$this->AdAddress = TableRegistry::get('AdAddress');
$this->AdAddress->find('jack');

AdAddressTable.php

<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\Table;

class AdAddressTable extends TableEx
{
	public function findJeff(Query $query, array $options)
	{
		return $query->group(['city_id'])->order(['id' => 'ASC'])->all();
	}
	public function findJack(Query $query, array $options)
	{
		return $this->find()->group(['city_id'])->order(['id' => 'ASC'])->limit(3);
	}
}

[PHP]mb_send_mail@XAMPP

mb_send_mail@XAMPP

・php.ini
SMTP=smtp.gmail.com
smtp_port=587
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

・sendmail.ini
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
auth_username=***@gmail.com
auth_password=***

・GMailアカウント
アカウント->ログインとセキュリティ->安全性の低いアプリの許可:有効

上記設定では送れなかった

・php.ini
SMTP=localhost
smtp_port=25
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

・sendmail.ini
smtp_server=localhost
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log

auth_username=***@gmail.com
auth_password=***

・GMailアカウント
アカウント->ログインとセキュリティ->安全性の低いアプリの許可:有効

stunnelをインストール&起動

上記の設定で送れた

PHPソースは下記

<?php
header('Content-Type: text/html; charset=UTF-8');

mb_language('ja');
mb_internal_encoding("UTF-8");

if (mb_send_mail('****@gmail.com','テスト送信-タイトル','テスト本文','From: ****@gmail.com')) {
echo '送信成功';
} else {
echo '送信失敗';
}
?>

https://www.stunnel.org/downloads.html

[PHP]URLを取得

URLを取得

$url = (empty($_SERVER["HTTPS"]) ? "http://" : "https://") . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]

[PHP]暗号化・複合化

暗号化・複合化

define('KEY', 'bsrNaTwou3PJJbUHMVp20BW0JFxszbOdTaYTtY2jD26TxNFZ');//getRandomStr(48)で取得
define('IV', 'rfKvr+rLztklJ0/6hc8ZmrILlMLVoan6ltu/SR2Bvzg=');//getCryptIV()で取得

$str='あいうえお';

$crypted_str = getEncrypt($str);
echo $crypted_str;
echo '<br/><br/>';
$decrypted_str = getDecrypt($crypted_str);
echo $decrypted_str;
exit;

function getEncrypt($data) {
    $resource = mcrypt_module_open('rijndael-256', '', 'ofb', '');
    $iv = base64_decode(str_rot13(IV));
    $ks = mcrypt_enc_get_key_size($resource);
    $key = substr(md5(KEY), 0, $ks);
    mcrypt_generic_init($resource, $key, $iv);
    $encrypt = mcrypt_generic($resource, $data);
    mcrypt_generic_deinit($resource);
    mcrypt_module_close($resource);
    return base64_encode($encrypt);
}
function getDecrypt($data) {
    $resource = mcrypt_module_open('rijndael-256', '', 'ofb', '');
    $iv = base64_decode(str_rot13(IV));
    $ks = mcrypt_enc_get_key_size($resource);
    $key = substr(md5(KEY), 0, $ks);
    mcrypt_generic_init($resource, $key, $iv);
    $decrypt = mdecrypt_generic($resource, base64_decode($data));
    mcrypt_generic_deinit($resource);
    mcrypt_module_close($resource);
    return $decrypt;
}
function getCryptIV(){
	$key = getRandomStr(48);
	$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
	$iv  = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	$iv = base64_encode($iv);
	mcrypt_module_close($td);
	return $iv;
}
function getRandomStr($length=8){
	$str='';
	for ($i = 0, $str = null; $i < $length; ) {
		$num = mt_rand(0x30, 0x7A);
		if ((0x30 <= $num && $num <= 0x39) || (0x41 <= $num && $num <= 0x5A) || (0x61 <= $num && $num <= 0x7A)) {
			$str .= chr($num);
			$i++;
		}
	}
	return $str;
}

[PHP]INSERT文を作る

INSERT文を作る

echo getInsertQueryByKey('system_table', array('name','gender'), array( array('jeff','male'), array('pola','female') ) );

function getInsertQueryByKey($tableName,$columns,$datas){

	//SQLite古いバージョン
	$w=array();

	$column = implode(',', $columns);
	$query="INSERT INTO {$tableName} ({$column}) SELECT ";
	$tmp=array();
	foreach ($columns as $index => $columnName) {
		$tmp[] = "'". $datas[0][$index] . "'" . ' AS ' . $columnName;
	}
	$query .= implode(', ', $tmp);
	$w[]=$query;

	foreach ($datas as $index => $data) {
		if($index<1)continue;
		$tmp=array();
		foreach ($columns as $index2 => $columnName) {
			$tmp[]=$data[$index2];
		}
		$w[]="'".implode("', '", $tmp)."'";
	}

	return implode(' UNION ALL SELECT ', $w).';';

	/* MySQL or SQLite(バージョン 3.7.11以降)
	$queryValues=array();
	foreach ($datas as $index => $value) {
		$values=array();
		foreach ($value as $index2 => $value2) {
			$values[]="'".$value2."'";
		}
		$queryValues[]='('.implode(',', $values).')';
	}

	$column=implode(',', $columns);
	$value=implode(',', $queryValues);
	$sql="INSERT INTO {$tableName} ({$column}) VALUES {$value};";
	return $sql;
	*/
}