Random imgur image loader
Definitely separate your PHP from HTML as Alex suggested. You probably don't need to go the full MVC route for something so simple, but simply generating your PHP variables then outputing your HTML would make your code a lot more readable/manageable. 

I like your idea of generating a random string and checking it, but Flambino's right, it will never be reliable (by design) - also, imgur probably hates you ;) A simpler approach would be to consume imgur's RSS feed: http://feeds.feedburner.com/ImgurGallery?format=rss

I was bored one morning, so I added something similar to the login page of one of my projects. It pulls one random image from lolcats' RSS feed and inserts it into the page. Here's the code that pulls the image:

$feed = $this-&gt;get('feed_parser'); // This is just a SimplePie object
$feed-&gt;set_feed_url('http://feeds.feedburner.com/lolcats/rss');
$feed-&gt;init();
$items = $feed-&gt;get_items();
$item = $items[array_rand($items)]; // Gets one random image, but can modify for more
$item = $item-&gt;get_content();


$this->get('feed_parser') is just a fancy way of getting a SimplePie object from the PIMPLE container - you could just instantiate a SimplePie object yourself (if you want code you can't test). After running this code, $item would be a PHP array (or some collection class) containing the details of one image. In my case, I then exposed this as JSON and a REST API endpoint for use by JavaScript, but you could just as easily have PHP output the appropriate HTML.