1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【PHP】cronを使って現在のBTC価格をメールに自動送信する処理

1
Posted at

前回の記事に記載した外部API情報をPHP curlを使ってビットコイン価格だけ取得をcronを使って自動でメール送信する処理をやってみた。

今回も当然ながら自分のメモ用です。
色々ツッコミどころあるかもしれませんが、ご容赦くださいw m(__)m

毎日午前10時にメール通知される様にメール送信処理の作成、cronの設定を行う

まずは

  • bitflyerのAPIを使ってBTC取得の処理
  • メール送信処理
cron_mail.php
<?php
$url = 'https://api.bitflyer.jp/v1/ticker?product_code=BTC_JPY';

//curlセッション初期化
$ch = curl_init();

//オプション設定
curl_setopt($ch, CURLOPT_URL, $url);//取得するURLを指定
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//実行結果を文字列で返す

//URLの情報を取得
$result = curl_exec($ch);

//結果の表示
$json = json_decode($result);

//セッションを終了
curl_close($ch);

mb_language("Japanese");
mb_internal_encoding("UTF-8");

$to ='xxxxxx@gmail.com';
$subject = '現在のBTC価格のご案内';
$message = '現在のBTC価格は:' . number_format($json->ltp) . '円です';
$headers = 'From:hogehoge@hoge.co.jp' . "\r\n";

mb_send_mail($to, $subject, $message, $headers);
?>

で、次にcron処理。
cronは自動実行するためのもので、以下のプロセスが必要となる。
①phpの場所を確認

$which php
/usr/bin/php

crontab -l でcron設定を確認(このフローはなくてもOK)

$crontab -l
no crontab for name

crontab -eでエディタが立ち上がるのでcronの処理内容を記述します。

例えば、1分毎にメール送信する処理する場合は以下のように記述。

*/1 * * * * /usr/bin/php /home/www/name/ディレクトリ名/cron_mail.php

毎朝10時の場合だと

0 10 * * * /usr/bin/php /home/www/name/ディレクトリ名/cron_mail.php

となる。

万が一

errors in crontab file, can't install.

とエラーが表示される場合は記述に問題がある。
よくあるのはパスの前の日時指定に半角スペースがない場合 がほとんどではないだろうか。

例えば先ほどの処理で

010*** /usr/bin/php /home/www/name/ディレクトリ名/cron_mail.php

なんてするとエラー表示され、もう一度編集するかどうか聞かれます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?