ラベル PHP の投稿を表示しています。 すべての投稿を表示
ラベル PHP の投稿を表示しています。 すべての投稿を表示

PHP:MySQLiを使ってSELECT文を実行 #2

公開:2026.06.07(日) 15:25

MySQLiを使ってSELECT文を実行 #2

前回の記事(PHP:MySQLiを使ってSELECT文を実行)ではバインド変数を使ったSELECT文の実装方法だったが、バインド変数を使わない場合はもう少し簡単に記述することができる。

1. query メソッドの実行
queryメソッドの引数にSQLを渡すことでクエリを実行する
$sql = 'SELECT COUNT(*) FROM zipcodes';
$result = $dbh->query($sql))

2. fetch_row メソッドで結果セットの次の行を配列で取得
$row = $result->fetch_row();

3. 最後に mysqli_result::close メソッドで結果セットをクローズする
$result->close();


PHP:MySQLiを使ってSELECT文を実行

公開:2026.06.07(日) 13:44

MySQLiを使ってSELECT文を実行

MySQLiを使ってSELECT文を実行するには、
1. データベースに接続 (PHP:MySQLiを使ったDB接続方法)、

2. 取得したmysqliオブジェクトの stmt_init メソッドを使いステートメントを初期化する
戻り値として mysqli_stmt クラスのオブジェクトを返す。
$sth = $dbh->stmt_init();

3. stmt_init戻り値のmysqli_stmtオブジェクトの prepare メソッドでSQLステートメントを実行するための準備を行う
$sth->prepare($sql)

4. SQLにプレースホルダー(?)が含まれる場合は mysqli_stmtオブジェクトの bind_param メソッドでパラメータに値を当てはめる
メソッドの types引数 には対応するバインド変数の 変数の型 を以下の型文字を結合して指定
説明
iint
dfloat
sstring
bblob

$mincd = '2070000';
$maxcd = '2090000';
$sth->bind_param('ss', $mincd, $maxcd);

5. mysqli_stmtオブジェクトの execute メソッドでSQLを実行する

6. 実行結果を取得するための準備として mysqli_stmtオブジェクトの bind_result メソッドで結果を格納する変数を列の数だけ指定
例:実行するSQL
SELECT zipcode, pref, city, town FROM zipcodes
WHERE zipcode >= ? AND zipcode <= ?
ORDER BY zipcode ASC LIMIT 100

列 zipcode, pref, city, town をそれぞれ変数 $code, $pref, $city, $town へ格納する
$sth->bind_result($code, $pref, $city, $town);

反復可能な結果セットを取得したり、 行をオブジェクトや配列で取得したい場合は get_result メソッドを使用する

6. 実際に結果を取得しバインド変数に格納するには fetch メソッドを使用する
戻り値として、true:成功、false:エラー、null:行データなし が返るので、falseまたはnullが返るまでfetchを繰り返す

while($sth->fetch()){
  echo '<tr><td>',  htmlspecialchars($code, ENT_QUOTES, 'UTF-8');
  echo '</td><td>', htmlspecialchars($pref, ENT_QUOTES, 'UTF-8');
  echo '</td><td>', htmlspecialchars($city, ENT_QUOTES, 'UTF-8');
  echo '</td><td>', htmlspecialchars($town, ENT_QUOTES, 'UTF-8');
  echo '</td></tr>', PHP_EOL;
}

7. 最後にmysqli_stmtオブジェクトの close メソッドを呼び出して終了
$sth->close();


PHP:MySQLiを使ったDB接続方法

公開:2026.06.07(日) 10:29

MySQLiを使ったDB接続方法

mysqliオブジェクトを生成し、以降はこのオブジェクトを操作する。

$dbh = new mysqli(ホスト名, ユーザー名, パスワード, DB名);

ついでに文字コードも指定しておく。
$dbh->set_charset('utf8mb4');


"PHP 学習"

PHP:エラー制御演算子

公開:2026.06.07(日) 09:51

PHP:エラー制御演算子

書籍:プロになるためのPHPプログラミング入門 (ISBN:978-4-7741-4972-1) のサンプルを見ていたら newの前に "@" が付いているものがあった。

例:
$dbh = @new mysqli(	'localhost',	//	ホスト
					'ppguest',		//	ユーザ名
					'GGGGGGGGGG',	//	パスワード
					'ppdb'	);		//	DB名

この "@"マークは "エラー制御演算子" と呼ばれるもで、その式により生成されたエラーメッセージを無視する。(つまりエラーが画面に表示されない)
※ 公式マニュアル: https://www.php.net/manual/ja/language.operators.errorcontrol.php

基本的に使用は避けるべきで、try-catch構文を使って正しく例外処理を行うのが基本形。


"PHP 学習"

PHP:プロになるためのPHPプログラミング入門 10

公開:2026.06.06(土) 22:04

プロになるためのPHPプログラミング入門 10

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

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

PHP:8.3.30
MySQL:8.0.46

リスト 3-1 郵便番号検索プログラム (/ppa/p32mysql.php) (P.121)

サンプルをそのまま実行(http://localhost:8080/prophp_sample/ppa/p32mysql.php)するとエラーが発生する。

Fatal error: Uncaught Error: Class "mysqli" not found in /var/www/prophp_sample/www/ppa/p32mysql.php:4 Stack trace: #0 {main} thrown in /var/www/prophp_sample/www/ppa/p32mysql.php on line 4

対応
Dockerfileを追加、php:8.3-apacheイメージに mysqli を追加するようにする。
# 現在お使いのイメージをベースにします
FROM php:8.3-apache

# mysqli 拡張機能をインストールするコマンドを追加します
RUN docker-php-ext-install mysqli

compose.yamlを修正、php:8.3-apacheの使用をやめ Dockerfileをビルドして使用するように修正。
services:
    php:
      # image: php:8.3-apache
      build: .
      volumes:
        - ./www/html:/var/www/html
        - ./prophp_sample:/var/www/prophp_sample
        - ./php.ini-debug:/usr/local/etc/php/php.ini
        - ./prophp_sample.conf:/etc/apache2/conf-available/prophp_sample.conf
      extra_hosts:
        - "host.docker.internal:host-gateway"
      ports:
        - "8080:80"
      command: >
        sh -c "a2enconf prophp_sample && apache2-foreground"
   :

以下の記事は上記を踏まえて修正
PHP 学習:プロになるためのPHPプログラミング入門 サンプル環境構築

エラー その2

上記対応後の実行結果:
Fatal error: Uncaught mysqli_sql_exception: No such file or directory in /var/www/prophp_sample/www/ppa/p32mysql.php:4 Stack trace: #0 /var/www/prophp_sample/www/ppa/p32mysql.php(4): mysqli->__construct('localhost', 'ppguest', Object(SensitiveParameterValue), 'ppdb') #1 {main} thrown in /var/www/prophp_sample/www/ppa/p32mysql.php on line 4

接続先"localhost”、パスワード"GGGGGGGGGG" になっているのでこの部分を修正、
接続先は別のDockerコンテナ"db"、パスワードは今回 "passwordpassword" で設定した。
<?php
//!	MySQLiのプリペアド・ステートメントを使うサンプル
//	MySQLに接続する
$dbh = @new mysqli(	'db',	//	ホスト
					'ppguest',		//	ユーザ名
					'passwordpassword',	//	パスワード
					'ppdb'	);		//	DB名

結果

今回のサンプルはHTML_Tempalte_Flexyを使っていないので、これで動くようになった。


PHP:プロになるためのPHPプログラミング入門 9

公開:2026.05.27(水) 07:33

プロになるためのPHPプログラミング入門 9

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

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

PHP:8.3.30
MySQL:8.0.46

1.6.4 セッション管理を行うアプリケーション (P.77)

サンプルを実行するも当然エラーになる。
http://localhost:8080/prophp_sample/ppa/p16sessq.php

Fatal error: Uncaught TypeError: PpPage::display(): Argument #2 ($elem) must be of type array, stdClass given, called in /var/www/prophp_sample/www/ppa/p16sessa.php on line 36 and defined in /var/www/prophp_sample/www/ppa/ppPage.php:26 Stack trace: #0 /var/www/prophp_sample/www/ppa/p16sessa.php(36): PpPage->display('p16sessa.html', Object(stdClass)) #1 {main} thrown in /var/www/prophp_sample/www/ppa/ppPage.php on line 26

※ 書籍では "p41sassq.php" となっているが "p16sessa.php" の誤りを思われる。

◆ リスト1-17 質問画面テンプレート (p16sessq.php)
オブジェクトを配列に変更、
HTML_Template_Flexy_Element オブジェクトを渡しているところは単純に値のみ配列にセットするようにした。

修正前:
$dobj = new stdClass();
$dobj->qno = (string)($qno + 1);
$dobj->qstr = $qmsg[$qno][0];
$elem['a1'] = new HTML_Template_Flexy_Element;
$elem['a1']->setValue($qmsg[$qno][1]);
$elem['a2'] = new HTML_Template_Flexy_Element;
$elem['a2']->setValue($qmsg[$qno][2]);
if($qno >= $qcnt){
	$elem['a1f'] = new HTML_Template_Flexy_Element;
	$elem['a1f']->attributes['action'] = 'p16sessa.php';
	$elem['a2f'] = new HTML_Template_Flexy_Element;
	$elem['a2f']->attributes['action'] = 'p16sessa.php';
}
修正後:
$dobj = [
  'qno' => (string)($qno + 1),
  'qstr' => $qmsg[$qno][0],
  'a1' => $qmsg[$qno][1],
  'a2' => $qmsg[$qno][2],
];

if ($qno >= $qcnt) {
	$dobj = array_merge($dobj, [
    'a1f' => [
      'action' => 'p16sessa.php',
    ],
    'a2f' => [
      'action' => 'p16sessa.php',
    ],
	]);
}

◆ リスト1-15 質問画面テンプレート (p16sessq.html)
formのaction属性、inputのvalue属性を追加した。

修正前:
<p><span>Q{qno:hs}</span>{qstr:hs}</p>
<form name="a1f" method="post" action="p16sessq.php">
<input type="submit" name="a1">
<p><span>Q{qno:hs}</span>{qstr:hs}</p>
<form name="a1f" method="post"

修正後:
<p><span>Q{{ qno }}</span>{{ qstr }}</p>
<form name="a1f" method="post" action="{{ a1f.action }}">
<input type="submit" name="a1" value="{{ a1 }}">
<form name="a2f" method="post" action="{{ a2f.action }}">
<input type="submit" name="a2" value="{{ a2 }}">

◆ リスト1-18 結果画面プログラム (/ppa/p16sessa.php)
修正前:
$dobj = new stdClass();
$dobj->ans = $amsg[$ans];
$dobj->ok = $ans ? true : false;

修正後:
$dobj = [
	'ans' => $amsg[$ans],
	'ok' => $ans? true: false,
];

◆ 結果画面テンプレート (p16sessa.html)
修正前:
<span>{ans:hs}</span>{if:ok}をおすすめいたします。{end:}

修正後:
<span>{{ ans }}</span>{% if ok %}をおすすめいたします。{% endif %}

参考 (ソース全体)

◆ p16sessa.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>proPHPトラベル</title>
<style type="text/css">
<!--
body { margin:0; padding:0; font-family: Osaka, メイリオ, sans-serif; }
div { margin:20px; }
span { font-size:120%; color:#E61980; padding-right:5px; }
h1 { margin:0; padding:10px; background-color:#0269A8; color:#FFFFFF; }
h2 { border-left: 12px solid #264C73; border-bottom: 2px solid #264C73; padding-left:10px; }
#fm{ padding:20px; background-color: #DCE6F0; border: 1px solid #264C73; }
-->
</style>
</head>
<body>
<h1>proPHPトラベル</h1>
<div>
<h2>おすすめツアー検索結果</h2>
<div id="fm">
<span>{{ ans }}</span>{% if ok %}をおすすめいたします。{% endif %}
</div>
<p><a href="p16sessq.php">おすすめツアー検索にもどる</a></p>
</body>
</html>

◆ p16sessq.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>proPHPトラベル</title>
<style type="text/css">
<!--
body { margin:0; padding:0; font-family: Osaka, メイリオ, sans-serif; }
input {  padding:2px; border: 1px solid #14191E; background: #1980E6; color:#FFFFFF;
font-size: 120%; font-weight: bold; }
input:hover { cursor: pointer; background: #3399FF;}
div { margin:20px; }
span { font-size:120%; color:#E61980; padding-right:5px; }
h1 { margin:0; padding:10px; background-color:#0269A8; color:#FFFFFF; }
h2 { border-left: 12px solid #264C73; border-bottom: 2px solid #264C73; padding-left:10px; }
form { display:inline; }
#fm{ padding:0 20px 20px 20px; background-color: #DCE6F0; border: 1px solid #264C73; }
-->
</style>
</head>
<body>
<h1>proPHPトラベル</h1>
<div>
<h2>おすすめツアー検索</h2>
<p>いくつかの質問に答えていくと、あなたにオススメのツアーを選びます。</p>
<div id="fm">
<p><span>Q{{ qno }}</span>{{ qstr }}</p>
<form name="a1f" method="post" action="{{ a1f.action }}">
<input type="submit" name="a1" value="{{ a1 }}">
</form>
<form name="a2f" method="post" action="{{ a2f.action }}">
<input type="submit" name="a2" value="{{ a2 }}">
</form>
</div>
</div>
</body>
</html>

◆ p16sessa.php
<?php
//!	セッション管理を行うサンプル	proPHPトラベルツアー結果画面
require_once 'ppPage.php';
require_once 'ppSession.php';
//	回答データ
$amsg = array(	'エラーです',
				'西表島ジャングルツアー',	'ボルネオ島鍾乳洞ツアー',
				'夏の熱海温泉ツアー',		'ボラボラ島リゾートツアー',
				'冬の八ヶ岳スキーツアー',	'スイス氷河特急ツアー',
				'紋別流氷ツアー',			'南極クルーズツアー'	);
$ans = 0;

//	セッション管理クラス
$sess = new PpSession('SESSQANDA');
if($sess->sessionExists()){
	$sess->start();
	if($_SERVER['REQUEST_METHOD'] === 'POST'){
		$ans = (int)$sess->get('ans');
		if(isset($_POST['a1'])){
			$ans |= (1 << 2);
		}

		if($ans >= 0 && $ans <= 7){
			$ans ++;
		}
	}
	//	セッション終了処理
	$sess->endProc();
}

//	画面表示処理
$dobj = [
	'ans' => $amsg[$ans],
	'ok' => $ans? true: false,
];
$page = new PpPage;
$page->display('p16sessa.html', $dobj);

◆ p16sessq.php
<?php
//!	セッション管理を行うサンプル	proPHPトラベルツアー質問画面処理
require_once 'ppPage.php';
require_once 'ppSession.php';
//	質問データ
$qmsg = array(	array(	'どこか遠くへ行きたい?', '遠くへ行きた~い', '近場がいいな~'),
				array(	'海と山どっちが好き?', '海が好き', '山が好き'),
				array(	'暑いのと寒いのとでは、どっちが苦手?', '暑いのは苦手', '寒いのは苦手')	);
$ans = 0;					//	回答
$qno = 0;					//	質問番号0~2
$qcnt = count($qmsg) - 1;	//	質問数

//	セッション管理クラス
$sess = new PpSession('SESSQANDA');
if($_SERVER['REQUEST_METHOD'] === 'POST'){
	$sess->start();
	$ans = (int)$sess->get('ans');
	$qno = (int)$sess->get('qno');
	if($qno >= 0 && $qno < $qcnt){
		if(isset($_POST['a1'])){
			$ans |= (1 << $qno);
		}
		$qno ++;
	}
	$sess->set('ans', $ans);
	$sess->set('qno', $qno);
}
else{
	if($sess->sessionExists()){
		$sess->start();
		$sess->endProc();
	}
}

//	画面表示処理
$dobj = [
  'qno' => (string)($qno + 1),
  'qstr' => $qmsg[$qno][0],
  'a1' => $qmsg[$qno][1],
  'a2' => $qmsg[$qno][2],
];

if ($qno >= $qcnt) {
	$dobj = array_merge($dobj, [
    'a1f' => [
      'action' => 'p16sessa.php',
    ],
    'a2f' => [
      'action' => 'p16sessa.php',
    ],
	]);
}
$page = new PpPage;
$page->display('p16sessq.html', $dobj);

◆ ppSession.php
そのまま使用可


PHP:プロになるためのPHPプログラミング入門 8

公開:2026.05.27(水) 07:20

プロになるためのPHPプログラミング入門 8

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

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

PHP:8.3.30
MySQL:8.0.46

1.5.6 HTML_Template_Flexyの制御構文

◆ {foreach:value, value}
◆ {foreach:variable, key, value}
Twigとさほど変わらない
{% for record in records %} {% endfor %}
{% for key, value in records %} {% endfor %}

◆ {if:variable}
◆ {if:method()}
Twigではif:method()は使えないが、さほど変わらない
{% if variable %}{% endif %}

サンプルの実行

◆ リスト 1-13 プログラムファイル (/ppa/f15flexyif.php)
実行したところエラーが発生した。
Fatal error: Uncaught TypeError: PpPage::display(): Argument #2 ($elem) must be of type array, stdClass given, called in /var/www/prophp_sample/www/ppa/p15flexyif.php on line 13 and defined in /var/www/prophp_sample/www/ppa/ppPage.php:26 Stack trace: #0 /var/www/prophp_sample/www/ppa/p15flexyif.php(13): PpPage->display('p15flexyif.html', Object(stdClass)) #1 {main} thrown in /var/www/prophp_sample/www/ppa/ppPage.php on line 26

これは \$page->displayの第2引数に $obj (stdClassクラス) を渡しているため。
現在、第2引数は配列のみ指定可能。
なので全体的に配列に変更する。

<?php
//!	HTML_Template_Flexyのサンプル	if制御構文で表示を制御する
require_once 'ppPage.php';
&page = new PpPage;
// &dobj = new stdClass();
&obj = array();
// &dobj->member = false;
&obj['member'] = false;

//	0: 非会員	1: 会員
&kaiin = 1;
if(&kaiin === 1){
	// &dobj->member = true;
	&obj['member'] = true;
}
&page->display('p15flexyif.html', &obj);

テンプレートのif文もTwigの書式に修正

修正前:
{if:member}
<h2>会員さまへのスペシャル情報</h2>
<p id="kaiin">
会員さまだけに、いちはやくお知らせする新商品情報です。
ご案内は<a href="#">こちら</a>からどうぞ。</p>
{end:}

修正後:
{% if member %}
<h2>会員さまへのスペシャル情報</h2>
<p id="kaiin">
会員さまだけに、いちはやくお知らせする新商品情報です。
ご案内は<a href="#">こちら</a>からどうぞ。</p>
{% endif %}

参考 (サンプル全体)

◆ リスト1-12 テンプレートファイル (p15flexyif.html) (P.70)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style TYPE="text/css">
<!--
h2 {  margin-bottom:0; padding:5px; width:400px; color:#FFFFFF;
background-color:#267333; border-left: 12px solid #990026;
}
#kaiin {  margin-top:0; padding:10px; width:400px; color: #000000;
background-color: #DCF0DF; border: 1px solid #267333;
}
-->
</style>
</head>
<body>
{% if member %}
<h2>会員さまへのスペシャル情報</h2>
<p id="kaiin">
会員さまだけに、いちはやくお知らせする新商品情報です。
ご案内は<a href="#">こちら</a>からどうぞ。</p>
{% endif %}
<h3>当店の人気商品</h3>
<ul>
<li>もりもりうどん</li>
<li>シャッキリドリンク</li>
<li>パパイア大福</li>
</ul>
</body>
</html>

◆ リスト1-13 プログラムファイル (/ppa/f15flexyif.php) (P.71)
<?php
//!	HTML_Template_Flexyのサンプル	if制御構文で表示を制御する
require_once 'ppPage.php';
$page = new PpPage;
$obj = array();
$obj['member'] = false;

//	0: 非会員	1: 会員
$kaiin = 1;
if($kaiin === 1){
	$obj['member'] = true;
}
$page->display('p15flexyif.html', $obj);


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

公開:2026.05.23(土) 08:43

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

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

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

PHP:8.3.30
MySQL:8.0.46

1.5.5 HTML_Template_Flexyとデータベースを組み合わせる (P.64)

検証対象:
・リスト 1-10 p15flexydb.html (P.66)
・リスト 1-11 ppa/p15flexydb.php (P.67)

1. MySQL接続パスワードの変更
~/docker/php/prophp_sample/www/ppa/p15flexydb.php (15行目)
初期パスワードは "GGGGGGGGGG" になっているのでユーザ情報テーブルに登録したパスワードを設定する。
PHP:プロになるためのPHPプログラミング入門 サンプル環境構築 4

2. とりあえずの動作確認
とりあえず http://localhost:8080/prophp_sample/ppa/p15flexydb.php に接続したところエラーが表示された。

Connect Error: 0

3. PDO MySQLドライバーのインストール
PDO MySQLドライバーが必要かもしれないのでインストールを実施。
PHPコンテナに接続し以下コマンドを実行する。
apt-get install php-mysql

4. エラー 2002
エラー発生
Connect Error: 2002

データベース接続先が "localhost# になっていた。
今回の環境では PHP と MySQL は別コンテナで、MySQLのコンテナ名は compose.yamlの設定では "db" としていたので "db" へ変更する。
$dbh = new PDO('mysql:dbname=ppdb;host=db;charset=utf8mb4',
				'ppguest',		//	DB接続ユーザ
				'passwordpassword');	//	DB接続パスワード

5. エラー 1045
エラー発生
Connect Error: 1045

権限が無いためエラーになっている。
ppguestユーザーで接続しようとしているが、過去記事「PHP:プロになるためのPHPプログラミング入門 サンプル環境構築 4」でユーザーを作成した際 'ppguest'@'localhost' で作成していたので localhost からのアクセスしかできない。
今回は学習用なので、とりあえずすべてOKのユーザーを作成して対応。
mysql> create user 'ppguest'@'%' identified by 'xxxx';
Query OK, 0 rows affected (0.01 sec)

権限も付与
mysql> GRANT SELECT ON ppdb.* to 'ppguest'@'%';
Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

6. エラー 1044
エラー発生
Connect Error: 1044

6. とりあえずDB接続はOK
とりあえず ppPageのエラーに変わったので DB接続はOKと思われる。
Fatal error: Uncaught TypeError: PpPage::display(): Argument #2 ($elem) must be of type array, CcData given, called in /var/www/prophp_sample/www/ppa/p15flexydb.php on line 50 and defined in /var/www/prophp_sample/www/ppa/ppPage.php:26 Stack trace: #0 /var/www/prophp_sample/www/ppa/p15flexydb.php(50): PpPage->display('p15flexydb.html', Object(CcData)) #1 {main} thrown in /var/www/prophp_sample/www/ppa/ppPage.php on line 26

7. PHPソース修正
オリジナルでは CcDataクラスのオブジェクトを PpPageクラスのdisplayメソッド第2引数に渡し、
dispalyメソッドでは HTML_Template_Flexy の outputObject に直接オブジェクトを渡している。
HTML_Template_Flexy では、ある意味何でもできるっぽい。
p15flexydb.php
 :$page = new PpPage;							//	表示クラス
  $cdata = new CcData;						//	DAOクラス
  $cdata->getData();							//	DBからデータを取得
  $page->display('p15flexydb.html', $cdata);
   :

ppPage.php
	//!	コンパイルして表示する
	//!	@param	string	$tmpl	テンプレートファイル名
	//!	@param	object	$dobj	出力データ
	//!	@param	array	$elem	HTML要素出力データ
	public function display($tmpl, $dobj = false, array $elem = array()) {
		$this->flexy->compile($tmpl);
		$this->flexy->outputObject($dobj, $elem);
	}

これを Twig 対応とするには、
・ CcDataクラスの $records プロパティを PpPage.displayメソッドの第2引数に渡す
$page->display('p15flexydb.html', 
	[
		'records' => $cdata->records,
	]
);

・ PpPage.displayメソッドでは Twigのrenderメソッドの第2引数に渡す

・テンプレートの修正
foreachの書式を変更:
{foreach:records,r} → {% for r in records %}
{end:} → {% endfor %}
プロパティの変更:
例:{r.zipcode:hs} → {{ r.zipcode }}

実行結果:

参考 (ソース全体)

◆ p15flexydb.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>郵便番号検索</title>
</head>
<body>
<table>
<tr><th>郵便番号</th><th>都道府県名</th><th>市区町村名</th><th>町域名</th></tr>
{% for r in records %}
<tr>
<td>{{ r.zipcode }}</td>
<td>{{ r.pref }}</td>
<td>{{ r.city }}</td>
<td>{{ r.town }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>

◆ p15flexydb.php
<?php
//!	HTML_Template_Flexyのサンプル	データベース処理との組合せ
require_once 'ppPage.php';
//------------------------------//
//!	DAOクラス
class CcData {
	public &records = array();	//!<	検索したレコードの配列

	//!	データ取得
	public function getData() {
		try {
			//	MySQLに接続	PHP5.3.6以降でcharsetを指定可	MySQL5.5未満ではcharset=utf8を指定
			&dbh = new PDO('mysql:dbname=ppdb;host=db;charset=utf8mb4',
							'ppguest',		//	DB接続ユーザ
							'passwordpassword');	//	DB接続パスワード
		} catch (PDOException &e) {
			die('Connect Error: ' . &e->getCode());
		}

		&dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		&dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

		try {
			&sql  = 'SELECT zipcode, pref, city, town FROM zipcodes';
			&sql .= ' WHERE zipcode >= ? AND zipcode <= ?';
			&sql .= ' ORDER BY zipcode ASC LIMIT 100';

			//	郵便番号の検索範囲
			&mincd = '2070000';
			&maxcd = '2090000';

			&sth = &dbh->prepare(&sql);
			&sth->bindParam(1, &mincd, PDO::PARAM_STR);
			&sth->bindParam(2, &maxcd, PDO::PARAM_STR);
			&sth->execute();
			while (&row = &sth->fetchObject()) {
				&this->records[] = &row;
			}
			&sth->closeCursor();
		} catch (Exception &e) {
			die('Access Error: ' .&e->getCode());
		}
	}
}

//------------------------------//
&page = new PpPage;							//	表示クラス
&cdata = new CcData;						//	DAOクラス
&cdata->getData();							//	DBからデータを取得
&page->display('p15flexydb.html', 
	[
		'records' => &cdata->records,
	]
);


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

公開:2026.05.23(土) 08:27

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

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

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

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

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

A.3 MySQLの設定 / 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)


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)

3. 郵便番号データのロード
3-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)
を指定し[保存]

3-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:/

3.3. CSVのロード
MySQLコンテナで ppdbデータベース ppadminユーザーで接続し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)が無効化されているため

◆ 対応:ローカルの読み込み機能を有効化する
3.3.1. サーバ側の設定確認
現在のlocal_infile設定確認:→ "OFF" なので無効になっている
mysql> show variables like 'local_infile'
    -> ;
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | OFF   |
+---------------+-------+
1 row in set (0.05 sec)

3.3.2. 設定を有効にする
MySQLに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)

3.3.3. 郵便番号データのロード
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にコピーしたので /KEN_ALL.CSV 修正。

実行結果: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


PHP:ランダム文字列の生成方法

公開:2026.05.18(月) 05:32

PHPでのランダム文字列生成方法

PHPでパスワードなどに使用できるランダム文字列の生成方法

"php -a" で対話型シェルを開始し以下コマンドを実行
// 32文字の安全なパスワードを生成
echo bin2hex(random_bytes(16));

関連



"PHP Tips"

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

公開:2026.05.17(日) 04:51

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

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

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

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

A.3 MySQLの設定 / A.3.1 データベースと接続ユーザーの作成 (P.320)

1. MySQLコンテナへの接続
MySQLコンテナに接続する。

実行結果:
xxxxxxxx@yyyy:~/docker/php$ docker ps
CONTAINER ID   IMAGE                   COMMAND                  CREATED      STATUS      PORTS                                                    NAMES
3d8258bc2177   php:8.3-apache          "docker-php-entrypoi…"   7 days ago   Up 5 days   0.0.0.0:8080->80/tcp, [::]:8080->80/tcp                  php-php-1
d094e1650051   mysql:8.0               "docker-entrypoint.s…"   7 days ago   Up 5 days   0.0.0.0:3306->3306/tcp, [::]:3306->3306/tcp, 33060/tcp   php-db-1
b60aebf325a6   phpmyadmin/phpmyadmin   "/docker-entrypoint.…"   7 days ago   Up 5 days   0.0.0.0:8081->80/tcp, [::]:8081->80/tcp                  php-phpmyadmin-1
xxxxxxxx@yyyy:~/docker/php$ docker exec -it d094e1650051 /bin/bash
bash-5.1#

2. MySQLログイン
MySQLにrootユーザで接続する。
mysql -u root -p

実行結果:
bash-5.1# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 382
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>

3. ppdbデータベースの作成
以下コマンドを実行
create database ppdb CHARACTER set utf8mb4;
実行結果:
mysql> create database ppdb CHARACTER set utf8mb4;
Query OK, 1 row affected (0.03 sec)

4. 管理者ユーザの追加
以下コマンドを実行 → エラー発生
grant all on ppdb.* to 'ppadmin'@'localhost' identified by 'パスワード';
実行結果:
mysql> grant all on ppdb.* to 'ppadmin'@'localhost' identified by 'xxxx';
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 'xxxx'' at line 1
原因:MySQL 8.0以降では、GRANT コマンドと同時に IDENTIFIED BY を使ってユーザーの作成やパスワードの変更を行うことができなくなった。

対応:
4-1. ユーザーを先に作成する
まず、CREATE USER コマンドでユーザーとパスワードを設定する。
CREATE USER 'ppadmin'@'localhost' IDENTIFIED BY 'パスワード';
実行結果:
mysql> CREATE USER 'ppadmin'@'localhost' IDENTIFIED BY 'xxxx';
Query OK, 0 rows affected (0.02 sec)

4-2. 権限を付与する
次に、GRANT コマンドで権限を設定する。
GRANT ALL PRIVILEGES ON ppdb.* TO 'ppadmin'@'localhost';
実行結果:
mysql> CREATE USER 'ppadmin'@'localhost' IDENTIFIED BY 'xxxx';
Query OK, 0 rows affected (0.02 sec)

4-3. 設定を反映する
念のため、変更を確実に反映させるために以下のコマンドを実行しておく。
FLUSH PRIVILEGES;
実行結果:
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.01 sec)

5. 一般ユーザの追加
一般ユーザーもユーザ作成と権限付与を分けて実行する。
CREATE USER 'ppguest'@'localhost' identified by 'パスワード';
実行結果:
mysql> CREATE USER 'ppguest'@'localhost' identified by 'xxxx';
Query OK, 0 rows affected (0.01 sec)

GRANT SELECT ON ppdb.* to 'ppguest'@'localhost';
実行結果:
mysql> GRANT SELECT ON ppdb.* to 'ppguest'@'localhost';
Query OK, 0 rows affected, 1 warning (0.00 sec)

FLUSH PRIVILEGES;
実行結果:
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.01 sec)

続く・・


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

公開:2026.05.17(日) 00:08

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

リスト 1-1 文字エンコーディングをチェックするプログラムの例 (P.42)

リスト 1-2 マルチバイト文字列関数を使うプログラムの例 (P.43)
リスト 1-3 テンプレートファイル (P.55) リスト 1-4 プログラムファイル (P.56)
http://localhost:8080/prophp_sample/ppa/p15flexy.php

Twigへの置換が必要。

◆ p15flexy.html
<html>
<body>
<h1>{{ val }}</h1>
</body>
</html>

◆ p15flexyif.html
<?php
require_once '../../vendor/autoload.php';

define('TEMPLATE_PATH', '../../templates');

$oobj = ['val' => '楽しい夏休み'];

$loader = new \Twig\Loader\FilesystemLoader(TEMPLATE_PATH);
$twig = new \Twig\Environment($loader);

echo $twig->render('p15flexy.html', $oobj);

リスト 1-6 PpPageクラス (P.60)
リスト 1-7 テンプレートファイル (P.61)
リスト 1-8 プログラムファイル (P.62)
Twigへの置換が必要。

◆ PpPage.php
<?php
require_once '../../vendor/autoload.php';
define('TEMPLATE_PATH', '../../templates');	//	テンプレートファイルを置くフォルダ
//------------------------------//
//!	ページ表示クラス
class PpPage {
	protected $twig = null;  // Twigオブジェクト

	//!	コンストラクタ
	public function __construct() {
		//	E_DEPRECATEDとE_STRICTのメッセージを非表示にする
		if(defined('E_DEPRECATED')){
			error_reporting(error_reporting() & ~(E_DEPRECATED | E_STRICT));
		}

		$loader = new \Twig\Loader\FilesystemLoader(TEMPLATE_PATH);

		$this->twig = new \Twig\Environment($loader, [
			'cache' => '/var/cache',
			'debug' => true,
		]);
	}

	//!	@param	string	$tmpl	テンプレートファイル名
	//!	@param	array	$elem	HTML要素出力データ
	public function display($tmpl, array $elem = array()) {
		echo $this->twig->render($tmpl, $elem);
	}
}

◆ p15flexyform.html
selectへの項目(option)追加は {% for … %} によるループが必要
checked属性の追加は それぞれの項目で対応が必要
{{- kcomm -}} の "-" は前後のスペースを取り除くためのもの
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ピザの注文</title>
</head>
<body>
<form name="pform" method="post" action="p15flexyform.php">
<p>生地の種類:
<select name="pbase" id="pbase">
  {% for value, label in pkind %}
  <option value="{{ value }}" {{ pbase == value ? 'selected' : '' }}>
    {{ label }}
  </option>
  {% endfor %}
</select>
</p>
<p>サイズ:<br>
<input type="radio" name="psize" value="1" {{ psize  == 1 ? 'checked': '' }}>大
<input type="radio" name="psize" value="2" {{ psize  == 2 ? 'checked': '' }}>中
<input type="radio" name="psize" value="3" {{ psize  == 3 ? 'checked': '' }}>小
</p>
<p>トッピング:<br>
<input type="checkbox" name="ptop[]" value="1" {{ '1' in ptop ? 'checked': '' }}>ペパロニ
<input type="checkbox" name="ptop[]" value="2" {{ '2' in ptop ? 'checked': '' }}>アンチョビ
<input type="checkbox" name="ptop[]" value="3" {{ '3' in ptop ? 'checked': '' }}>トマト
<input type="checkbox" name="ptop[]" value="4" {{ '4' in ptop ? 'checked': '' }}>ピーマン
<input type="checkbox" name="ptop[]" value="5" {{ '5' in ptop ? 'checked': '' }}>バジル
</p>
<p>お名前:<br>
<input name="kname" size="40" maxlength="30" value="{{ kname }}">
</p>
<p>連絡事項:<br>
<textarea name="kcomm" cols="{{ kcomm_attr.cols }}" rows="{{ kcomm_attr.rows }}">
  {{- kcomm -}}
</textarea>
</p>
<input type="submit" value="注文する">
</form>
</body>
</html>

p15flexyform.php
<?php
require_once 'ppPage.php';

$elems = [
  'pkind' => [
    1 => 'モッチモチ! 弾力がある厚めの生地です',
    2 => 'パリパリッ! 薄い生地がお好きな方はどうぞ',
    3 => 'サクットロ~! サクッとした生地の中にはトロ~リチーズ'    
  ],
    'pbase'   => 2,
    'psize'   => 3,
    'ptop'    => ['2', '3'],
    'kname'   => 'お名前を入力してください',
    'kcomm'   => '連絡事項を入力してください',
    'kcomm_attr' => ['cols' => 40, 'rows' => 10]  
];

$page = new PpPage;
$page->display('p15flexyform.html', $elems);


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

公開:2026.05.15(金) 01:17

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

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

1. Compose環境を作る
まずは PHP Composer環境を作る。
→「PHP:Compose環境を作る

実行結果:
xxxxxxxx@yyyy:~/docker/php$ docker ps
CONTAINER ID   IMAGE                   COMMAND                  CREATED      STATUS          PORTS                                                    NAMES
3d8258bc2177   php:8.3-apache          "docker-php-entrypoi…"   2 days ago   Up 11 minutes   0.0.0.0:8080->80/tcp, [::]:8080->80/tcp                  php-php-1
d094e1650051   mysql:8.0               "docker-entrypoint.s…"   2 days ago   Up 11 minutes   0.0.0.0:3306->3306/tcp, [::]:3306->3306/tcp, 33060/tcp   php-db-1
b60aebf325a6   phpmyadmin/phpmyadmin   "/docker-entrypoint.…"   2 days ago   Up 11 minutes   0.0.0.0:8081->80/tcp, [::]:8081->80/tcp                  php-phpmyadmin-1
xxxxxxxx@yyyy:~/docker/php$ docker exec -it 3d8258bc2177 /bin/bash
root@3d8258bc2177:/var/www/html# php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
root@3d8258bc2177:/var/www/html# php -r "if (hash_file('sha384', 'composer-setup.php') === 'c8b085408188070d5f52bcfe4ecfbee5f727afa458b2573b8eaaf77b3419b0bf2768dc67c86944da1544f06fa544fd47') { echo 'Installer verified'.PHP_EOL; } else { echo 'Installer corrupt'.PHP_EOL; unlink('composer-setup.php'); exit(1); }"
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
Installer verified
root@3d8258bc2177:/var/www/html# php composer-setup.php
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
All settings correct for using Composer
Downloading...

Composer (version 2.9.8) successfully installed to: /var/www/html/composer.phar
Use it: php composer.phar

root@3d8258bc2177:/var/www/html# php -r "unlink('composer-setup.php');"
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
root@3d8258bc2177:/var/www/html# mv composer.phar /usr/local/bin/composer

2. Twigインストール
サンプルのテンプレートエンジンは HTML_Templafe_Flexy というのを使っているが、PHP8.3環境だとうまく動かないため Twig を使うことにする。
→「PHP:Twigのインストール

2-1. Twigが必要なコンポーネントのインストール
実行結果:
root@3d8258bc2177:/var/www/prophp_sample# apt-get update [ \
apt-get install -y \
libzip-dev \
git \
unzip \
zip \
&& docker-php-ext-install zip
Hit:1 http://deb.debian.org/debian trixie InRelease
Get:2 http://deb.debian.org/debian trixie-updates InRelease [47.3 kB]
Get:3 http://deb.debian.org/debian-security trixie-security InRelease [43.4 kB]
Get:4 http://deb.debian.org/debian trixie/main amd64 Packages [9671 kB]
Get:5 http://deb.debian.org/debian trixie-updates/main amd64 Packages [5412 B]
Get:6 http://deb.debian.org/debian-security trixie-security/main amd64 Packages [161 kB]
Fetched 9928 kB in 1s (12.2 MB/s)
Reading package lists... Done
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  git-man less libcbor0.10 libcurl3t64-gnutls libedit2 liberror-perl libfido2-1 libngtcp2-16 libngtcp2-crypto-gnutls8
  libx11-6 libx11-data libxau6 libxcb1 libxdmcp6 libxext6 libxmuu1 libzip5 openssh-client xauth zipcmp zipmerge
  ziptool zlib1g-dev
Suggested packages:
  gettext-base git-doc git-email git-gui gitk gitweb git-cvs git-mediawiki git-svn keychain libpam-ssh monkeysphere
  ssh-askpass
The following NEW packages will be installed:
  git git-man less libcbor0.10 libcurl3t64-gnutls libedit2 liberror-perl libfido2-1 libngtcp2-16
  libngtcp2-crypto-gnutls8 libx11-6 libx11-data libxau6 libxcb1 libxdmcp6 libxext6 libxmuu1 libzip-dev libzip5
  openssh-client unzip xauth zip zipcmp zipmerge ziptool zlib1g-dev
0 upgraded, 27 newly installed, 0 to remove and 6 not upgraded.
Need to get 16.1 MB of archives.
After this operation, 67.3 MB of additional disk space will be used.
Get:1 http://deb.debian.org/debian trixie/main amd64 less amd64 668-1 [161 kB]
Get:2 http://deb.debian.org/debian trixie/main amd64 libedit2 amd64 3.1-20250104-1 [93.8 kB]
Get:3 http://deb.debian.org/debian trixie/main amd64 libcbor0.10 amd64 0.10.2-2 [28.3 kB]
Get:4 http://deb.debian.org/debian trixie/main amd64 libfido2-1 amd64 1.15.0-1+b1 [78.7 kB]
Get:5 http://deb.debian.org/debian-security trixie-security/main amd64 openssh-client amd64 1:10.0p1-7+deb13u2 [986 kB]
Get:6 http://deb.debian.org/debian-security trixie-security/main amd64 libngtcp2-16 amd64 1.11.0-1+deb13u1 [132 kB]
Get:7 http://deb.debian.org/debian-security trixie-security/main amd64 libngtcp2-crypto-gnutls8 amd64 1.11.0-1+deb13u1 [29.5 kB]
Get:8 http://deb.debian.org/debian trixie/main amd64 libcurl3t64-gnutls amd64 8.14.1-2+deb13u2 [383 kB]
Get:9 http://deb.debian.org/debian trixie/main amd64 liberror-perl all 0.17030-1 [26.9 kB]
Get:10 http://deb.debian.org/debian trixie/main amd64 git-man all 1:2.47.3-0+deb13u1 [2205 kB]
Get:11 http://deb.debian.org/debian trixie/main amd64 git amd64 1:2.47.3-0+deb13u1 [8862 kB]
Get:12 http://deb.debian.org/debian trixie/main amd64 libxau6 amd64 1:1.0.11-1 [20.4 kB]
Get:13 http://deb.debian.org/debian trixie/main amd64 libxdmcp6 amd64 1:1.1.5-1 [27.8 kB]
Get:14 http://deb.debian.org/debian trixie/main amd64 libxcb1 amd64 1.17.0-2+b1 [144 kB]
Get:15 http://deb.debian.org/debian trixie/main amd64 libx11-data all 2:1.8.12-1 [343 kB]
Get:16 http://deb.debian.org/debian trixie/main amd64 libx11-6 amd64 2:1.8.12-1 [815 kB]
Get:17 http://deb.debian.org/debian trixie/main amd64 libxext6 amd64 2:1.3.4-1+b3 [50.4 kB]
Get:18 http://deb.debian.org/debian trixie/main amd64 libxmuu1 amd64 2:1.1.3-3+b4 [21.9 kB]
Get:19 http://deb.debian.org/debian trixie/main amd64 libzip5 amd64 1.11.3-2 [62.6 kB]
Get:20 http://deb.debian.org/debian trixie/main amd64 zipcmp amd64 1.11.3-2 [19.8 kB]
Get:21 http://deb.debian.org/debian trixie/main amd64 zipmerge amd64 1.11.3-2 [14.5 kB]
Get:22 http://deb.debian.org/debian trixie/main amd64 ziptool amd64 1.11.3-2 [22.6 kB]
Get:23 http://deb.debian.org/debian trixie/main amd64 zlib1g-dev amd64 1:1.3.dfsg+really1.3.1-1+b1 [920 kB]
Get:24 http://deb.debian.org/debian trixie/main amd64 libzip-dev amd64 1.11.3-2 [181 kB]
Get:25 http://deb.debian.org/debian trixie/main amd64 unzip amd64 6.0-29 [173 kB]
Get:26 http://deb.debian.org/debian trixie/main amd64 xauth amd64 1:1.1.2-1.1 [35.9 kB]
Get:27 http://deb.debian.org/debian trixie/main amd64 zip amd64 3.0-15 [235 kB]
Fetched 16.1 MB in 1s (29.3 MB/s)
debconf: unable to initialize frontend: Dialog
debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 79, <STDIN> line 27.)
debconf: falling back to frontend: Readline
Selecting previously unselected package less.
(Reading database ... 15584 files and directories currently installed.)
Preparing to unpack .../00-less_668-1_amd64.deb ...
Unpacking less (668-1) ...
Selecting previously unselected package libedit2:amd64.
Preparing to unpack .../01-libedit2_3.1-20250104-1_amd64.deb ...
Unpacking libedit2:amd64 (3.1-20250104-1) ...
Selecting previously unselected package libcbor0.10:amd64.
Preparing to unpack .../02-libcbor0.10_0.10.2-2_amd64.deb ...
Unpacking libcbor0.10:amd64 (0.10.2-2) ...
Selecting previously unselected package libfido2-1:amd64.
Preparing to unpack .../03-libfido2-1_1.15.0-1+b1_amd64.deb ...
Unpacking libfido2-1:amd64 (1.15.0-1+b1) ...
Selecting previously unselected package openssh-client.
Preparing to unpack .../04-openssh-client_1%3a10.0p1-7+deb13u2_amd64.deb ...
Unpacking openssh-client (1:10.0p1-7+deb13u2) ...
Selecting previously unselected package libngtcp2-16:amd64.
Preparing to unpack .../05-libngtcp2-16_1.11.0-1+deb13u1_amd64.deb ...
Unpacking libngtcp2-16:amd64 (1.11.0-1+deb13u1) ...
Selecting previously unselected package libngtcp2-crypto-gnutls8:amd64.
Preparing to unpack .../06-libngtcp2-crypto-gnutls8_1.11.0-1+deb13u1_amd64.deb ...
Unpacking libngtcp2-crypto-gnutls8:amd64 (1.11.0-1+deb13u1) ...
Selecting previously unselected package libcurl3t64-gnutls:amd64.
Preparing to unpack .../07-libcurl3t64-gnutls_8.14.1-2+deb13u2_amd64.deb ...
Unpacking libcurl3t64-gnutls:amd64 (8.14.1-2+deb13u2) ...
Selecting previously unselected package liberror-perl.
Preparing to unpack .../08-liberror-perl_0.17030-1_all.deb ...
Unpacking liberror-perl (0.17030-1) ...
Selecting previously unselected package git-man.
Preparing to unpack .../09-git-man_1%3a2.47.3-0+deb13u1_all.deb ...
Unpacking git-man (1:2.47.3-0+deb13u1) ...
Selecting previously unselected package git.
Preparing to unpack .../10-git_1%3a2.47.3-0+deb13u1_amd64.deb ...
Unpacking git (1:2.47.3-0+deb13u1) ...
Selecting previously unselected package libxau6:amd64.
Preparing to unpack .../11-libxau6_1%3a1.0.11-1_amd64.deb ...
Unpacking libxau6:amd64 (1:1.0.11-1) ...
Selecting previously unselected package libxdmcp6:amd64.
Preparing to unpack .../12-libxdmcp6_1%3a1.1.5-1_amd64.deb ...
Unpacking libxdmcp6:amd64 (1:1.1.5-1) ...
Selecting previously unselected package libxcb1:amd64.
Preparing to unpack .../13-libxcb1_1.17.0-2+b1_amd64.deb ...
Unpacking libxcb1:amd64 (1.17.0-2+b1) ...
Selecting previously unselected package libx11-data.
Preparing to unpack .../14-libx11-data_2%3a1.8.12-1_all.deb ...
Unpacking libx11-data (2:1.8.12-1) ...
Selecting previously unselected package libx11-6:amd64.
Preparing to unpack .../15-libx11-6_2%3a1.8.12-1_amd64.deb ...
Unpacking libx11-6:amd64 (2:1.8.12-1) ...
Selecting previously unselected package libxext6:amd64.
Preparing to unpack .../16-libxext6_2%3a1.3.4-1+b3_amd64.deb ...
Unpacking libxext6:amd64 (2:1.3.4-1+b3) ...
Selecting previously unselected package libxmuu1:amd64.
Preparing to unpack .../17-libxmuu1_2%3a1.1.3-3+b4_amd64.deb ...
Unpacking libxmuu1:amd64 (2:1.1.3-3+b4) ...
Selecting previously unselected package libzip5:amd64.
Preparing to unpack .../18-libzip5_1.11.3-2_amd64.deb ...
Unpacking libzip5:amd64 (1.11.3-2) ...
Selecting previously unselected package zipcmp.
Preparing to unpack .../19-zipcmp_1.11.3-2_amd64.deb ...
Unpacking zipcmp (1.11.3-2) ...
Selecting previously unselected package zipmerge.
Preparing to unpack .../20-zipmerge_1.11.3-2_amd64.deb ...
Unpacking zipmerge (1.11.3-2) ...
Selecting previously unselected package ziptool.
Preparing to unpack .../21-ziptool_1.11.3-2_amd64.deb ...
Unpacking ziptool (1.11.3-2) ...
Selecting previously unselected package zlib1g-dev:amd64.
Preparing to unpack .../22-zlib1g-dev_1%3a1.3.dfsg+really1.3.1-1+b1_amd64.deb ...
Unpacking zlib1g-dev:amd64 (1:1.3.dfsg+really1.3.1-1+b1) ...
Selecting previously unselected package libzip-dev:amd64.
Preparing to unpack .../23-libzip-dev_1.11.3-2_amd64.deb ...
Unpacking libzip-dev:amd64 (1.11.3-2) ...
Selecting previously unselected package unzip.
Preparing to unpack .../24-unzip_6.0-29_amd64.deb ...
Unpacking unzip (6.0-29) ...
Selecting previously unselected package xauth.
Preparing to unpack .../25-xauth_1%3a1.1.2-1.1_amd64.deb ...
Unpacking xauth (1:1.1.2-1.1) ...
Selecting previously unselected package zip.
Preparing to unpack .../26-zip_3.0-15_amd64.deb ...
Unpacking zip (3.0-15) ...
Setting up libxau6:amd64 (1:1.0.11-1) ...
Setting up libxdmcp6:amd64 (1:1.1.5-1) ...
Setting up libxcb1:amd64 (1.17.0-2+b1) ...
Setting up libzip5:amd64 (1.11.3-2) ...
Setting up libcbor0.10:amd64 (0.10.2-2) ...
Setting up unzip (6.0-29) ...
Setting up libedit2:amd64 (3.1-20250104-1) ...
Setting up less (668-1) ...
Setting up zipmerge (1.11.3-2) ...
Setting up liberror-perl (0.17030-1) ...
Setting up zip (3.0-15) ...
Setting up libx11-data (2:1.8.12-1) ...
Setting up zlib1g-dev:amd64 (1:1.3.dfsg+really1.3.1-1+b1) ...
Setting up zipcmp (1.11.3-2) ...
Setting up git-man (1:2.47.3-0+deb13u1) ...
Setting up libx11-6:amd64 (2:1.8.12-1) ...
Setting up libngtcp2-16:amd64 (1.11.0-1+deb13u1) ...
Setting up libfido2-1:amd64 (1.15.0-1+b1) ...
Setting up ziptool (1.11.3-2) ...
Setting up libxmuu1:amd64 (2:1.1.3-3+b4) ...
Setting up libngtcp2-crypto-gnutls8:amd64 (1.11.0-1+deb13u1) ...
Setting up libzip-dev:amd64 (1.11.3-2) ...
Setting up openssh-client (1:10.0p1-7+deb13u2) ...
Setting up libcurl3t64-gnutls:amd64 (8.14.1-2+deb13u2) ...
Setting up libxext6:amd64 (2:1.3.4-1+b3) ...
Setting up git (1:2.47.3-0+deb13u1) ...
Setting up xauth (1:1.1.2-1.1) ...
Processing triggers for libc-bin (2.41-12+deb13u2) ...
Configuring for:
PHP Api Version:         20230831
Zend Module Api No:      20230831
Zend Extension Api No:   420230831
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for a sed that does not truncate output... /usr/bin/sed
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether the compiler supports GNU C... yes
checking whether cc accepts -g... yes
checking for cc option to enable C11 features... none needed
checking how to run the C preprocessor... cc -E
checking for egrep -e... (cached) /usr/bin/grep -E
checking for icc... no
checking for suncc... no
checking for system library directory... lib
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking target system type... x86_64-pc-linux-gnu
checking for PHP prefix... /usr/local
checking for PHP includes... -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib
checking for PHP extension directory... /usr/local/lib/php/extensions/no-debug-non-zts-20230831
checking for PHP installed headers prefix... /usr/local/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for gawk... no
checking for nawk... nawk
checking if nawk is broken... no
checking for zip archive read/write support... yes, shared
checking for libzip >= 0.11 libzip != 1.3.1 libzip != 1.7.0... yes
checking for zip_file_set_mtime in -lzip... yes
checking for zip_file_set_encryption in -lzip... yes
checking for zip_libzip_version in -lzip... yes
checking for zip_register_progress_callback_with_state in -lzip... yes
checking for zip_register_cancel_callback_with_state in -lzip... yes
checking for zip_compression_method_supported in -lzip... yes
checking for a sed that does not truncate output... /usr/bin/sed
checking for ld used by cc... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for /usr/bin/ld option to reload object files... -r
checking for BSD-compatible nm... /usr/bin/nm -B
checking whether ln -s works... yes
checking how to recognize dependent libraries... pass_all
checking for stdio.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for strings.h... yes
checking for sys/stat.h... yes
checking for sys/types.h... yes
checking for unistd.h... yes
checking for dlfcn.h... yes
checking the maximum length of command line arguments... 1572864
checking command to parse /usr/bin/nm -B output from cc object... ok
checking for objdir... .libs
checking for ar... ar
checking for ranlib... ranlib
checking for strip... strip
checking if cc supports -fno-rtti -fno-exceptions... no
checking for cc option to produce PIC... -fPIC
checking if cc PIC flag -fPIC works... yes
checking if cc static flag -static works... yes
checking if cc supports -c -o file.o... yes
checking whether the cc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... no

creating libtool
appending configuration tag "CXX" to libtool
configure: patching config.h.in
configure: creating ./config.status
config.status: creating config.h
/bin/bash /usr/src/php/ext/zip/libtool --tag=CC --mode=compile cc -I. -I/usr/src/php/ext/zip -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE    -DZEND_COMPILE_DL_EXT=1 -c /usr/src/php/ext/zip/php_zip.c -o php_zip.lo  -MMD -MF php_zip.dep -MT php_zip.lo
mkdir .libs
 cc -I. -I/usr/src/php/ext/zip -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE -DZEND_COMPILE_DL_EXT=1 -c /usr/src/php/ext/zip/php_zip.c -MMD -MF php_zip.dep -MT php_zip.lo  -fPIC -DPIC -o .libs/php_zip.o
/bin/bash /usr/src/php/ext/zip/libtool --tag=CC --mode=compile cc -I. -I/usr/src/php/ext/zip -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE    -DZEND_COMPILE_DL_EXT=1 -c /usr/src/php/ext/zip/zip_stream.c -o zip_stream.lo  -MMD -MF zip_stream.dep -MT zip_stream.lo
 cc -I. -I/usr/src/php/ext/zip -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE -DZEND_COMPILE_DL_EXT=1 -c /usr/src/php/ext/zip/zip_stream.c -MMD -MF zip_stream.dep -MT zip_stream.lo  -fPIC -DPIC -o .libs/zip_stream.o
/bin/bash /usr/src/php/ext/zip/libtool --tag=CC --mode=link cc -shared -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE  -Wl,-O1 -pie  -o zip.la -export-dynamic -avoid-version -prefer-pic -module -rpath /usr/src/php/ext/zip/modules  php_zip.lo zip_stream.lo -lzip
cc -shared  .libs/php_zip.o .libs/zip_stream.o  -lzip  -Wl,-O1 -Wl,-soname -Wl,zip.so -o .libs/zip.so
creating zip.la
(cd .libs && rm -f zip.la && ln -s ../zip.la zip.la)
/bin/bash /usr/src/php/ext/zip/libtool --tag=CC --mode=install cp ./zip.la /usr/src/php/ext/zip/modules
cp ./.libs/zip.so /usr/src/php/ext/zip/modules/zip.so
cp ./.libs/zip.lai /usr/src/php/ext/zip/modules/zip.la
PATH="$PATH:/sbin" ldconfig -n /usr/src/php/ext/zip/modules
----------------------------------------------------------------------
Libraries have been installed in:
   /usr/src/php/ext/zip/modules

If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,--rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------

Build complete.
Don't forget to run 'make test'.

+ strip --strip-all modules/zip.so
Installing shared extensions:     /usr/local/lib/php/extensions/no-debug-non-zts-20230831/
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
find . -name \*.gcno -o -name \*.gcda | xargs rm -f
find . -name \*.lo -o -name \*.o -o -name \*.dep | xargs rm -f
find . -name \*.la -o -name \*.a | xargs rm -f
find . -name \*.so | xargs rm -f
find . -name .libs -a -type d|xargs rm -rf
rm -f libphp.la      modules/* libs/*
rm -f ext/opcache/jit/zend_jit_x86.c
rm -f ext/opcache/jit/zend_jit_arm64.c
rm -f ext/opcache/minilua

2-2. Twigのインストール
var/www/prophp_sample フォルダに Twig をインストールする。

実行結果:
root@3d8258bc2177:/var/www/prophp_sample# composer require twig/twig
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
The repository at "/var/www/prophp_sample" does not have the correct ownership and git refuses to use it:

fatal: detected dubious ownership in repository at '/var/www/prophp_sample'
To add an exception for this directory, call:

git config --global --add safe.directory /var/www/prophp_sample

./composer.json has been updated
The repository at "/var/www/prophp_sample" does not have the correct ownership and git refuses to use it:

fatal: detected dubious ownership in repository at '/var/www/prophp_sample'
To add an exception for this directory, call:

git config --global --add safe.directory /var/www/prophp_sample

Running composer update twig/twig
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
  - Downloading symfony/polyfill-mbstring (v1.37.0)
  - Downloading symfony/polyfill-ctype (v1.37.0)
  - Downloading symfony/deprecation-contracts (v3.7.0)
  - Downloading twig/twig (v3.24.0)
  - Installing symfony/polyfill-mbstring (v1.37.0): Extracting archive
  - Installing symfony/polyfill-ctype (v1.37.0): Extracting archive
  - Installing symfony/deprecation-contracts (v3.7.0): Extracting archive
  - Installing twig/twig (v3.24.0): Extracting archive
Generating autoload files
4 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
No security vulnerability advisories found.
Using version ^3.24 for twig/twig

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

更新:2026.06.06(土) 22:09
公開:2026.05.11(月) 09:46

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

書籍:プロになるためのPHPプログラミング入門
(ISBN:978-4-7741-4972-1)

この書籍のサンプルプログラムを動かすためのコンテナを作成する。
本来であれば新たに専用Dockerコンテナを作成するのが良しと思うが、
今回は「Docker:WSL+Docker+PHP+MySQL+phpMyAdmin環境の作成」で作成したコンテナに環境を作ろうと思う。

DocumentRootは/var/www/html(WSLの./www/html/にマウント)としているが、
compose.yamlに「Apache:エイリアスの設定」の設定を追加し、 サンプルプログラム(prophp_sample)を localhost/prophp_sample で公開するように対応する。

現在の環境
現在の環境は、WSLの "~/docker/php"フォルダ にcompose.yamlなどDocker関連のファイル および
"~/docker/php/www/html"フォルダ にDocumentRoot をマウントしている。

サンプルプログラムの環境
本付属サンプル "prophp_sample.zip" は解凍したのち WSLの "~/docker/php/prophp_sample" フォルダに配置した。
これをコンテナの "/var/www/prophp_sample" フォルダへマウントする。

(2026.06.06 追加)
Dockerfile
mysqliを使いたいので php:8.3-apache のイメージファイルに mysqli を追加する Dockerfileを作成する。
# 現在お使いのイメージをベースにします
FROM php:8.3-apache

# mysqli 拡張機能をインストールするコマンドを追加します
RUN docker-php-ext-install mysqli

compose.yaml
(2026.06.06 修正) php:8.3-apacheイメージを使い代わりに mysqliを組み込んだDockerfileを使うように修正
services:
    php:
      # image: php:8.3-apache
    volumes:
      - ./www/html:/var/www/html
+     - ./prophp_sample:/var/www/prophp_sample
      - ./php.ini-debug:/usr/local/etc/php/php.ini
 :

Apacheのエイリアス設定を行うための prophp_sample.conf ファイルをWSL上に作成する。
prophp_sample.conf
Alias /prophp_sample /var/www/prophp_sample/www

<Directory /var/www/prophp_sample/www>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

prophp_sample.confをコンテナにマウントし、Apacheの設定有効化と起動をcompose.yamlに追加する。
compose.yaml
  services:
    php:
      image: php:8.3-apache
      volumes:
        - ./www/html:/var/www/html
        - ./prophp_sample:/var/www/prophp_sample
        - ./php.ini-debug:/usr/local/etc/php/php.ini
+       - ./prophp_sample.conf:/etc/apache2/conf-available/prophp_sample.conf
      ports:
        - "8080:80"
+     command: >
+       sh -c "a2enconf prophp_sample && apache2-foreground"
 :

あとは "docker copmose up -d" でコンテナを起動、 試しに "~/docker/php/prophp_sample/phpinfo.php" ファイルを作成、"localhost:8080/prophp_sample/phpinfo.php" でアクセスできればOK

参考(全体ソース)

Dockerfile
# 現在お使いのイメージをベースにします
FROM php:8.3-apache

# mysqli 拡張機能をインストールするコマンドを追加します
RUN docker-php-ext-install mysqli

compose.yaml
services:
  php:
    image: php:8.3-apache
    volumes:
      - ./www/html:/var/www/html
      - ./prophp_sample:/var/www/prophp_sample
      - ./php.ini-debug:/usr/local/etc/php/php.ini
      - ./prophp_sample.conf:/etc/apache2/conf-available/prophp_sample.conf
    ports:
      - "8080:80"
    command: >
      sh -c "a2enconf prophp_sample && apache2-foreground"

  db:
    image: mysql:8.0
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
  
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    ports:
      - "8081:80"
    environment:
      PMA_HOST: db

サンプル動作確認

・ p14mbchk.php (P.42 OK)
・ p14mbstr.php (P.43 OK)
・ p15flexyform.php

"PHP 学習"

PHP学習:ログイン認証について

公開:2026.05.10(日) 19:36

PHP学習:ログイン認証について

書籍:プロになるためのPHPプログラミング入門
4.1 ログイン認証の仕組みを作るには (P.130)

ログイン機能の流れ

1. ユーザーがユーザー名とパスワードをサーバーに送信する
2. 入力値をチェックする
3. ユーザー名と一致するユーザー情報をデータベースから1件取得する
4. ユーザーが入力したパスワードとデータベースから取得したパスワードを照合する
5. 認証に成功したときはセッション管理を開始する
6. 認証成功後の画面にリダイレクトする

ログアウト機能の流れ

1. ユーザーのログアウト要求をサーバーに送信する
2. セッションデータを削除する
3. ログイン画面に繊維、クッキーのセッションID削除をWebブラウザに要求する

PHP:Twigの基本

公開:2026.04.26 20:15

Twigの基本

テンプレートの書式
{% ... %} ステートメント
{{ }} 実行結果の出力
{# #} コメント

PHPコード
1. Twigインストール
PHPプロジェクトのフォルダにComposerを使ってTwigをインストールする。

2. autoload.phpの読み込み
vendor/autoload.phpを読み込むことでTwigが使用可能となる。

コード例:
require_once '../../vendor/autoload.php';

PHP:Twigのインストール

更新:2026.05.16(土) 11:03
公開:2026.04.26(日) 01:25

PHPテンプレートエンジン twig

PHPのテンプレートエンジン、HTML_Template_FlexyやSmartyの代替をChatGPTに聞いたところ "Twig" と "Blade" というのを教えてもらった。
ということで、今回はTwigというのをインストールしてみる。
インストールはChatGPTに聞いた手順で行う。

Twigとは

「ついっぐ」と呼ぶらしい。

環境

◆ Windows 11 25H2 (26200.8037) + WSL + Docker
◆ WSL:
PS C:\Users\xxx> wsl --version
WSL バージョン: 2.3.24.0
カーネル バージョン: 5.15.153.1-2
WSLg バージョン: 1.0.65
MSRDC バージョン: 1.2.5620
Direct3D バージョン: 1.611.1-81528511
DXCore バージョン: 10.0.26100.1-240331-1435.ge-release
Windows バージョン: 10.0.26200.8037
◆ Ubuntu:
xxx@xxx:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 24.04.1 LTS
Release: 24.04
Codename: noble

過去記事:Docker 学習 #4:Docker Composeを学ぶ で作成したPHPコンテナを使用する。
以下コマンドでコンテナを起動。
docker compose up -d

コンテナのbashに接続する。
docker exec -it (CONTAINER ID) /bin/bash
※ (CONTAINER ID)は "docker ps" コマンドで確認。

Twigインストール

下記手順通りではエラーが出るので(最終的にはうまくいったが)、
インストール方法の結論は末尾 "まとめ" を参照のこと。

以下コマンドでTwigをインストールする。
composer require twig/twig

実行結果:失敗
root@05fa4e42bbcd:~# composer require twig/twig
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
Xdebug: [Step Debug] Time-out connecting to debugging client, waited: 200 ms. Tried: 172.25.0.1:9003 (through xdebug.client_host/xdebug.client_port).
./composer.json has been created
Running composer update twig/twig
Loading composer repositories with package information
Updating dependencies
Lock file operations: 4 installs, 0 updates, 0 removals
  - Locking symfony/deprecation-contracts (v3.6.0)
  - Locking symfony/polyfill-ctype (v1.36.0)
  - Locking symfony/polyfill-mbstring (v1.36.0)
  - Locking twig/twig (v3.24.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
    Failed to download symfony/polyfill-mbstring from dist: The zip extension and unzip/7z commands are both missing, skipping.
Your command-line PHP is using multiple ini files. Run `php --ini` to show them.
    Now trying to download from source

In GitDownloader.php line 82:

  git was not found in your PATH, skipping source download


require [--dev] [--dry-run] [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--fixed] [--no-suggest] [--no-progress] [--no-update] [--no-install] [--no-audit] [--audit-format AUDIT-FORMAT] [--no-security-blocking] [--update-no-dev] [-w|--update-with-dependencies] [-W|--update-with-all-dependencies] [--with-dependencies] [--with-all-dependencies] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [-m|--minimal-changes] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--apcu-autoloader-prefix APCU-AUTOLOADER-PREFIX] [--] [<packages>...]

git, unzip, zipインストール

Twigをインストールするには git, unzip, zip が必要っぽいのでインストールする。

1. apt-get update
まずはお約束の "apt-get update" から。

実行結果:OK
root@05fa4e42bbcd:~# apt-get update
Hit:1 http://deb.debian.org/debian trixie InRelease
Get:2 http://deb.debian.org/debian trixie-updates InRelease [47.3 kB]
Get:3 http://deb.debian.org/debian-security trixie-security InRelease [43.4 kB]
Get:4 http://deb.debian.org/debian-security trixie-security/main amd64 Packages [127 kB]
Fetched 218 kB in 0s (1377 kB/s)
Reading package lists... Done

2. apt-get install git
"git" をインストールする。

実行結果:OK
root@05fa4e42bbcd:~# apt-get install git
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  git-man less libcbor0.10 libcurl3t64-gnutls libedit2 liberror-perl libfido2-1 libngtcp2-16
  libngtcp2-crypto-gnutls8 libx11-6 libx11-data libxau6 libxcb1 libxdmcp6 libxext6 libxmuu1 openssh-client
  xauth
Suggested packages:
  gettext-base git-doc git-email git-gui gitk gitweb git-cvs git-mediawiki git-svn keychain libpam-ssh
  monkeysphere ssh-askpass
The following NEW packages will be installed:
  git git-man less libcbor0.10 libcurl3t64-gnutls libedit2 liberror-perl libfido2-1 libngtcp2-16
  libngtcp2-crypto-gnutls8 libx11-6 libx11-data libxau6 libxcb1 libxdmcp6 libxext6 libxmuu1 openssh-client
  xauth
0 upgraded, 19 newly installed, 0 to remove and 3 not upgraded.
Need to get 14.4 MB of archives.
After this operation, 64.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://deb.debian.org/debian trixie/main amd64 less amd64 668-1 [161 kB]
Get:2 http://deb.debian.org/debian trixie/main amd64 libedit2 amd64 3.1-20250104-1 [93.8 kB]
Get:3 http://deb.debian.org/debian trixie/main amd64 libcbor0.10 amd64 0.10.2-2 [28.3 kB]
Get:4 http://deb.debian.org/debian trixie/main amd64 libfido2-1 amd64 1.15.0-1+b1 [78.7 kB]
Get:5 http://deb.debian.org/debian-security trixie-security/main amd64 openssh-client amd64 1:10.0p1-7+deb13u2 [986 kB]
Get:6 http://deb.debian.org/debian-security trixie-security/main amd64 libngtcp2-16 amd64 1.11.0-1+deb13u1 [132 kB]
Get:7 http://deb.debian.org/debian-security trixie-security/main amd64 libngtcp2-crypto-gnutls8 amd64 1.11.0-1+deb13u1 [29.5 kB]
Get:8 http://deb.debian.org/debian trixie/main amd64 libcurl3t64-gnutls amd64 8.14.1-2+deb13u2 [383 kB]
Get:9 http://deb.debian.org/debian trixie/main amd64 liberror-perl all 0.17030-1 [26.9 kB]
Get:10 http://deb.debian.org/debian trixie/main amd64 git-man all 1:2.47.3-0+deb13u1 [2205 kB]
Get:11 http://deb.debian.org/debian trixie/main amd64 git amd64 1:2.47.3-0+deb13u1 [8862 kB]
Get:12 http://deb.debian.org/debian trixie/main amd64 libxau6 amd64 1:1.0.11-1 [20.4 kB]
Get:13 http://deb.debian.org/debian trixie/main amd64 libxdmcp6 amd64 1:1.1.5-1 [27.8 kB]
Get:14 http://deb.debian.org/debian trixie/main amd64 libxcb1 amd64 1.17.0-2+b1 [144 kB]
Get:15 http://deb.debian.org/debian trixie/main amd64 libx11-data all 2:1.8.12-1 [343 kB]
Get:16 http://deb.debian.org/debian trixie/main amd64 libx11-6 amd64 2:1.8.12-1 [815 kB]
Get:17 http://deb.debian.org/debian trixie/main amd64 libxext6 amd64 2:1.3.4-1+b3 [50.4 kB]
Get:18 http://deb.debian.org/debian trixie/main amd64 libxmuu1 amd64 2:1.1.3-3+b4 [21.9 kB]
Get:19 http://deb.debian.org/debian trixie/main amd64 xauth amd64 1:1.1.2-1.1 [35.9 kB]
Fetched 14.4 MB in 1s (10.4 MB/s)
debconf: unable to initialize frontend: Dialog
debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 79, <STDIN> line 19.)
debconf: falling back to frontend: Readline
Selecting previously unselected package less.
(Reading database ... 18182 files and directories currently installed.)
Preparing to unpack .../00-less_668-1_amd64.deb ...
Unpacking less (668-1) ...
Selecting previously unselected package libedit2:amd64.
Preparing to unpack .../01-libedit2_3.1-20250104-1_amd64.deb ...
Unpacking libedit2:amd64 (3.1-20250104-1) ...
Selecting previously unselected package libcbor0.10:amd64.
Preparing to unpack .../02-libcbor0.10_0.10.2-2_amd64.deb ...
Unpacking libcbor0.10:amd64 (0.10.2-2) ...
Selecting previously unselected package libfido2-1:amd64.
Preparing to unpack .../03-libfido2-1_1.15.0-1+b1_amd64.deb ...
Unpacking libfido2-1:amd64 (1.15.0-1+b1) ...
Selecting previously unselected package openssh-client.
Preparing to unpack .../04-openssh-client_1%3a10.0p1-7+deb13u2_amd64.deb ...
Unpacking openssh-client (1:10.0p1-7+deb13u2) ...
Selecting previously unselected package libngtcp2-16:amd64.
Preparing to unpack .../05-libngtcp2-16_1.11.0-1+deb13u1_amd64.deb ...
Unpacking libngtcp2-16:amd64 (1.11.0-1+deb13u1) ...
Selecting previously unselected package libngtcp2-crypto-gnutls8:amd64.
Preparing to unpack .../06-libngtcp2-crypto-gnutls8_1.11.0-1+deb13u1_amd64.deb ...
Unpacking libngtcp2-crypto-gnutls8:amd64 (1.11.0-1+deb13u1) ...
Selecting previously unselected package libcurl3t64-gnutls:amd64.
Preparing to unpack .../07-libcurl3t64-gnutls_8.14.1-2+deb13u2_amd64.deb ...
Unpacking libcurl3t64-gnutls:amd64 (8.14.1-2+deb13u2) ...
Selecting previously unselected package liberror-perl.
Preparing to unpack .../08-liberror-perl_0.17030-1_all.deb ...
Unpacking liberror-perl (0.17030-1) ...
Selecting previously unselected package git-man.
Preparing to unpack .../09-git-man_1%3a2.47.3-0+deb13u1_all.deb ...
Unpacking git-man (1:2.47.3-0+deb13u1) ...
Selecting previously unselected package git.
Preparing to unpack .../10-git_1%3a2.47.3-0+deb13u1_amd64.deb ...
Unpacking git (1:2.47.3-0+deb13u1) ...
Selecting previously unselected package libxau6:amd64.
Preparing to unpack .../11-libxau6_1%3a1.0.11-1_amd64.deb ...
Unpacking libxau6:amd64 (1:1.0.11-1) ...
Selecting previously unselected package libxdmcp6:amd64.
Preparing to unpack .../12-libxdmcp6_1%3a1.1.5-1_amd64.deb ...
Unpacking libxdmcp6:amd64 (1:1.1.5-1) ...
Selecting previously unselected package libxcb1:amd64.
Preparing to unpack .../13-libxcb1_1.17.0-2+b1_amd64.deb ...
Unpacking libxcb1:amd64 (1.17.0-2+b1) ...
Selecting previously unselected package libx11-data.
Preparing to unpack .../14-libx11-data_2%3a1.8.12-1_all.deb ...
Unpacking libx11-data (2:1.8.12-1) ...
Selecting previously unselected package libx11-6:amd64.
Preparing to unpack .../15-libx11-6_2%3a1.8.12-1_amd64.deb ...
Unpacking libx11-6:amd64 (2:1.8.12-1) ...
Selecting previously unselected package libxext6:amd64.
Preparing to unpack .../16-libxext6_2%3a1.3.4-1+b3_amd64.deb ...
Unpacking libxext6:amd64 (2:1.3.4-1+b3) ...
Selecting previously unselected package libxmuu1:amd64.
Preparing to unpack .../17-libxmuu1_2%3a1.1.3-3+b4_amd64.deb ...
Unpacking libxmuu1:amd64 (2:1.1.3-3+b4) ...
Selecting previously unselected package xauth.
Preparing to unpack .../18-xauth_1%3a1.1.2-1.1_amd64.deb ...
Unpacking xauth (1:1.1.2-1.1) ...
Setting up libxau6:amd64 (1:1.0.11-1) ...
Setting up libxdmcp6:amd64 (1:1.1.5-1) ...
Setting up libxcb1:amd64 (1.17.0-2+b1) ...
Setting up libcbor0.10:amd64 (0.10.2-2) ...
Setting up libedit2:amd64 (3.1-20250104-1) ...
Setting up less (668-1) ...
Setting up liberror-perl (0.17030-1) ...
Setting up libx11-data (2:1.8.12-1) ...
Setting up git-man (1:2.47.3-0+deb13u1) ...
Setting up libx11-6:amd64 (2:1.8.12-1) ...
Setting up libngtcp2-16:amd64 (1.11.0-1+deb13u1) ...
Setting up libfido2-1:amd64 (1.15.0-1+b1) ...
Setting up libxmuu1:amd64 (2:1.1.3-3+b4) ...
Setting up libngtcp2-crypto-gnutls8:amd64 (1.11.0-1+deb13u1) ...
Setting up openssh-client (1:10.0p1-7+deb13u2) ...
Setting up libcurl3t64-gnutls:amd64 (8.14.1-2+deb13u2) ...
Setting up libxext6:amd64 (2:1.3.4-1+b3) ...
Setting up git (1:2.47.3-0+deb13u1) ...
Setting up xauth (1:1.1.2-1.1) ...
Processing triggers for libc-bin (2.41-12+deb13u2) ...

3. apt-get install unzip
"unzip" をインストールする。

実行結果:OK
root@05fa4e42bbcd:~# apt-get install unzip
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Suggested packages:
  zip
The following NEW packages will be installed:
  unzip
0 upgraded, 1 newly installed, 0 to remove and 3 not upgraded.
Need to get 173 kB of archives.
After this operation, 396 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian trixie/main amd64 unzip amd64 6.0-29 [173 kB]
Fetched 173 kB in 0s (1845 kB/s)
debconf: unable to initialize frontend: Dialog
debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 79,  line 1.)
debconf: falling back to frontend: Readline
Selecting previously unselected package unzip.
(Reading database ... 19746 files and directories currently installed.)
Preparing to unpack .../unzip_6.0-29_amd64.deb ...
Unpacking unzip (6.0-29) ...
Setting up unzip (6.0-29) ...

4. apt-get install zip
"zip" をインストールする。

実行結果:OK
root@05fa4e42bbcd:~# apt-get install zip
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
  zip
0 upgraded, 1 newly installed, 0 to remove and 3 not upgraded.
Need to get 235 kB of archives.
After this operation, 642 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian trixie/main amd64 zip amd64 3.0-15 [235 kB]
Fetched 235 kB in 0s (2226 kB/s)
debconf: unable to initialize frontend: Dialog
debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 79, <STDIN> line 1.)
debconf: falling back to frontend: Readline
Selecting previously unselected package zip.
(Reading database ... 19764 files and directories currently installed.)
Preparing to unpack .../archives/zip_3.0-15_amd64.deb ...
Unpacking zip (3.0-15) ...
Setting up zip (3.0-15) ...

5. docker-php-ext-install zip
ZIP PHP拡張モジュールを docker-php-ext-install コマンドを使ってインストールする。

実行結果:失敗
root@05fa4e42bbcd:~# docker-php-ext-install zip
Configuring for:
PHP Api Version:         20230831
Zend Module Api No:      20230831
Zend Extension Api No:   420230831
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for a sed that does not truncate output... /usr/bin/sed
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether the compiler supports GNU C... yes
checking whether cc accepts -g... yes
checking for cc option to enable C11 features... none needed
checking how to run the C preprocessor... cc -E
checking for egrep -e... (cached) /usr/bin/grep -E
checking for icc... no
checking for suncc... no
checking for system library directory... lib
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking target system type... x86_64-pc-linux-gnu
checking for PHP prefix... /usr/local
checking for PHP includes... -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib
checking for PHP extension directory... /usr/local/lib/php/extensions/no-debug-non-zts-20230831
checking for PHP installed headers prefix... /usr/local/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for gawk... no
checking for nawk... nawk
checking if nawk is broken... no
checking for zip archive read/write support... yes, shared
checking for libzip >= 0.11 libzip != 1.3.1 libzip != 1.7.0... no
configure: error: Package requirements (libzip >= 0.11 libzip != 1.3.1 libzip != 1.7.0) were not met:

Package 'libzip', required by 'virtual:world', not found
Package 'libzip', required by 'virtual:world', not found
Package 'libzip', required by 'virtual:world', not found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables LIBZIP_CFLAGS
and LIBZIP_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.

libzip-devインストール

"docker-php-ext-install zip" コマンドを実行するには "libzip-dev" が必要っぽいのでインストールする。

1. apt-get install libzip-dev
libzip-dev をインストールする。

実行結果:OK
root@05fa4e42bbcd:~# apt-get install libzip-dev
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  libzip5 zipcmp zipmerge ziptool zlib1g-dev
The following NEW packages will be installed:
  libzip-dev libzip5 zipcmp zipmerge ziptool zlib1g-dev
0 upgraded, 6 newly installed, 0 to remove and 3 not upgraded.
Need to get 1220 kB of archives.
After this operation, 2063 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://deb.debian.org/debian trixie/main amd64 libzip5 amd64 1.11.3-2 [62.6 kB]
Get:2 http://deb.debian.org/debian trixie/main amd64 zipcmp amd64 1.11.3-2 [19.8 kB]
Get:3 http://deb.debian.org/debian trixie/main amd64 zipmerge amd64 1.11.3-2 [14.5 kB]
Get:4 http://deb.debian.org/debian trixie/main amd64 ziptool amd64 1.11.3-2 [22.6 kB]
Get:5 http://deb.debian.org/debian trixie/main amd64 zlib1g-dev amd64 1:1.3.dfsg+really1.3.1-1+b1 [920 kB]
Get:6 http://deb.debian.org/debian trixie/main amd64 libzip-dev amd64 1.11.3-2 [181 kB]
Fetched 1220 kB in 0s (3538 kB/s)
debconf: unable to initialize frontend: Dialog
debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 79, <STDIN> line 6.)
debconf: falling back to frontend: Readline
Selecting previously unselected package libzip5:amd64.
(Reading database ... 19779 files and directories currently installed.)
Preparing to unpack .../0-libzip5_1.11.3-2_amd64.deb ...
Unpacking libzip5:amd64 (1.11.3-2) ...
Selecting previously unselected package zipcmp.
Preparing to unpack .../1-zipcmp_1.11.3-2_amd64.deb ...
Unpacking zipcmp (1.11.3-2) ...
Selecting previously unselected package zipmerge.
Preparing to unpack .../2-zipmerge_1.11.3-2_amd64.deb ...
Unpacking zipmerge (1.11.3-2) ...
Selecting previously unselected package ziptool.
Preparing to unpack .../3-ziptool_1.11.3-2_amd64.deb ...
Unpacking ziptool (1.11.3-2) ...
Selecting previously unselected package zlib1g-dev:amd64.
Preparing to unpack .../4-zlib1g-dev_1%3a1.3.dfsg+really1.3.1-1+b1_amd64.deb ...
Unpacking zlib1g-dev:amd64 (1:1.3.dfsg+really1.3.1-1+b1) ...
Selecting previously unselected package libzip-dev:amd64.
Preparing to unpack .../5-libzip-dev_1.11.3-2_amd64.deb ...
Unpacking libzip-dev:amd64 (1.11.3-2) ...
Setting up libzip5:amd64 (1.11.3-2) ...
Setting up zipmerge (1.11.3-2) ...
Setting up zlib1g-dev:amd64 (1:1.3.dfsg+really1.3.1-1+b1) ...
Setting up zipcmp (1.11.3-2) ...
Setting up ziptool (1.11.3-2) ...
Setting up libzip-dev:amd64 (1.11.3-2) ...
Processing triggers for libc-bin (2.41-12+deb13u2) ...

docker-php-ext-install zip

あらためて docker-php-ext-install zip コマンドを実行してみる。

1. docker-php-ext-install zip
実行結果:今度はOK!
root@05fa4e42bbcd:~# docker-php-ext-install zip
Configuring for:
PHP Api Version:         20230831
Zend Module Api No:      20230831
Zend Extension Api No:   420230831
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for a sed that does not truncate output... /usr/bin/sed
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether the compiler supports GNU C... yes
checking whether cc accepts -g... yes
checking for cc option to enable C11 features... none needed
checking how to run the C preprocessor... cc -E
checking for egrep -e... (cached) /usr/bin/grep -E
checking for icc... no
checking for suncc... no
checking for system library directory... lib
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking target system type... x86_64-pc-linux-gnu
checking for PHP prefix... /usr/local
checking for PHP includes... -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib
checking for PHP extension directory... /usr/local/lib/php/extensions/no-debug-non-zts-20230831
checking for PHP installed headers prefix... /usr/local/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for gawk... no
checking for nawk... nawk
checking if nawk is broken... no
checking for zip archive read/write support... yes, shared
checking for libzip >= 0.11 libzip != 1.3.1 libzip != 1.7.0... no
configure: error: Package requirements (libzip >= 0.11 libzip != 1.3.1 libzip != 1.7.0) were not met:

Package 'libzip', required by 'virtual:world', not found
Package 'libzip', required by 'virtual:world', not found
Package 'libzip', required by 'virtual:world', not found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables LIBZIP_CFLAGS
and LIBZIP_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.
root@05fa4e42bbcd:~# apt-get install libzip-dev
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  libzip5 zipcmp zipmerge ziptool zlib1g-dev
The following NEW packages will be installed:
  libzip-dev libzip5 zipcmp zipmerge ziptool zlib1g-dev
0 upgraded, 6 newly installed, 0 to remove and 3 not upgraded.
Need to get 1220 kB of archives.
After this operation, 2063 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://deb.debian.org/debian trixie/main amd64 libzip5 amd64 1.11.3-2 [62.6 kB]
Get:2 http://deb.debian.org/debian trixie/main amd64 zipcmp amd64 1.11.3-2 [19.8 kB]
Get:3 http://deb.debian.org/debian trixie/main amd64 zipmerge amd64 1.11.3-2 [14.5 kB]
Get:4 http://deb.debian.org/debian trixie/main amd64 ziptool amd64 1.11.3-2 [22.6 kB]
Get:5 http://deb.debian.org/debian trixie/main amd64 zlib1g-dev amd64 1:1.3.dfsg+really1.3.1-1+b1 [920 kB]
Get:6 http://deb.debian.org/debian trixie/main amd64 libzip-dev amd64 1.11.3-2 [181 kB]
Fetched 1220 kB in 0s (3538 kB/s)
debconf: unable to initialize frontend: Dialog
debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 79, <STDIN> line 6.)
debconf: falling back to frontend: Readline
Selecting previously unselected package libzip5:amd64.
(Reading database ... 19779 files and directories currently installed.)
Preparing to unpack .../0-libzip5_1.11.3-2_amd64.deb ...
Unpacking libzip5:amd64 (1.11.3-2) ...
Selecting previously unselected package zipcmp.
Preparing to unpack .../1-zipcmp_1.11.3-2_amd64.deb ...
Unpacking zipcmp (1.11.3-2) ...
Selecting previously unselected package zipmerge.
Preparing to unpack .../2-zipmerge_1.11.3-2_amd64.deb ...
Unpacking zipmerge (1.11.3-2) ...
Selecting previously unselected package ziptool.
Preparing to unpack .../3-ziptool_1.11.3-2_amd64.deb ...
Unpacking ziptool (1.11.3-2) ...
Selecting previously unselected package zlib1g-dev:amd64.
Preparing to unpack .../4-zlib1g-dev_1%3a1.3.dfsg+really1.3.1-1+b1_amd64.deb ...
Unpacking zlib1g-dev:amd64 (1:1.3.dfsg+really1.3.1-1+b1) ...
Selecting previously unselected package libzip-dev:amd64.
Preparing to unpack .../5-libzip-dev_1.11.3-2_amd64.deb ...
Unpacking libzip-dev:amd64 (1.11.3-2) ...
Setting up libzip5:amd64 (1.11.3-2) ...
Setting up zipmerge (1.11.3-2) ...
Setting up zlib1g-dev:amd64 (1:1.3.dfsg+really1.3.1-1+b1) ...
Setting up zipcmp (1.11.3-2) ...
Setting up ziptool (1.11.3-2) ...
Setting up libzip-dev:amd64 (1.11.3-2) ...
Processing triggers for libc-bin (2.41-12+deb13u2) ...
root@05fa4e42bbcd:~#
root@05fa4e42bbcd:~#
root@05fa4e42bbcd:~#
root@05fa4e42bbcd:~#
root@05fa4e42bbcd:~# docker-php-ext-install zip
Configuring for:
PHP Api Version:         20230831
Zend Module Api No:      20230831
Zend Extension Api No:   420230831
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for a sed that does not truncate output... /usr/bin/sed
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether the compiler supports GNU C... yes
checking whether cc accepts -g... yes
checking for cc option to enable C11 features... none needed
checking how to run the C preprocessor... cc -E
checking for egrep -e... (cached) /usr/bin/grep -E
checking for icc... no
checking for suncc... no
checking for system library directory... lib
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking target system type... x86_64-pc-linux-gnu
checking for PHP prefix... /usr/local
checking for PHP includes... -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib
checking for PHP extension directory... /usr/local/lib/php/extensions/no-debug-non-zts-20230831
checking for PHP installed headers prefix... /usr/local/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for gawk... no
checking for nawk... nawk
checking if nawk is broken... no
checking for zip archive read/write support... yes, shared
checking for libzip >= 0.11 libzip != 1.3.1 libzip != 1.7.0... yes
checking for zip_file_set_mtime in -lzip... yes
checking for zip_file_set_encryption in -lzip... yes
checking for zip_libzip_version in -lzip... yes
checking for zip_register_progress_callback_with_state in -lzip... yes
checking for zip_register_cancel_callback_with_state in -lzip... yes
checking for zip_compression_method_supported in -lzip... yes
checking for a sed that does not truncate output... /usr/bin/sed
checking for ld used by cc... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for /usr/bin/ld option to reload object files... -r
checking for BSD-compatible nm... /usr/bin/nm -B
checking whether ln -s works... yes
checking how to recognize dependent libraries... pass_all
checking for stdio.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for strings.h... yes
checking for sys/stat.h... yes
checking for sys/types.h... yes
checking for unistd.h... yes
checking for dlfcn.h... yes
checking the maximum length of command line arguments... 1572864
checking command to parse /usr/bin/nm -B output from cc object... ok
checking for objdir... .libs
checking for ar... ar
checking for ranlib... ranlib
checking for strip... strip
checking if cc supports -fno-rtti -fno-exceptions... no
checking for cc option to produce PIC... -fPIC
checking if cc PIC flag -fPIC works... yes
checking if cc static flag -static works... yes
checking if cc supports -c -o file.o... yes
checking whether the cc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... no

creating libtool
appending configuration tag "CXX" to libtool
configure: patching config.h.in
configure: creating ./config.status
config.status: creating config.h
/bin/bash /usr/src/php/ext/zip/libtool --tag=CC --mode=compile cc -I. -I/usr/src/php/ext/zip -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE    -DZEND_COMPILE_DL_EXT=1 -c /usr/src/php/ext/zip/php_zip.c -o php_zip.lo  -MMD -MF php_zip.dep -MT php_zip.lo
mkdir .libs
 cc -I. -I/usr/src/php/ext/zip -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE -DZEND_COMPILE_DL_EXT=1 -c /usr/src/php/ext/zip/php_zip.c -MMD -MF php_zip.dep -MT php_zip.lo  -fPIC -DPIC -o .libs/php_zip.o
/bin/bash /usr/src/php/ext/zip/libtool --tag=CC --mode=compile cc -I. -I/usr/src/php/ext/zip -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE    -DZEND_COMPILE_DL_EXT=1 -c /usr/src/php/ext/zip/zip_stream.c -o zip_stream.lo  -MMD -MF zip_stream.dep -MT zip_stream.lo
 cc -I. -I/usr/src/php/ext/zip -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE -DZEND_COMPILE_DL_EXT=1 -c /usr/src/php/ext/zip/zip_stream.c -MMD -MF zip_stream.dep -MT zip_stream.lo  -fPIC -DPIC -o .libs/zip_stream.o
/bin/bash /usr/src/php/ext/zip/libtool --tag=CC --mode=link cc -shared -I/usr/src/php/ext/zip/include -I/usr/src/php/ext/zip/main -I/usr/src/php/ext/zip -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H  -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE  -Wl,-O1 -pie  -o zip.la -export-dynamic -avoid-version -prefer-pic -module -rpath /usr/src/php/ext/zip/modules  php_zip.lo zip_stream.lo -lzip
cc -shared  .libs/php_zip.o .libs/zip_stream.o  -lzip  -Wl,-O1 -Wl,-soname -Wl,zip.so -o .libs/zip.so
creating zip.la
(cd .libs && rm -f zip.la && ln -s ../zip.la zip.la)
/bin/bash /usr/src/php/ext/zip/libtool --tag=CC --mode=install cp ./zip.la /usr/src/php/ext/zip/modules
cp ./.libs/zip.so /usr/src/php/ext/zip/modules/zip.so
cp ./.libs/zip.lai /usr/src/php/ext/zip/modules/zip.la
PATH="$PATH:/sbin" ldconfig -n /usr/src/php/ext/zip/modules
----------------------------------------------------------------------
Libraries have been installed in:
   /usr/src/php/ext/zip/modules

If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,--rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------

Build complete.
Don't forget to run 'make test'.

+ strip --strip-all modules/zip.so
Installing shared extensions:     /usr/local/lib/php/extensions/no-debug-non-zts-20230831/
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
Xdebug: [Step Debug] Time-out connecting to debugging client, waited: 200 ms. Tried: 172.25.0.1:9003 (through xdebug.client_host/xdebug.client_port).
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
Xdebug: [Step Debug] Time-out connecting to debugging client, waited: 200 ms. Tried: 172.25.0.1:9003 (through xdebug.client_host/xdebug.client_port).
find . -name \*.gcno -o -name \*.gcda | xargs rm -f
find . -name \*.lo -o -name \*.o -o -name \*.dep | xargs rm -f
find . -name \*.la -o -name \*.a | xargs rm -f
find . -name \*.so | xargs rm -f
find . -name .libs -a -type d|xargs rm -rf
rm -f libphp.la      modules/* libs/*
rm -f ext/opcache/jit/zend_jit_x86.c
rm -f ext/opcache/jit/zend_jit_arm64.c
rm -f ext/opcache/minilua

Twigインストール

再度 Twig のインストールをやってみる。

1. composer require twig/twig
※ composerコマンドはrootのhomeディレクトリで実行してしまったが、本来はPHPのプロジェクトフォルダ上で実行すること。

実行結果:
root@05fa4e42bbcd:~# composer require twig/twig
Xdebug: [Log Files] File '/tmp/xdebug.log' could not be opened.
Xdebug: [Step Debug] Time-out connecting to debugging client, waited: 200 ms. Tried: 172.25.0.1:9003 (through xdebug.client_host/xdebug.client_port).
./composer.json has been updated
Running composer update twig/twig
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
  - Downloading symfony/polyfill-mbstring (v1.36.0)
  - Downloading symfony/polyfill-ctype (v1.36.0)
  - Downloading symfony/deprecation-contracts (v3.6.0)
  - Downloading twig/twig (v3.24.0)
  - Installing symfony/polyfill-mbstring (v1.36.0): Extracting archive
  - Installing symfony/polyfill-ctype (v1.36.0): Extracting archive
  - Installing symfony/deprecation-contracts (v3.6.0): Extracting archive
  - Installing twig/twig (v3.24.0): Extracting archive
Generating autoload files
4 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
No security vulnerability advisories found.
Using version ^3.24 for twig/twig

まとめ

結局 Twig を Dockerコンテナにインストールする場合の手順は・・
apt-get update && \
apt-get install -y \
    libzip-dev \
    git \
    unzip \
    zip \
&& docker-php-ext-install zip

composer require twig/twig
となる。


WSL Docker PHP Twig

その他の記事