フレームワークを使わずに素のPHPだけでherokuにデプロイする関連記事が少なく、かなり苦戦しましたので自分なりにまとめてみました。
方法
$ heroku create {名}
$ git remote add heroku https://git.heroku.com/{名}.git
$ git init
$ git commit -m "test"
$ git push heroku master
(この際pushの中にindex.phpが無いとエラーになる)
※詳しくは読み進めていく中でディレクトリ構造のキャプチャがあるのでそちらを参考にしてください。
To https://git.heroku.com/phpkadai.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/{名}.git'
$heroku addons:add cleardb
(mysql入れる)
$ heroku config
CLEARDB_DATABASE_URL: mysql://[ユーザー名]:[パスワード]@[ホスト名]/[データベース名]?reconnect=true
heroku configで得られた結果を下記にそれぞれの箇所に入れながらコマンドを実行していきましょう。
$ heroku config:set DB_DATABASE=[データベース名]
$ heroku config:set DB_HOST=[ホスト名]
$ heroku config:set DB_USERNAME=[ユーザー名]
$ heroku config:set DB_PASSWORD=[パスワード]
$ touch procfile
$ vim procfile
__web: vendor/bin/heroku-php-apache2 web/を記入します。
vimの使い方が難しければローカル環境で直接ファイルを編集してから$ git push heroku master__をすればOK
※webディレクトリの中にherokuで表示させたいファイルを入れておきます。
webの中にindex.phpファイルを入れておく。(理由は上記)
procfileに記入した末尾のwebと実際にpushしたディレクトリにwebフォルダが一致していなかったり、webの位置がズレていると下記の様な画面表示となりますので注意が必要です。
$ heroku open
これでアプリが表示されるはずです。
バック側の処理は色々設定がありますので、そのまま読み進めてみましょう。
mysqlログイン方法
先ほどheroku config
した結果を元にmysqlにログインしてみましょう。
mysql --host=[ホスト名] --user=[ユーザー名] --password=[パスワード] [データベース名]
DBは作成できないので最初に用意されたものを使用しましょう。
MySQL [heroku_e2556b4168bb606]> show databases;
+------------------------+
| Database |
+------------------------+
| information_schema |
| heroku_e2556b4168bb606 |
+------------------------+
PDOを使ったDB接続
<?php session_start();?>
<?php
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));
$db_name = substr($url["path"], 1);
$db_host = $url["host"];
$user = $url["user"];
$password = $url["pass"];
$dsn = "mysql:dbname=".$db_name.";host=".$db_host;
$pdo=new PDO($dsn,$user,$password,array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
//ここまでがheroku関係のDB設定
$sql=$pdo->prepare('select * from customer where email=? and password=?');
$sql->execute([$_REQUEST['email'], $_REQUEST['password']] );
foreach($sql->fetchAll() as $row){
$_SESSION['customer']=[
'id'=>$row['id'], 'name'=>$row['name'],
'email'=>$row['email'],
'password'=>$row['password'] ];
}
if (isset($_SESSION['customer'])){
header('Location: index.php');
exit();
}
else{
$_SESSION['miss']="ログイン名またはパスワードが違います";
header('Location: login.php');
exit();
}
?>
ここのDB接続が間違っているとweb上では500エラーと表示されます。
ここまで来ればPHPを使用したバックの処理もできますのでアプリとして正常に動作するはずです。
番外編
herokuDBで遭遇したエラー
CREATE DATABASE db_name;
を実行したらこの様なエラーが表示されコマンドが実行されませんでした。
Error Code: 2013. Lost connection to MySQL server during query
解決方法
下記コマンドを打った後にDB上のコマンドが使えるはずです。
SHOW VARIABLES LIKE '%timeout';
MySQL [heroku_e2556b4168bb606]> SHOW VARIABLES LIKE '%timeout';
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id: 617088257
Current database: heroku_e2556b4168bb606
+----------------------------+----------+
| Variable_name | Value |
+----------------------------+----------+
| connect_timeout | 10 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 300 |
| innodb_rollback_on_timeout | OFF |
| interactive_timeout | 90 |
| lock_wait_timeout | 31536000 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| wait_timeout | 90 |
+----------------------------+----------+
10 rows in set (1.002 sec)
SET SESSION wait_timeout = 31536000;
MySQL [heroku_e2556b4168bb606]> SET SESSION wait_timeout = 31536000;
+----------------------------+----------+
| Variable_name | Value |
+----------------------------+----------+
| connect_timeout | 10 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 300 |
| innodb_rollback_on_timeout | OFF |
| interactive_timeout | 90 |
| lock_wait_timeout | 31536000 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| wait_timeout | 31536000 |
+----------------------------+----------+
10 rows in set (0.184 sec)
herokuに無いライブラリを追加する方法
私のローカル環境では市町村を使ったAPIが動作したのにherokuでは動作しませんでした。。。
$ heroku logs --tail
2020-04-12T02:50:40.672833+00:00 heroku[router]: at=info method=POST path="/php/yahoo-api.php" host=phpkadai.herokuapp.com request_id=4330cc55-23db-47a0-bf96-e0d0e99ecf5f fwd="126.94.72.102" dyno=web.1 connect=0ms service=72ms status=500 bytes=247 protocol=https
2020-04-12T02:50:40.671062+00:00 app[web.1]: [12-Apr-2020 02:50:40 UTC] PHP Fatal error: Uncaught Error: Call to undefined function mb_convert_encoding() in /app/web/php/yahoo-api.php:7
どうやらmb_convert_encoding()
がherokuには導入されていなかったみたいのなので、追加してみました。
{
"require": {
"php": "~7.2.27",
"ext-mbstring": "*" //これをherokuに追加
},
"require-dev": {
"heroku/heroku-buildpack-php": "*"
}
}
composer.jsonに記述してから下記の手順通りコマンド操作を行えばheroku上でmb_convert_encoding()
が使えました。
$ composer update
$ git add .
$ git commit -m "update"
$ git push heroku master