Home > Mobile >  How to view 1 Line in a .txt Document, then display the next line the next day with PHP?
How to view 1 Line in a .txt Document, then display the next line the next day with PHP?

Time:08-08

I would like to add a different Coupon Code on my Site every day. Doing this manually seems to take up a lot of unnecessary time. Is there any way i could just paste 365 Codes into a .txt File and display 1 line per day?

CodePudding user response:

You could use date() to get the current day of the year and then file() to read the complete file as array.

<?php

// Fill the tmp file
define('CouponCodeFile', 'file.txt');

file_put_contents(CouponCodeFile, '');
for ($i=1; $i <= 365 ; $i  ) { 
    file_put_contents(CouponCodeFile, sprintf("Coupon_Code_Day_%s\n", $i), FILE_APPEND);
}

// Read Coupon Code from file 
$curr_day = date('z');
$CouponCodeFileLines = file(CouponCodeFile);
printf("Your Coupon Code for the day %d is: %s\n", $curr_day 1, $CouponCodeFileLines[$curr_day]);

?>

CodePudding user response:

You can create a table called coupons like so

create table coupons(
    id int primary key not null auto_increment,
    coupon_name varchar(255),
    start_date timestamp default CURRENT_TIMESTAMP ,
    end_date timestamp default CURRENT_TIMESTAMP,
    created_at timestamp default CURRENT_TIMESTAMP
);

Cron Script:

You can create a script like below to run on 1st day of every year:

Snippet:

<?php

$days = getDaysInTheYear(date('Y'));
$coupons = [];

$day = DateTime::createFromFormat('!Y-m-d',date('Y'). '-01-01');

for($i = 1; $i <= $days;   $i){
    $coupons[] = [
        getRandomChars(4) . '_CUP' . $i,
        $day->format('Y-m-d H:i:s'),
        $day->format('Y-m-d'). ' 23:59:59',
        date("Y-m-d H:i:s")
    ];

    $day = $day->add(new DateInterval('P1D'));
}

function getRandomChars($len){
    $chars = range('A', 'Z');
    shuffle($chars);
    $str = '';
    for($i = 0; $i < $len;   $i){
        $str .= $chars[rand(0, count($chars) - 1)];
    }
    
    return $str;
}

function getDaysInTheYear($year){
    return $year % 100 == 0 && $year % 400 == 0 || 
           $year % 100 != 0 && $year % 4 == 0 ? 366 : 365;
}


print_r($coupons);

/*

 mysqli DB connections etc

*/
// bulk insert all coupons at once

$coupons = array_map(fn($v) => "'".implode("','",$v). "'", $coupons);
try{
    if($conn->query("insert into coupons(coupon_name, start_date, end_date, created_at) values(". implode("),(", $coupons). ")") === false){
        throw new \Exception("Couldn't insert coupons: ". $conn->error);
    }
}catch(\Exception $e){
    // your code
}finally{
    $conn->close();
}

Online Demo

Cron syntax to setup on your server would be like so:

0 0 1 1 *

Cron mnemonic

Fetching coupons:

While fetching valid coupons, it could be as simple as:

<?php

$result = $conn->query("select * from coupons where start_date >= 'your_start_date' and end_date <= 'your_end_date');

// rest of your code
  •  Tags:  
  • php
  • Related