PHP Snippets

PHP subtract 1 month from date formatted with date(“m-Y”) or date(“Y-m”)

$now = mktime(0, 0, 0, 12, 26, 2022);
$newdate = date("m-Y", strtotime("-1 months", $now));
$newdate = date("Y-m", strtotime("-1 months", $now));

Akan error jika tanggal pada akhir bulan (tgl. 31). Maka siasati ketika tgl tersebut, ganti dengan tanggal lain.

Difference between two months

//get Date diff as intervals
$d1 = new DateTime("2018-01-10 00:00:00");
$d2 = new DateTime("2019-05-18 01:23:45");
$interval = $d1->diff($d2);
$diffInSeconds = $interval->s; //45
$diffInMinutes = $interval->i; //23
$diffInHours = $interval->h; //8
$diffInDays = $interval->d; //21
$diffInMonths = $interval->m; //4
$diffInYears = $interval->y; //1

//or get Date difference as total difference
$d1 = strtotime("2018-01-10 00:00:00");
$d2 = strtotime("2019-05-18 01:23:45");
$totalSecondsDiff = abs($d1-$d2); //42600225
$totalMinutesDiff = $totalSecondsDiff/60; //710003.75
$totalHoursDiff = $totalSecondsDiff/60/60;//11833.39
$totalDaysDiff = $totalSecondsDiff/60/60/24; //493.05
$totalMonthsDiff = $totalSecondsDiff/60/60/24/30; //16.43
$totalYearsDiff = $totalSecondsDiff/60/60/24/365; //1.35

This does not work if the interval is more than 12 months. A difference of 13 months will show up as 1. As a user mentioned in a comment on the other answer, you can use echo $diffInMonths = $interval->m + 12*$interval->y to fix this.

Check if file exists using URL

Use get_header

function remote_file_exists($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if( $httpCode == 200 ){return true;}
    return false;
}
function UR_exists($url){
   $headers=get_headers($url);
   return stripos($headers[0],"200 OK")?true:false;
}

Get last distinct set of records / last record group by

 SELECT * 
 FROM [tableName] 
 WHERE id IN (SELECT MAX(id) FROM [tableName] GROUP BY code)

It’s and old post, but testing @smdrager above answer with large tables was very slow. My fix to this was using “inner join” instead of “where in”.

SELECT * 
 FROM [tableName] as t1
 INNER JOIN (SELECT MAX(id) as id FROM [tableName] GROUP BY code) as t2
 ON t1.id = t2.id

This worked really fast.