PHP:プロになるためのPHPプログラミング入門 サンプル環境構築 5

公開:2026.05.22(金) 14:01

プロになるためのPHPプログラミング入門 サンプル環境構築

前回記事「PHP:プロになるためのPHPプログラミング入門 サンプル環境構築 4」の続き。

以下書籍に付属するサンプルの実行環境を構築する。
プロになるためのPHPプログラミング入門」(ISBN 978-4-7741-4972-1)

環境は以下記事のものを使用
PHP:プロになるためのPHPプログラミング入門 サンプル環境構築

サーバのバージョン: 8.0.46 - MySQL Community Server - GPL

A.3 MySQLの設定 / A.3.2 郵便番号データテーブル(zipcodes)の作成 (P.321)

1. ppadminユーザーでMySQLに接続
MySQLコンテナのコンソールで ppdbデータベース ppadminユーザーでMySQLに接続する。
mysql -u ppadmin -p ppdb

実行結果:
bash-5.1# mysql -u ppadmin -p ppdb
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

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

Copyright (c) 2000, 2026, Oracle and/or its affiliates.

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>

2. zipcodesテーブルの作成
MySQLに ppdbデータベース、ppadminユーザーでに接続し サンプル prophp.sql の 41~48行目 の zipcodes テーブル作成SQLを実行する。
CREATE TABLE zipcodes (
jiscode  VARCHAR(8),
zipcode  VARCHAR(8),
pref     VARCHAR(128),
city     VARCHAR(128),
town     VARCHAR(128),
townkana VARCHAR(128)
);

実行結果:
mysql> CREATE TABLE zipcodes (
town     VARCHAR(128),
townkana VARCHAR(128)
);    -> jiscode  VARCHAR(8),
    -> zipcode  VARCHAR(8),
    -> pref     VARCHAR(128),
    -> city     VARCHAR(128),
    -> town     VARCHAR(128),
    -> townkana VARCHAR(128)
    -> );
Query OK, 0 rows affected (0.05 sec)

2. 郵便番号データのロード
2-1. KEN_ALL.ZIPのダウンロード
郵便番号データを郵便局のホームページからダウンロードするが URL が書籍記載のものから変更になっている。
正しいURL:https://www.post.japanpost.jp/service/search/zipcode/download/

上記から「住所の郵便番号(CSV形式)」→ 「読み仮名データの促音・拗音を小書きで表記しないもの」または「読み仮名データの促音・拗音を小書きで表記するもの」のリンクより "全国一括" をクリック

ここから KEN_ALL.ZIP をダウンロードし解凍、

このファイルをテキストエディタで開き UTF-8(BOMなし) 改行コード LF で保存しなおす。

サクラエディタの場合は KEN_ALL.CSV を開いたあと「名前を付けて保存」より
・文字コードセットを "UTF-8" (BOMのチェックは外す)
・改行コード LF(UNIX)
を指定し[保存]

2-2. コンテナへのコピー
編集した KEN_ALL.CSV を MySQLコンテナにコピーする。
KEN_ALL.CSV は Windowsの D:\temp\KEN_ALL.CSV として保存、している場合は、
xxxxxxxx@yyyy:~/docker/php$ docker cp /mnt/d/temp/KEN_ALL.CSV d094e1650051:~
Successfully copied 18.9MB (transferred 18.9MB) to d094e1650051:/

MySQLコンテナの bash で MySQL に接続しCSVをロードする。
実行結果:エラー
bash-5.1# mysql -u ppadmin -p ppdb
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

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

Copyright (c) 2000, 2026, Oracle and/or its affiliates.

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> LOAD DATA LOCAL INFILE "/KEN_ALL.CSV" INTO TABLE zipcodes
    -> FIELDS TERMINATED BY ','
    -> ENCLOSED BY '"'
    -> LINES TERMINATED BY '\n'
    -> (jiscode, @dmy, zipcode, @dmy, @dmy, townkana, pref, city, town,
;    -> @dmy, @dmy, @dmy, @dmy, @dmy, @dmy);
ERROR 3948 (42000): Loading local data is disabled; this must be enabled on both the client and server sides

原因:セキュリティ上の理由から、ローカルファイルの読み込み機能(LOCAL_INFILE)が無効化されているため

サーバ側の設定を有効にする
現在のlocal_infile設定確認:→ "OFF" なので無効になっている
mysql> show variables like 'local_infile'
    -> ;
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | OFF   |
+---------------+-------+
1 row in set (0.05 sec)

設定を有効にする
rootでログインする
bash-5.1# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 289
Server version: 8.0.46 MySQL Community Server - GPL

Copyright (c) 2000, 2026, Oracle and/or its affiliates.

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.
以下コマンドを実行し local_infile を有効にする。
mysql> SET GLOBAL local_infile = 1;
Query OK, 0 rows affected (0.00 sec)
設定変更されたことを確認
mysql> show variables like 'local_infile'
    -> ;
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | ON    |
+---------------+-------+
1 row in set (0.03 sec)

郵便番号データのロード
MySQLにppadminユーザでログインする。その際 "--local-infile=1" オプションを付けること。
実行結果:
bash-5.1# mysql --local-infile=1 -u ppadmin -p ppdb
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

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

Copyright (c) 2000, 2026, Oracle and/or its affiliates.

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.

prophp.sql の 50~55行目のSQLを実行する。
CSVのパスが /home/ppuser/KEN_ALL.CSV となっているが、今回は ROOTにコピーしたのでこの点のみ修正。
実行結果:OK!
mysql> LOAD DATA LOCAL INFILE "/KEN_ALL.CSV" INTO TABLE zipcodes
    -> FIELDS TERMINATED BY ','
    -> ENCLOSED BY '"'
    -> LINES TERMINATED BY '\n'
    -> (jiscode, @dmy, zipcode, @dmy, @dmy, townkana, pref, city, town,
    -> @dmy, @dmy, @dmy, @dmy, @dmy, @dmy);
Query OK, 124822 rows affected (1.19 sec)
Records: 124822  Deleted: 0  Skipped: 0  Warnings: 0

A.3.3 ユーザ情報テーブルの作成 (P.323)

第3、第4、第5章で使用する usersテーブル を作成、
ログイン認証機能で認証を通過させるため、ユーザ (ユーザ名:ppuser) を1人分登録する

1. NySQLに接続
MySQLに接続し ppdbデータベースを選択
bash-5.1# mysql -u ppadmin -p ppdb
実行結果:OK!
bash-5.1# mysql -u ppadmin -p ppdb
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

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

Copyright (c) 2000, 2026, Oracle and/or its affiliates.

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.

2. userテーブル作成
prophp.sql の 60~65行目のSQLを実行する。
実行結果:
mysql> CREATE TABLE users(
 NULL AUTO_INCRE    -> id          INT UNSIGNED NOT NULL AUTO_INCREMENT,
    -> username    VARCHAR(50),
    -> password    VARCHAR(70),
    -> PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.03 sec)

3. パスワードの暗号化
3-1. 管理者用パスワードの作成
管理者用のパスワード (英数字で10~100文字まで) を作成する。
今回は練習なので "passwordpassword" にした。
ランダムな文字列とする場合は以下の過去記事を参照し作成する。
Linux:ランダム文字列の生成方法
Windows;ランダム文字列の生成方法
PHP:ランダム文字列の生成方法

3-2. ソルト値の作成
ランダムな英数字からなる40文字以上の文字列を作成する。
今回は PHPコンテナで「PHP:ランダム文字列の生成方法」の手順を使った。
実行結果:
root@3d8258bc2177:/var/www/html# php -a
Interactive shell

Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
php > echo bin2hex(random_bytes(32));
Xdebug: [Step Debug] Could not connect to debugging client. Tried: host.docker.internal:9003 (through xdebug.client_host/xdebug.client_port).
ee8ae119580ff4566963ed45d12504271deb22c17aa1aba8f0c58b82f2894fa0

3-3. 注意点
ソルトを生成しハッシュ化する方法は非推薦
PHPの password_hash 関数を使えばソルトはPHPが内部で自動生成・管理してくれるのでこの方法を使うべき
// パスワードを安全にハッシュ化(ソルトはPHPが内部で自動生成・管理してくれます)
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

// 認証時の検証方法
if (password_verify($inputPassword, $hashedPassword)) {
    // ログイン成功
}

3-4. ハッシュ取得
3-4-1. PHPコンテナで prophp.sql 68行目のコマンドを実行しハッシュを取得する
実行結果:
root@3d8258bc2177:/var/www/html# php -r 'echo(hash("sha256", "ee8ae119580ff4566963ed45d12504271deb22c17aa1aba8f0c58b82f2894fa0passwordpassword")."\n");'
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
Xdebug: [Step Debug] Could not connect to debugging client. Tried: host.docker.internal:9003 (through xdebug.client_host/xdebug.client_port).
af84fa5205f779964eba6ebfafe0d50f0545c030a8fea23f081f4a258237a168

3-4-2. MySQLコンテナで 3.4.1.で求めたハッシュを prophp.sql 73行目のSQLを実行し登録する
実行結果:
xxxxxxxx@yyyy:~/docker/php$ docker exec -it d094e1650051 /bin/bash
bash-5.1# mysql -u ppadmin -p ppdb
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

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

Copyright (c) 2000, 2026, Oracle and/or its affiliates.

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> INSERT INTO users VALUES(0, 'ppuser', 'af84fa5205f779964eba6ebfafe0d50f0545c030a8fea23f081f4a258237a168');
Query OK, 1 row affected (0.02 sec)

A.3.4 ToneMeアプリケーション用のテーブルの作成 (P.324)

1. MySQLコンテナで prophp.sql の 78~82、84~88、90~98行目のSQLを実行しテーブルを作成する
実行結果:
mysql> CREATE TABLE feelings (
    -> id          INT UNSIGNED NOT NULL AUTO_INCREMENT,
    -> name        VARCHAR(50) NOT NULL,
    -> PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.04 sec)

mysql> CREATE TABLE artists (
    -> id          INT UNSIGNED NOT NULL AUTO_INCREMENT,
    -> name        VARCHAR(90) NOT NULL,
    -> PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE tunes (
    -> id          INT UNSIGNED NOT NULL AUTO_INCREMENT,
    -> name        VARCHAR(90) NOT NULL,
ETIME,
PRIMARY K    -> artist_id   INT UNSIGNED NOT NULL,
    -> feeling_id  INT UNSIGNED NOT NULL,
EY (id)
);    -> comcont     TEXT,
    -> modified    DATETIME,
    -> PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.03 sec)

2. MySQLコンテナで prophp.sql の 100~125行目のSQLを実行しテーブルにデータを挿入する
全体のSQLをクリップボード経由でMySQLコンテナに張り付けてもうまく実行できないので、
全体のSQLを WSL(Ubuntu) の ~/docker/php/insert.sql に書き込み MySQLコンテナにコピー、
そしてこのSQLファイルを実行することにした。

実行結果:
xxxxxxxx@yyyy:~/docker/php$ docker cp insert.sql d094e1650051:/
Successfully copied 1.85kB (transferred 3.58kB) to d094e1650051:/
xxxxxxxx@yyyy:~/docker/php$ docker exec -it d094e1650051 /bin/bash
bash-5.1# ls
 KEN_ALL.CSV   boot                         entrypoint.sh   insert.sql   media   proc   sbin   tmp  '~'
 afs           dev                          etc             lib          mnt     root   srv    usr
 bin           docker-entrypoint-initdb.d   home            lib64        opt     run    sys    var
bash-5.1# mysql -u ppadmin -p ppdb < insert.sql
Enter password:
bash-5.1# mysql -u ppadmin -p ppdb
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

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

Copyright (c) 2000, 2026, Oracle and/or its affiliates.

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> select * from artists;
+----+-----------------------+
| id | name                  |
+----+-----------------------+
|  7 | ソフトズ          |
|  8 | 丸見栄子          |
|  9 | コナチーズ       |
| 10 | 上部安埔里       |
| 11 | 森見タマエ       |
| 12 | ピーエッチピー |
+----+-----------------------+
6 rows in set (0.00 sec)


0 件のコメント:

その他の記事