PHP

[PHP]Imagickサンプル

Imagickサンプル

<?php
$_data = array(
        'dir'       => './output/',
        'filename'  => date('YmdHis'),
        'filetype'  => 'png',
        'fontsize'  => 24,
        'width'     => 1000,
        'height'    => 640,
        'text'      => 'sample text',
        'textcolor' => '000000',
        'color'     => 'eeeeee',
        );
$filepath = realpath($_data['dir']).DIRECTORY_SEPARATOR.$_data['filename'];

$draw = new ImagickDraw();
$draw->setFont( realpath('./font/GenEiGothicP-Regular.otf') );
$draw->setFontSize($_data['fontsize']);
$draw->setFillColor(new ImagickPixel('#'.$_data['textcolor']));
$draw->setTextAlignment(Imagick::ALIGN_CENTER);
$draw->annotation($_data['width']*0.5,$_data['height']*0.5, $_data['text'] );

$canvas = new Imagick();
$canvas->newImage($_data['width'], $_data['height'], new ImagickPixel('#'.$_data['color']), $_data['filetype']);
$canvas->drawImage($draw);
$canvas->writeImage($filepath);
$canvas->clear();

[CodeIgniter]email

email

views/mail/user_mail.php

メール本文

libraries/MY_Email.php

<?php
class My_Email extends CI_Email {
	public function __construct(array $config = array())
	{
		parent::__construct($config);
	}

	/**
	 * get Body by tempalte
	 *
	 * @param	string
	 * @param   array
	 * @return	string
	 */
	public function get_template_contents($template, $values = array())
	{
		$file = VIEWPATH . $template;
		if(!file_exists($file)){
			$file .= '.php';
		}

		extract($values);
		ob_start();
		include($file);
		$contents = ob_get_contents();
		ob_end_clean();
		return $contents;
	}
}

config/config_mail.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['user_mail'] = array(
    'from'      => 'from@sample.co.jp',
    'from_name' => 'fromName',
    'subject'   => 'メールタイトル',
);

controller

$this->load->library('email');
$config_key = 'user_mail';
$this->load->config('config_mail');
$user_mail = $this->config->item($config_key);

$mail = new PHPMailer();
$mail->CharSet = "iso-2022-jp";
$mail->Encoding = "7bit";
$mail->AddAddress('to@sample.co.jp');
$mail->From = $user_mail['from'];
$mail->FromName = mb_encode_mimeheader(mb_convert_encoding($user_mail['from_name'], "JIS", "UTF-8"));
$mail->Subject = mb_encode_mimeheader(mb_convert_encoding($user_mail['subject'], "JIS", "UTF-8"));
$body = $this->email->get_template_contents('mail/'.$config_key);
//$mail->Body = mb_convert_encoding($body, "JIS", "UTF-8");
$mail->Body = mb_convert_encoding($body,"ISO-2022-JP-ms","UTF-8");//機種依存文字が含まれるならこちら
$result = $mail->Send();

[CodeIgniter]LoginControllerサンプル

LoginControllerサンプル

<?php
require_once 'BaseController.php';
class Login extends BaseController {
    protected $data = array();
    public function __construct()
    {
        parent::__construct();
        $this->load->model('admins');
    }

    public function index()
    {
        //postデータあり -> バリデーション
        if ($this->has_post_data()) {
            //バリデーション
            $result = $this->admins->validate('login');
            //バリデーションOK
            if($result){
                //メアド、パスワードDB照合
                $result = $this->admins->login();
                //メアド、パスワードDB照合OK
                if($result){
                    redirect('/');//ログイン済みホーム
                    return;
                }
            }
        }

        $this->view($this->get_template_name(),$this->data);
    }
}

AdminsModel

<?php
require_once 'BaseModel.php';
class Admins extends BaseModel {
	public $name = 'admins';
	public $validation = array(
		'login' => array(
			array(
				'field' => 'email',
				'label' => 'メールアドレス',
				'rules' => 'trim|xss_clean|required',
				'errors' => array(
					'required' => '%sは必須です。',
					'custom_validation' => '%sかパスワードが異なります。',
				),
			),
			array(
				'field' => 'password',
				'label' => 'パスワード',
				'rules' => 'trim|xss_clean|required',
				'errors' => array(
					'required' => '%sは必須です。',
				),
			),
		),
	);
	public function __construct()
	{
		parent::__construct();
	}
	public function login($email='',$password='')
	{
		if(empty($email)){
			$email = $this->post('email');
		}
		if(empty($password)){
			$password = $this->post('password');
		}
		$this->db->where('email',$email);
		$result = $this->db->get($this->name);
		if($result->num_rows() < 1){
			return false;
		}
		$result_data = $result->result('array');
		$data = array_shift($result_data);
		$login = password_verify($password,$data['password']);
		if($login){
			//ログイン成功
			$data = array(
				"email" => $email,
				"is_logged_in" => 1,
				"user_id" => $data['id'],
			);
			$this->session->set_userdata($data);
		}
		return $login;
	}
}

[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