こんにちは、鯨井貴博@opensourcetechです。
今回は、virtualbox上のCentOS6.6(64ビット)で、
LAMPを構築してみようと思います。
ちなみにLAMPとは、
Linux、Apache、MySQL、PHPの頭文字をとったもので、
DBと連動するWebアプリを開発する際によく使用されるソフトウェアの組み合わせです。
土台となるCentOS6.6(64ビット)であることは、
unameコマンドやredhat-releaseファイルから確認出来ます。
cat /etc/redhat-release
uname -r
必要ソフトウェアのインストール
yum install mysql-server
※今回はインストール済みでした。
yum install httpd
※今回はインストール済みでした。
yum install php php-mysql
PHPとApacheの動作確認
phpinfoを使用して、phpとApacheが正常に動作するか確認します。
方法は簡単、Apacheのドキュメントルートにindex.phpというファイルを作成し、
Apacheを起動後、クライアントからアクセスするだけです。
cd /var/www/html
vi index.php
/etc/init.d/httpd start
なお、必要に応じてiptablesの設定(iptables -F)等を行う事を忘れないようにして下さい。
index.phpの内容
<?php
phpinfo();
?>
クライアントのブラウザよりhttp://LinuxのIPアドレス/index.phpとして、
以下の画面が表示されれば、OKです。
データベース(MySQL)の設定等1
続いて、データベース(mysql)です。
まずは、mysqldを起動します。
/etc/init.d/mysqld start
念の為、netstatやpsで起動確認もしておきます。
netstat -tan | grep 3306
ps aux | grep mysql
起動が確認出来たら、mysql_secure_installationを用いてデータベースの構築を行います。
/usr/bin/mysql_secure_installation
英語でいろいろとメッセージが出てきますが、
rootユーザーのパスワード設定とそれ以外は基本的には「Y」を選択しておけば大丈夫です。
構築が出来たら、rootユーザーで接続が出来るか確認します。
mysql -u root -p
正常であれば、以下のように接続後、SQLでの操作が可能です。
各プログラムの自動起動設定
chkconfigでApacheとMySQLが自動起動するように変更しておきます。
chkconfig httpd on
chkconfig mysqld on
chkconfig --list | grep -E "(httpd|mysqld)"
データベース(MySQL)の設定等2
続いて、rootではないユーザーでデータベースに接続する為の設定を行います。
今回は、testuserというユーザーでtestdbというデータベースを使用出来るようにしています。
mysql -u root -p
create database testdb;
create user testuser identified by 'password';
このままでは、testuserはtestdbを使用する権限がないので、
権限を付与します。
grant select,insert,update,delete,create,drop on testdb.* to testuser;
※必要に応じてカスタマイズして下さい。
また、「show grants for testuser;」とすれば、
権限の確認が出来ます。
では、testuserに権限があるか確認します。
mysql -u testuser -p
「show databases;」や「use testdb;」で異常がなければOKでしょう。
Apache・PHP・MySQLの連動確認
Apacheのドキュメントルート(/var/www/html)に
mysql.phpを作成し、Apache・PHP・MySQLの連動を確認します。
mysql.php
<?php
$link = mysqli_connect ( "localhost", "testuser", "password", "testdb");
if (!$link) {
printf("Connect Error: %s\n", mysqli_connect_error());
exit();
}
printf("Connect Success: %s\n", mysqli_get_host_info($link));
mysqli_close($link);
?>
※上記ファイルは、phpからMySQLへ接続が出来れば”Connect” Success"、
NGなら”Connect Error”を返すというシンプルなものです。
クライアントのブラウザから、http://LinuxのIPアドレス/mysql.phpとアクセスすると、
結果が確認出来るかと思います。
phpMyAdminによるデータベース操作
こちらは必須ではありませんが、
MySQLのコマンド操作があまり得意でない場合には有効な手段かと思いますので、
必要な方だけ実施下さい。
phpMyAdminをCentOS6.6にインストールする場合は、
yumレポジトリを追加するなどの対応が必要です。
今回は、Epelレポジトリを追加しました。
rpm -ivh http://ftp.tsukuba.wide.ad.jp/Linux/fedora/epel/6/i386/epel-release-6-8.noarch.rpm
cd /etc/yum.repos.d(epel.repoの追加をチェックしましょう)
そして、yum install phpmyadmin
インストールが完了すると、/etc/httpd/conf.d配下にphpMyAdmin.confが生成されます。
デフォルトでは、ローカルホストからのアクセスしか許可されていないので、
必要なネットワークからアクセスように設定追加を行います。
Allow from 該当ネットワーク情報
そして、設定を再読み込みさせる為、Apacheを再起動。
/etc/init.d/httpd restart
クライアントブラウザから、http://LinuxのIPアドレス/phpMyAdminとアクセスすると、以下のログイン画面が出るはずです。
ここで使用するユーザーとパスワードは、MySQLのアカウントとなります。
ログイン後は、以下のようなWeb画面からMySQLを操作出来るようになります。
SQLの知識が少しあれば、なんとなく操作は出来るかと思います。
一応コマンドラインでも確認してみましたが、
大丈夫でした。
ブラウザからのデータベース操作
いよいよ、Webサーバ上にhtmlファイルおよびphpファイルを配置して、
データベースを操作します。
今回は、前述のphpMyAdminを用いてmembersというテーブルを予め作成し、
データの選択(SELECT)、データの追加(INSERT INTO)、データの更新(UPDATE)、
データの削除(DELETE)を行っています。
クライアントブラウザから操作するのは、以下のようなtest.htmlになり、
フォームの入力やクリックのみでデータベースの操作がお手軽に出来ます。
なお、今回使用したhtmlファイルとphpファイルの内容は、
以下となります。
test.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>データベース操作</title>
</head>
<body>
<br>
<H1>データベース操作を体験しましょう!</H1>
<br>
<p>※各操作を行った後は、ブラウザの戻るボタンで本画面に戻って下さい。</p>
<p>データベースのテーブルを表示したい場合は、以下をクリック</p>
<form action="list.php" method="post">
<input type="submit" value="テーブル表示" />
</form>
<br>
<p>データベースのテーブルにデータを追加したい場合は、以下をクリック</p>
<form action="insert.php" method="post">
FirstName:<br>
<input type="text" name="firstname" size="30" value="" /><br>
LastName:<br>
<input type="text" name="lastname" size="30" value="" /><br>
Comment:<br>
<input type="text" name="comment" size="30" value="" /><br>
<input type="submit" value="登録" />
</form>
<br>
<p>データベースのテーブルデータを更新したい場合は、<br>
ID番号を指定し以下をクリック</p>
<form action="update1.php" method="post">
ID:<br>
<input type="text" name="id" size="30" value="" /><br>
FirstName:<br>
<input type="text" name="firstname" size="30" value="" /><br>
<input type="submit" value="firstname更新" />
</form>
<br>
<form action="update2.php" method="post">
ID:<br>
<input type="text" name="id" size="30" value="" /><br>
LastName:<br>
<input type="text" name="lastname" size="30" value="" /><br>
<input type="submit" value="lastname更新" />
</form>
<br>
<form action="update3.php" method="post">
ID:<br>
<input type="text" name="id" size="30" value="" /><br>
Comment:<br>
<input type="text" name="comment" size="30" value="" /><br>
<input type="submit" value="comment更新" />
</form>
<br>
<p>データベースのテーブルデータを削除したい場合は、<br>
ID番号を指定し以下をクリック</p>
<form action="delete.php" method="post">
ID:<br>
<input type="text" name="id" size="30" value="" /><br>
<input type="submit" value="削除" />
</form>
</body>
</html>
list.php
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>テーブル表示</title>
</head>
<body>
<br>
<br>
<?php
$link = mysqli_connect ( "localhost", "testuser", "password", "testdb");
if (!$link) {
printf("Connect Error: %s\n", mysqli_connect_error());
exit();
}
$result = mysqli_query($link, "select * from members");
if (!$result) {
printf("Failed: %s\n", mysqli_connect_error());
exit();
}
print('<table border=1>');
print('<th>');
print('ID');
print('</th>');
print('<th>');
print('FirstName');
print('</th>');
print('<th>');
print('LastName');
print('</th>');
print('<th>');
print('Comment');
print('</th>');
while ($row = mysqli_fetch_assoc($result)) {
print('<tr>');
print('<td>');
print($row['id']);
print('</td>');
print('<td>');
print($row['firstname']);
print('</td>');
print('<td>');
print($row['lastname']);
print('</td>');
print('<td>');
print($row['comment']);
print('</td>');
print('</tr>');
}
print('</table>');
mysqli_close($link);
?>
</body>
</html>
insert.php
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>データ追加</title>
</head>
<body>
<br>
<br>
<?php
$link = mysqli_connect ( "localhost", "testuser", "password", "testdb");
if (!$link) {
printf("Connect Error: %s\n", mysqli_connect_error());
exit();
}
$id = $_REQUEST['id'];
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$comment = $_REQUEST['comment'];
$result = mysqli_query($link, "insert into members(firstname, lastname, comment) values('$firstname', '$lastname', '$comment')");
if (!$result) {
printf("Failed: %s\n", mysqli_connect_error());
exit();
}
print('登録完了');
include("list.php");
mysqli_close($link);
?>
</body>
</html>
delete.php
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>データ削除</title>
</head>
<body>
<br>
<br>
<?php
$link = mysqli_connect ( "localhost", "testuser", "password", "testdb");
if (!$link) {
printf("Connect Error: %s\n", mysqli_connect_error());
exit();
}
$id = $_REQUEST['id'];
$result = mysqli_query($link, "delete from members where id='$id'");
if (!$result) {
printf("Failed: %s\n", mysqli_connect_error());
exit();
}
print('削除完了');
include("list.php");
mysqli_close($link);
?>
</body>
</html>
update1.php
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>データ更新1(firstname)</title>
</head>
<body>
<br>
<br>
<?php
$link = mysqli_connect ( "localhost", "testuser", "password", "testdb");
if (!$link) {
printf("Connect Error: %s\n", mysqli_connect_error());
exit();
}
$id = $_REQUEST['id'];
$firstname = $_REQUEST['firstname'];
$result = mysqli_query($link, "update members set firstname='$firstname' where id='$id'");
if (!$result) {
printf("Failed: %s\n", mysqli_connect_error());
exit();
}
print('FirstName更新完了');
include("list.php");
mysqli_close($link);
?>
</body>
</html>
update2.php
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>データ更新2(lastname)</title>
</head>
<body>
<br>
<br>
<?php
$link = mysqli_connect ( "localhost", "testuser", "password", "testdb");
if (!$link) {
printf("Connect Error: %s\n", mysqli_connect_error());
exit();
}
$id = $_REQUEST['id'];
$lastname = $_REQUEST['lastname'];
$result = mysqli_query($link, "update members set lastname='$lastname' where id='$id'");
if (!$result) {
printf("Failed: %s\n", mysqli_connect_error());
exit();
}
print('LastName更新完了');
include("list.php");
mysqli_close($link);
?>
</body>
</html>
update3.php
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>データ更新3(comment)</title>
</head>
<body>
<br>
<br>
<?php
$link = mysqli_connect ( "localhost", "testuser", "password", "testdb");
if (!$link) {
printf("Connect Error: %s\n", mysqli_connect_error());
exit();
}
$id = $_REQUEST['id'];
$comment = $_REQUEST['comment'];
$result = mysqli_query($link, "update members set comment='$comment' where id='$id'");
if (!$result) {
printf("Failed: %s\n", mysqli_connect_error());
exit();
}
print('Comment更新完了');
include("list.php");
mysqli_close($link);
?>
</body>
</html>
以上、LAMP環境の構築でした。
2018年1月7日追記
-------
Githubに上記のコードを公開しました。
https://github.com/kujiraitakahiro/LAMP
うまく動作しない時に確認すべきポイント
・データベースの構造に間違いがないか
・HTMLの記述に間違いがないか(誤字など)
・PHPの記述に間違いがないか(syntax error、誤字など)
・HTMLファイルとPHPファイルの関連性(ファイル名やパラメータ名など)に間違いがないか
・tail -f /var/log/httpd/error_logで出力されるログがヒントになるかも