Can I use Plain PHP functions in tpl file?
For the first part of question:

You may output as form item the output of your custom function, where contain logic to get random image:

function MY_MODULE_form_alter(&amp;$form, &amp;$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $form['img_item'] = array(
          '#type' =&gt; 'markup',
          '#markup' =&gt; my_random_image_output(),
          '#weight' =&gt; -50
        );
    }
}

function my_random_image_output() {
    $output = '';

    // your custom logic to output one image $output = '&lt;img src=".... /&gt;'

    return $output;
}