diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

Matching dates within a monthly Interval that crosses over multiple years with PHP and Carbon

function getDatesInRange($dates, $start, $end) {
    $datesInRange = $dates->filter(function ($date) use ($start, $end) {
        if ((int) $start->format('Y') === (int) $end->format('Y')) {
            $start->year((int)$date->format('Y'));
            $end-> year((int)$date->format('Y'));
        } elseif ((int) $start->format('Y') < (int) $end->format('Y')) {
            if ((int) $date->format('m') >= (int) $start->format('m')) {
                $start->year((int) $date->format('Y'));
                $end->year((int) $date->format('Y'))->addYears(1);
            } else {
                $end->year((int) $date->format('Y'));
                $start->year((int) $date->format('Y'))->subYears(1);
            }
        }

        return Carbon::parse($date)->isBetween($start, $end);
    });

    return $datesInRange;
}

Getting exif metadata from image base64 in PHP

Exif headers provide useful metadata when it comes to images such as the image's orientation.

If you have used / are using Intervention Image, you might have noticed that some of the pictures you upload are turned from portrait to landscape.

If you upload the image normally, in Laravel you can orientate the image properly like so:

Image::make(Request::file('image'))->orientate();

But if you get the image data as a base 64 string this approach won't work, but the following snippet can be used to get the desired information from the image

$stream_resource = "data://image/jpeg;base64," . $base_64_image_string;
$exif_meta = exif_read_data($stream_resource);

You can now get the image's orientation and act based on it's value

$orientation = $exif_meta["Orientation"];

Also, make sure you have this line in you php.ini file

allow_url_fopen=On

Otherwise you will get

ErrorException: exif_read_data(): Unable to open file in file [filename]