<?php

# Define options
define('HI_RES', "https://img.youtube.com/vi/{{yid}}/maxresdefault.jpg");
define('LO_RES', "https://img.youtube.com/vi/{{yid}}/0.jpg");

# Get YouTube ID
$yid = preg_replace('~\.\w+$~', '', $_GET['yid']);

# Try hi-res
$redirect = exists(url(HI_RES, $yid))
    ? url(HI_RES, $yid)
    : url(LO_RES, $yid);

# Redirect
header("Location: {$redirect}", true, 307);
exit();

function url($template, $yid) {
    return str_replace('{{yid}}', $yid, $template);
}

function exists($url) {
    $headers = get_headers($url);
    return strstr($headers[0], '404') === false;
}