menu

Engine PHP - Create txt file


Pada tutorial kali ini kita akan belajar membuat sebuah file .txt dari php, biasanya file .txt ini sering kali digunakan saat kita akan membuat sebuah sistem crontab yang membutuhkan data log dari proses crontab tersebut.

Data log ini biasanya disimpan pada file .txt agar suatu saat nanti jika terjadi error pada crontab yang menyebabkan proses crontab terhenti kita bisa tahu sampai diproses mana crontab tersebut terhenti, sehingga kita bisa mengidentifikasi penyebab berhentinya crontab dan dapat melanjutkan kembali proses crontab tersebut dari posisi dia berhenti sebelumnya.

Berikut syntax-syntax membuat file .txt,
//akses file yang akan dipakai
$myfile = fopen("/path/file/name_file.txt", "a") or die("Unable to open file!");
//write text
$txt = "------------test-----------";
fwrite($myfile, $txt);
//close file
fclose($myfile);

Aturan akses file bisa dilihat disini.
Tutorial ini adalah penyempurnaan dari tutorila sebelumnya tentang Move database field to other database.

Oke langsung saja kita praktekan tutorialnya.

Pertama buka file movedatabaselog.php yang sudah dibuat pada tutorial sebelumnya, edit menjadi seperti ini.
<?php
  $host="localhost";
  $user="root";
  $pass="root";  

  $dbname1 = "source_logs";
  $dbname2 = "backup_logs";

  $db=mysql_connect($host,$user,$pass);
  
  $sql2="USE $dbname2";
  mysql_query($sql2,$db);

  //create logs processing--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  $myfile = fopen("/var/www/html/crontab/log_processing.txt", "a") or die("Unable to open file!");
  $date=strtotime("now");
  $enddate = strtotime("-7 days", $date);
  //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  //cek any databse or not?
  $sql = "SELECT * FROM user_logs";
  $hsl1 = mysql_query($sql,$db);
  if (!$hsl1) {
    //create database if not exists
    $sql4 ="CREATE DATABASE IF NOT EXISTS `backup_FE` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci";
    mysql_query($sql4,$db);

    $txt = "Database was create \n";
    fwrite($myfile, $txt);

    $sql2="USE $dbname2";
    mysql_query($sql2,$db);

    //create table if not exists
    $sql4 = "CREATE TABLE IF NOT EXISTS `user_logs` (
              `id` bigint(20) NOT NULL,
              `user_id` bigint(20) DEFAULT NULL,
              `type` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `request_method` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `url` text COLLATE utf8_unicode_ci,
              `parameter_json` text COLLATE utf8_unicode_ci,
              `status` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `logable_id` int(11) DEFAULT NULL,
              `logable_type` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `ip` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `device_type` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `device` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `platform` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `platform_version` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `browser` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `browser_version` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `app_version` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `android` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `ios` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `duration` decimal(10,4) DEFAULT NULL,
              `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
              `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
              `deleted_at` timestamp NULL DEFAULT NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
    mysql_query($sql4,$db);

    //add primary key
    $sql4 = "ALTER TABLE `user_logs` ADD PRIMARY KEY (`id`)";
    mysql_query($sql4,$db);

    //add auto increment
    $sql4 = "ALTER TABLE `user_logs` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT";
    mysql_query($sql4,$db);

    $txt = "Table was create \n";
    fwrite($myfile, $txt);
  }

  //begin backup
  $sql = "SELECT * FROM user_logs";
  $hsl2 = mysql_query($sql,$db);
  $array2 = mysql_fetch_array($hsl2);
  if (!$array2) {
    //if empty field on database insert this

    $txt = "first insert on ".date("Y-m-d h:i:sa", $date)."\n";
    fwrite($myfile, $txt);
 
    $sql2="USE $dbname2";
    mysql_query($sql2,$db);
    
    $sql2="INSERT INTO user_logs (user_id,type,request_method,url,parameter_json,status,logable_id,logable_type,ip,device_type,device,platform,platform_version,browser,browser_version,app_version,android,ios,duration,created_at,updated_at,deleted_at) ";
    $sql2.="(SELECT user_id,type,request_method,url,parameter_json,status,logable_id,logable_type,ip,device_type,device,platform,platform_version,browser,browser_version,app_version,android,ios,duration,created_at,updated_at,deleted_at "; 
    $sql2.="FROM $dbname1.user_logs)";
    mysql_query($sql2,$db);

    $txt = "user_logs insert first DONE! at \n".$date;
    fwrite($myfile, $txt);
  } elseif ($array2) {
    //if database was insert before so insert this

    $txt = "backup from ".date("Y-m-d h:i:sa", $date)." until ".date("Y-m-d h:i:sa", $enddate)."\n";
    fwrite($myfile, $txt);

    $sql2="USE $dbname2";
    mysql_query($sql2,$db);
    
    $sql2="INSERT INTO user_logs (user_id,type,request_method,url,parameter_json,status,logable_id,logable_type,ip,device_type,device,platform,platform_version,browser,browser_version,app_version,android,ios,duration,created_at,updated_at,deleted_at) ";
    $sql2.="(SELECT user_id,type,request_method,url,parameter_json,status,logable_id,logable_type,ip,device_type,device,platform,platform_version,browser,browser_version,app_version,android,ios,duration,created_at,updated_at,deleted_at "; 
    $sql2.="FROM $dbname1.user_logs WHERE created_at > (SELECT created_at FROM $dbname2.user_logs ORDER BY created_at DESC LIMIT 1))";
    mysql_query($sql2,$db);

    $txt = "\n user_logs backup DONE! \n";
    fwrite($myfile, $txt);

    //delete logs that are not used anymore
    $sql3="USE $dbname1";
    mysql_query($sql3,$db);
    $sql3="DELETE FROM user_logs WHERE created_at < DATE_ADD(CURDATE(), INTERVAL -6 DAY)";
    mysql_query($sql3,$db);

    $txt = "delete user_logs source DONE! \n";
    fwrite($myfile, $txt); 

    $txt = "----------------------------------------- \n";
    fwrite($myfile, $txt);
    fclose($myfile);
  }
?>

Kemudian jalankan file tersebut pada terminal Ubuntu seperti ini.
php /var/www/html/crontab/movedatabaselog.php

Sehingga program tersebut akan secara otomatis membuat file log_processing.txt pada path /var/www/html/crontab/ yang berisi log dari proses menjalankan program tersebut.

Jika anda ingin menjalankannya pada crontab bisa lihat disini.

===DONE!===