Hope is a Dream. Dream is a Hope.

非公開ブログは再開しました。

ファイル名を作成日時で保存する。 php初心者メモ。

作成した日時のファイル名でサーバに保存したい。

こんな感じ
20120520161320.csv

phpで日付を取得する

  • time()関数
  • 現在の時刻をタイムスタンプで取得することができる。

  • date()関数

  • タイムスタンプのフォーマット変換
echo "<p>timestamp".time();
//1400570541

echo "<p>date() ". date("Y/m/d H:i:s",time());
//2014/05/20 16:22:21

echo "<p>date() ". date("YmdH:i:s");
//2014052016:22:21

timezoneの設定

ただ上のコードだとタイムゾーンが分からないと怒られた。

Warning: date(): It is not safe to rely on the system's timezone settings.   You are *required* to use the date.timezone setting or the date_default_timezone_set() function.   In case you used any of those methods and you are still getting this warning,   you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone

ので、タイムゾーンを明示する

タイムゾーンの設定 - はらぐろブログラマン

date_default_timezone_set('Asia/Tokyo');

ディレクトリ内の最新ファイルを取得する

// Linux 
// chdir('../data');
// $file_name = "../data/".exec('ls -tr');


// php
$path = '../data/';
$latest_mtime = 0;
$file_name = "";
if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $fname = $path.$file;
                $mtime = filemtime( $fname );
                if( $mtime > $latest_mtime ){
                    $latest_mtime = $mtime;
                    $file_name = $file;
                }
            }
        }
        closedir($handle);
    }