PHP GD で画像処理 (伸縮)

サーバーサイドでの画像処理は、ImageMagick を使ってましたが、脆弱性があり、使用回避することになり、PHP GD の利用に置換予定です。

[ ImageMagick 脆弱性情報 ]

https://www.mbsd.jp/blog/20180831.html

https://qiita.com/yoya/items/2076c1f5137d4041e3aa

https://blog.cybozu.io/entry/2018/08/21/080000[

[ 準備 ]

CentOS7の yum でインストールした7系では、何もしなくても GDライブラリが使えます。

Windows の場合、php.ini に以下の記述を追加して有効化します。

[PHP_GD2]
extension=php_gd2.dll

[ コード例 ]

アプリケーションで、結果はファイルに保存
処理結果情報はJSONで返す


<?php

/**
 * GD 画像ストレッチ
 * argv : 1 : ソースファイル名, 2 : デストファイル名, 3 : 横ピクセルサイズ 
 */
// 引数取得 //
$srcfnm = $argv[1];
$dstfnm = $argv[2];
$new_width = $argv[3];

// ** 縦長算出 ** //
// 画像サイズ取得 //
list($src_width, $src_height, $type) = getimagesize($srcfnm);
$ratio = (float) $src_width / $src_height;
$new_height = (int) ((float) $new_width / (float) $ratio);

//echo $srcfnm." -> ". $dstfnm. "\n";
//echo "PHP GD type:".$type . ":" . $src_width . ":" . $src_height . " => " . $new_width . ":" . $new_height."\n";
// 画像を読み込み再サンプリングして縮小 //
switch ($type) {
  case IMAGETYPE_JPEG:    // 2
    $image = imagecreatefromjpeg($srcfnm);
    break;
  case IMAGETYPE_PNG:     // 3
    $image = imagecreatefrompng($srcfnm);
    break;
  case IMAGETYPE_GIF:     // 1
    $image = imagecreatefromgif($srcfnm);
    break;
}

// 変換 //
$image_p = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $src_width, $src_height);
/* $new_width はキャスト不要 */

// ファイルに出力 //
$res = 1;
try {
  if ($type == IMAGETYPE_JPEG) {
    imagejpeg($image_p, $dstfnm, 100);
  }
  else if ($type == IMAGETYPE_PNG) {
    imagepng($image_p, $dstfnm, 9);
  }
  else {
    imagegif($image_p, $dstfnm, 100);
  }
}
catch (Exception $ex) {
  $res = 0;
}

imagedestroy($image);
imagedestroy($image_p);

// 連想配列に格納 //
$responce = [];
$responce["SrcW"] = $src_width;
$responce["SrcH"] = $src_height;
$responce["DstW"] = (int) $new_width;  // <== 引数のままなので
$responce["DstH"] = $new_height;
$responce["Result"] = $res;

// JSONに変換して出力 //
echo json_encode($responce, JSON_PRETTY_PRINT);

?>

MySQL mysqlコマンド (よく使う)

データベースの変更 : use [ データベース名 ]

mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

データベース一覧 : show databases;

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

テーブル一覧 : show tables;

mysql> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| engine_cost               |
| event                     |
| func                      |
| general_log               |
| gtid_executed             |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| server_cost               |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
31 rows in set (0.00 sec)

テーブルスキーマ (1) : show create table [ テーブル名 ]

mysql> show create table time_zone;
+-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table     | Create Table                                                                                                                                                                                                                                                                                                                         |
+-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| time_zone | CREATE TABLE `time_zone` (
  `Time_zone_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Use_leap_seconds` enum('Y','N') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'N',
  PRIMARY KEY (`Time_zone_id`)
) /*!50100 TABLESPACE `mysql` */ ENGINE=InnoDB DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT='Time zones' |
+-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

テーブルスキーマ (2) : desc [ テーブル名 ]

mysql> desc m_todou;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| CD     | tinyint(4)  | NO   | PRI | NULL    |       |
| K_NAME | varchar(8)  | NO   |     | NULL    |       |
| H_NAME | varchar(12) | NO   |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

テーブルスキーマ (3) : show full columns from [ テーブル名 ]

mysql> show full columns from m_todou;
+--------+-------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| Field  | Type        | Collation       | Null | Key | Default | Extra | Privileges                      | Comment |
+--------+-------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| CD     | tinyint(4)  | NULL            | NO   | PRI | NULL    |       | select,insert,update,references |         |
| K_NAME | varchar(8)  | utf8_general_ci | NO   |     | NULL    |       | select,insert,update,references |         |
| H_NAME | varchar(12) | utf8_general_ci | NO   |     | NULL    |       | select,insert,update,references |         |
+--------+-------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
3 rows in set (0.00 sec)

ストアドスキーマ : show create procedure [ ストアドプロシージャー名 ]

mysql> show create procedure test \G;
*************************** 1. row ***************************
           Procedure: test
            sql_mode: STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
    Create Procedure: CREATE DEFINER=`root`@`localhost` PROCEDURE `test`(
        IN `tstvalue` INT
)
    COMMENT 'nothing to reffer'
BEGIN
SELECT tstvalue;
END
character_set_client: utf8mb4
collation_connection: utf8mb4_general_ci
  Database Collation: utf8_general_ci
1 row in set (0.00 sec)

ERROR:
No query specified

ファンクションスキーマ : show create function [ ファンクション名 ]

mysql> show create function fc_csv_idxtxt \G;
*************************** 1. row ***************************
            Function: fc_csv_idxtxt
            sql_mode: NO_ENGINE_SUBSTITUTION
     Create Function: CREATE DEFINER=`root`@`localhost` FUNCTION `fc_csv_idxtxt`(
        `src` VARCHAR(9000),
        `idx` smallint
) RETURNS varchar(9000) CHARSET utf8
    COMMENT 'CSV列指定位置取得'
begin

declare rtntxtcsv varchar(9000) default '';

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(src, ',', idx), ',', -1) INTO rtntxtcsv;

return rtntxtcsv;

end
character_set_client: utf8mb4
collation_connection: utf8mb4_general_ci
  Database Collation: utf8_general_ci
1 row in set (0.00 sec)

ユーザー一覧 : select host,user,plugin from mysql.user;

mysql> select host,user,plugin from mysql.user limit 0, 3;
+-----------+------------------+-----------------------+
| host      | user             | plugin                |
+-----------+------------------+-----------------------+
| localhost | mysql.infoschema | caching_sha2_password |
| localhost | mysql.session    | caching_sha2_password |
| localhost | mysql.sys        | caching_sha2_password |
+-----------+------------------+-----------------------+
3 rows in set (0.00 sec)

終了 : exit or quit or \q

[root@localhost ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 592
Server version: 8.0.13 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> exit
Bye
[root@localhost ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 593
Server version: 8.0.13 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> quit
Bye
[root@localhost ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 596
Server version: 8.0.13 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> \q
Bye
[root@localhost ~]# 

MySQL SQLの結果に連番を振る

 

 

 

(SELECT @num := -1) as dmy で連番用の仮想テーブルを記述、
@num := @num + 1 AS ID のような列を記述します。

mysql> SELECT
    ->   @num := @num + 1 AS ID,
    ->   CD,
    ->   K_NAME, H_NAME
    -> FROM
    ->   (SELECT @num := -1) as dmy,
    ->   m_todou
    -> LIMIT 0, 5;
+------+----+-----------+--------------------+
| ID   | CD | K_NAME    | H_NAME             |
+------+----+-----------+--------------------+
|    0 |  1 | 北海道    | ほっかいどう       |
|    1 |  2 | 青森県    | あおもりけん       |
|    2 |  3 | 岩手県    | いわてけん         |
|    3 |  4 | 宮城県    | みやぎけん         |
|    4 |  5 | 秋田県    | あきたけん         |
+------+----+-----------+--------------------+
5 rows in set (0.00 sec)

mysql> show create table m_todou;
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                                                                                                                    |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| m_todou | CREATE TABLE `m_todou` (
  `CD` tinyint(4) NOT NULL,
  `K_NAME` varchar(8) NOT NULL,
  `H_NAME` varchar(12) NOT NULL,
  PRIMARY KEY (`CD`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='都道府県マスタ'        |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> 

 

 

MySQL 8 GRANT文で user が追加出来ない

MySQL5系からのくせで、grantで新規ユーザー追加しようとすると、エラーになります。

create user してから grant することになります。

 

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8614
Server version: 8.0.13 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> grant all on *.* to 'newuser'@'localhost' identified by 'newuser';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'identified by 'newuser'' at line 1
mysql> 

詳しくは、ここに書いておられます。 https://www7390uo.sakura.ne.jp/wordpress/archives/456

山本五十六 : 開戦

是非やれといわれれば、初めの半年や一年は、ずいぶん暴れてごらんにいれます。

しかし二年、三年となっては、全く確信は持てません。

三国同盟ができたのは致し方ないが、かくなった上は、日米戦争の回避に極力ご努力を願いたいと思います。

[商品価格に関しましては、リンクが作成された時点と現時点で情報が変更されている場合がございます。]

山本五十六のことば [ 稲川明雄 ]
価格:1100円(税込、送料無料) (2022/12/27時点)