2
\$\begingroup\$

Just a little thing I made to load 20 random images from imgur. I looked at the way that imgur references images on its site, and I felt like I could probably generate a random string of letters and numbers that would, on occasion, produce a valid image URL. So I threw this together in PHP, because I am trying to learn PHP. It takes a while to get the 20 that it does, way longer for more. I would like to speed it up, and my current project in PHP is to learn more about classes etc, but I really have no idea where to start.

I would love some feedback! I know this looks real amateur hour, but I am a real amateur, so go easy on me!

BEWARE: not everything on imgur is worksafe, so if you decide to try this code out on your own server, the images returned are truly random with no filter, so no telling what you might see.

<html>
<head>
    <title>Random imgur Loader</title>

    <style type='text/css'>
        #bg {
            position:fixed; 
            top:-50%; 
            left:-50%; 
            width:200%; 
            height:200%;
            z-index: -10;
        }
        #bg img {
            position:absolute; 
            top:0; 
            left:0; 
            right:0; 
            bottom:0; 
            margin:auto; 
            min-width:50%;
            min-height:50%;
            z-index: -10;
            opacity: 0.4;
        }
        #container { 
            width: 760px; 
            margin: 0 auto; 
        }
        .imgcell {
            border: 1px solid black;
        }
    </style>
</head>
<body>
<div id='container' style='text-align: center;'>

<?php
$gcode1=generateCode(5);
$url3="http://i.imgur.com/".$gcode1.".jpg";
?>
<div id="bg">
    <img src="<?=$url3?>" alt="">
</div>
<?php
$pagepath=$_SERVER["PHP_SELF"];
if ($_GET['numimg']=='') {
    $numimg=20;
} else {
    $numimg=$_GET['numimg'];
}
?>
<h1 style='font-family: verdana;'><?=$numimg?> random imgur images</h1>
<table border=0><tr>
<?php

function generateCode($length=6) {
    $source='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $code='';

    for ($i=0; $i<$length; $i++) {
        $code .= $source[(rand() % strlen($source))];
    }

return $code;
}

$ii=1;
while ($ii<=$numimg):
    $gcode=generateCode(5);
    $url="http://i.imgur.com/".$gcode.".jpg";
    $url2="http://www.imgur.com/".$gcode;
    $headerfile=get_headers($url2, 1);
    $http_code=$headerfile[1];
    $imgheader=get_headers($url, 1);
    $imgcode=$imgheader["Content-Type"];
    #echo $imgcode;

    if ($imgcode == 'image/gif') {
        $bcode='red';
    } else {
        $bcode='gray';
    }

    if($http_code!="HTTP/1.1 404 Not Found") {
        print("<td style='border: 2px solid $bcode' ><a target='_blank' href='$url2'><img title='$imgcode' width='160px' height='160px' src='$url'></a><td>");
        echo(str_repeat(' ',4096));
        if ($ii % 5 == 0) {
            print("</tr><tr>");
        }
        flush();
        $ii++;
    }
endwhile;
?>
</tr></table>
<?php print("<p><a href='$pagepath'>Get $numimg more!</a></p>");?>
</div> 
</body>
</html>
\$\endgroup\$
  • \$\begingroup\$ First of all I'd separate my php from the HTML. Create class of functions and call them on the HTML like myclass::myfunction(arguments) or similar. See Model-View-Controller \$\endgroup\$ – Alex May 14 '13 at 16:07
  • \$\begingroup\$ There's no way to really speed this up, since it's essentially random. It might be really fast the next time you run it or it might run forever (unlikely, but possible). You could spawn off several processes and check multiple urls in parallel, but since it's still random, there's no guarantee it'll actually find n images faster. By all means try refactoring it, see what other here say, and learn what you can (I'm all for that), but "using classes" is not a silver bullet in this case - the general approach is just slow. \$\endgroup\$ – Flambino May 14 '13 at 19:01
  • \$\begingroup\$ @Flambino Yeah it averages about 1.2 failures for every image it does find. That average goes up exponentially the longer I make the generated string length, some have 5, 6, 7 or more. I guess it takes longer on the longer strings because there might be fewer of those, plus a longer string means another power more possibilities. Pretty cool little proof of concept I guess, just looks ugly to me. I'm going to work on trimming it up a bit. Thanks for the input! \$\endgroup\$ – Refrax May 14 '13 at 20:57
2
\$\begingroup\$

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->get('feed_parser'); // This is just a SimplePie object
$feed->set_feed_url('http://feeds.feedburner.com/lolcats/rss');
$feed->init();
$items = $feed->get_items();
$item = $items[array_rand($items)]; // Gets one random image, but can modify for more
$item = $item->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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Apparently, imgur has a proper API, which might be easier than parsing the rss feed. It even has "random images" endpoint \$\endgroup\$ – Flambino May 15 '13 at 8:39
  • \$\begingroup\$ Ah I didn't even think about the fact that I was not being a very good netizen by hammering imgur :( Yeah their RSS feed might be more apporpriate. Also, their API has a random images endpoint?! wtf, well at least I learned some PHP in the process haha \$\endgroup\$ – Refrax May 16 '13 at 17:26
  • \$\begingroup\$ Good find Flambino! I'd definitely use their API. \$\endgroup\$ – Johntron May 16 '13 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.