Get First Google Image Search Result with PHP

August 13th, 2011

Here’s a quick  & dirty way to get the thumbnail image for the first search result in Google Image Search:

<?php
if(isset($_GET['q'])){
 $q = urlencode($_GET['q']);
 $jsonurl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$q;
 $result = json_decode(file_get_contents($jsonurl), true);
 header("Content-Type: image/jpg");
 $img = imagecreatefromjpeg($result['responseData']['results'][0]['tbUrl']);
 imagejpeg($img);
 imagedestroy($img);
 
exit;
}
?>
<html>
<body>
<form action='' method='post'>
<fieldset>
<input type='text' name='q' /><input type='submit' name='submit' />
</fieldset>
</form>
<?php
if(isset($_POST['q'])){
 $q = urlencode($_POST['q']);
 $jsonurl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$q;
 $result = json_decode(file_get_contents($jsonurl), true);
 echo "<img src='{$result['responseData']['results'][0]['tbUrl']}' />";
}
?>
</body>
</html>

A few notes:

  • Your PHP install must have gd which it probably will if you’re running 5+ which is required for json_decode (the function file_get_contents is 5.2+, but is just a shorthand function.)
  • For my purposes I only needed a thumbnail-sized image, but Google’s API provides piles of useful data. View the data directly [example], and copy+paste into a parser [example] if you need help navigating the data structure they provide. PHP’s json_decode will turn Google’s JSON data object into a deeply-nested array (and using “true” for the optional second parameter will make it an associative array which is helpful.
  • When you access the script by URL with the 'q' variable set the image itself will be served, which I needed for my pipeline. This way I was able to call the script in the HTML itself via:
    • <img src='firstgoogleimage.php?q=figgalicous' /> which as of this writing serves:
      Mike Figueroa figgalicous

WordPress shortcode no-value attributes

June 23rd, 2011

As a web developer, I often find that once clients get used to the idea that they can edit their own site many are likely to think about cool design & interactive they have seen on other websites, and think to themselves “Can I do that in WordPress?”

The answer, of course, is “Of course,” but depending on the feature being requested that can involve some work. Perhaps on the part of the web developer to enable a function or add a javascript library to their WordPress header; but most certainly on the part of the site owner to learn how to employ that new feature. This can mean acquainting oneself with additional code snippets, or memorizing Shortcodes.

For people who work in code everyday, that seems like meeting the client easily half-way. But even WordPress shortcodes can seem cryptic to average users. Especially where there are multiple optional/required attributes, and especially where the client is an organization and you have no idea who will be asssigned to use the tool you’ve developed. I was recently asked why one needed to write out entire attribute for an optional true/false attribute whose default was false. Example:
[myshortcode] //foo = false
[myshortcode foo="true"] //foo =true

Obviously, part of me was thinking “Come on, it’s not that hard is it?” but I thought I would have a go at finding a workaround so they could merely write:
[myshortcode]// foo = false
[myshortcode foo] //foo =true

So let’s go through a practical example. (If you’ve never worked with shortcodes before,  I recommend you check out the docs on this feature, however you can begin by pasting a given code example in your theme’s function.php file.)

function myShortCodeFunction( $atts ){
 extract( shortcode_atts( array(
  'text' => 'Important Notice!',
 'width' => '500',
 'height' => '250',
 ), $atts ) );
 return "<div style='width:{$width}px; height:
{$height}px; background-color:aliceblue; border:3px solid SkyBlue;'>{$text}</div>";
}
add_shortcode('noticebox', 'myShortCodeFunction');

The code above will allow you to create a styled div element containing the text of your choice, and you may optionally set a width & height (default 500px × 250px), merely by typing [noticebox text="10 points from Gryffindor!"]

This looks pretty good, but what if on certain pages or in certain contexts the border didn’t look good? Well we can obviously adapt the myShortCodeFunction to accept:

[noticebox text="Some text." border="false"]

Which would look something like:

function myShortCodeFunction( $atts ){
 extract( shortcode_atts( array(
 'text' => 'Important Notice!',
 'border' => 'true',
 'width' => '500',
 'height' => '250',
 ), $atts ) );
 if($border == 'true'){
 $borderstyle = '
border:3px solid SkyBlue;';
 } else {
 $borderstyle = '';
 }
 return "<div style='width:{$width}px; height:{$height}px; background-color:aliceblue; {$borderstyle}'>{$text}</div>";
}
add_shortcode('noticebox', 'myShortCodeFunction');

In the version above, if the attribute border="false" is NOT detected  then the variable $borderstyle is assigned some inline CSS; otherwise it becomes an empty string, which when included in the returned string does nothing.

However if we wanted to simplify the shortcode from:
[noticebox text="Some text." border="false"] // no border
[noticebox text="Some text." noborder] // no border

We could modify the code in this way:

function myShortCodeFunction( $atts ){
 extract( shortcode_atts( array(
 'text' => 'Important Notice!',
 'width' => '500',
 'height' => '250',
 'noborder' => isset($atts['noborder']),
 ), $atts ) );
 if($noborder){
 $borderstyle = '';
 } else {
 $borderstyle = 'border:3px solid SkyBlue';
 }

 return "<div style='width:{$width}px; height:{$height}px; background-color:aliceblue; {$borderstyle}'>{$text}</div>";
}
add_shortcode('noticebox', 'myShortCodeFunction');

In this final version we assign the result of PHP’s isset() function (which returns true/false ) to the default value for $noborder, then reverse the logic used to assign the $borderstyle variable.

Neat, huh?

border="false"

Clearing Windows 7 Print Spool

June 1st, 2011

Windows 7 and my inkjet printer don’t always get along. When they start giving each other the silent “treatment”, I’m occasionally forced to restart my computer so I can print documents.

I cobbled this batch file together from various sources online. It works about half the time.

@echo off
echo Stopping print spooler.
echo.
net stop spooler
echo Erasing Temporary Junk Printer Documents
echo.
del /Q /F /S %systemroot%\System32\Spool\Printers\*.*
echo Starting print spooler.
echo.
net start spooler

If you’ve never made a batch file, copy the code above into a plain text editor and save the file to your Windows folder with the extension .bat

To use, call the file from the Run… command in the Windows menu.

Server-logging client-side javascript errors

May 25th, 2011

There are several examples of this already on the net, but this technique came in handy on a recent site I programmed. The concept is that you overwrite any existing browser reaction to the window.onerror event with your own function that sends an XMLHttpRequest containing gathered error information to a server-side script which logs that information to a file or database.

The user-experience as defined by the designer & client called for virtually every page to have a “dashboard” feel, whereby a site visitor could click buttons & links and the main content area of the page would be replaced (typically via innerHTML.)

Cross-browser debugging nearly became a serious issue; it was like a wild shoot-out in a digital saloon, with AJAX bullets flying through HTML-tag-cowboy hats and ricocheting off the piano player’s include files.

I got pretty much everything straightened out, but we still had the rare non-responsive button or empty content screen. So as we opened the site to a private beta, the following bit of PHP helped the browsers with issues call attention to themselves.

echo "<script>
window.onerror = function(msg, err_url, line){
 var params = 'jserror=1&msg=' +msg+ '&url=' +err_url+ '&line=' +line+ '&ua={$_SERVER['HTTP_USER_AGENT']}';
 whateverAjaxCallYouUse('action.php?'+params);
</script>";

With the increasing reliability of document.activeElement you could conceivably get more detailed information about the page element which caused the problem, however in my case I was only interested in the error messages themselves. In the untested example below, I create a string of JSON text from the activeElement‘s attributes.

var curr = (document.activeElement) ? document.activeElement : false;
if(curr){
 var json_string = '{' +
  ' "element" : "' + curr +
  ' ","tagname" : "' + curr.tagName +
  ' ","name" : "' + curr.name +
  ' ","id" : "' + curr.id +
  ' ","parent" : "' + curr.parentNode +
  ' ","href" : "' + curr.href +
  ' ","src" : "' + curr.src +
  ' ","onclick" : "' + curr.onclick +
  ' ","onfocus" : "' + curr.onfocus +
  ' ","onblur" : "' + curr.onblur + '"}';
}

Or something to that effect, there’s probably a smarter way to do it.

Obviously, this suppresses any normal error reporting in the browser so you’ll want a way to deactivate this behavior for when you’re debugging as you won’t see any errors yourself. In my case, since the site was decently MVC’d it was easy to not echo this function based on whether the appropriate administrator variables were set in the $_SESSION array.

Javascript: Abbreviated DOM methods

May 18th, 2011

<rant>As a foolishly ardent DIY-er AND a programmer I often try to avoid using third-party libraries, as if my “real programmer” credibility depended on complete self-reliance.

This is especially a nuisance when crafting modern interactive websites, as it’s becoming increasingly difficult to avoid libraries such as jQuery.

For me, though, it’s not about some idealist notion of authorship but rather it boils down to my need to understand the code I’m deploying. If I am not getting an expected result, and am including some third-party library, it can be hard to tell where the train went off the rails (sorry, sometimes I don’t have time for breakpoints & stack traces when I’m trying to push attractive & valid code to the browser from what is often the meat & potatoes of a site project: the back-end code in a template system or CMS.

Well this year I finally got around to de-obfuscating the jQuery library and began picking apart how it works.
This is a really important step in deciding to seriously use a tool that I recommend to every practitioner of every craft. Don’t get me wrong, jQuery has some fabulous docs, but mentally understanding the “Why” behind the way things is just as liberating as a complete list of functions & methods.

One way to look at a powerful Javascript library such as jQuery is to canonize it mentally into js, and erase the difference in your mind. That probably works for some people; I don’t think I can do that. There are times where I can imagine not needing the extra baggage of the whole of it for one or two functions.</rant>

Point in case:

On a site which wasn’t already using jQuery, I had need of some considerable DOM manipulations; creating & removing elements, applying additional style, and modifying hrefs. All of which are provided simply by javascript, except that the names of the methods are so freaking long! Come on, you know what I mean. Even IF you’re development environment has an auto-completion feature (I use Notepad++, and the shortcut is CTRL+ENTER, but it’s slower to look through the list and down-arrow to the desired item than it is to just keep typing) document.getElementById(‘…’) is just too damn long.

You gotta admit, there’s something sexy about $(‘#…’). C`est la vie, right?

So here’s what I did, it worked for me, your mileage may vary. Essentially, as a preamble to all the rest of the code, we abbreviate those long names by assigning an anonymous function to a given variable name, like so:

$ID = function(f){return document.getElementById(f);};
$NAME = function(f){return document.getElementsByTagName(f);};

Then, merely use them like this:
var e = $ID('some-element');
alert(e.innerHTML);

Of course, when you really need to boogie, you’ll need access to elements’ class attributes, so:

$CLASS = function(clsName){
 var classy = new Array();
 var pool = document.getElementsByTagName("*");
 for(var i = 0;i < pool.length;i++){
  if(pool[i].className.indexOf(" ") >= 0){
   var classes = pool[i].className.split(" ");
    for(var j = 0;j < classes.length;j++){
    if(classes[j] == clsName){
     classy.push(pool[i]);
    }
   }
  } else if(pool[i].className == clsName){
   classy.push(pool[i]);
  }
 }
 return classy;
}

A Northwest Horizon

January 1st, 2011

Cameraphone picture, cropped.

That’s how he rolls

December 2nd, 2010

I have no idea why a roll of toilet paper would be so sad, but it’s still cute.

Miniature Japanese Lantern

October 26th, 2010

A few years ago I purchased a roll of authentic Japanese rice paper from Uwajimaya market in Seattle intending to use it on a number of projects but I only recently started using it.

A combination of balsa & basswood is used in the model. I designed it to stand off the floor the same height as a typical electronic flickering tea light. This is a floor lantern in the Japanese style that is 40 scale inches tall at 1½” scale. I used a variety of images on the internet as inspiration/reference material. While I was researching designs I realized how similar the visual styles of Japanese Carpentry are to that of the Arts & Crafts Movement.

Hmm..

Roof-top Garden Grove

October 8th, 2010

Click for full-size.

Here’s an old architectural concept illustration from sometime in 2008. A sort of portico of brick archways suspends a living roof accessible from the second story of the main building to which both are attached. Small fruit-bearing trees could be made to take root making a pleasant garden roof-top.

I hope you like it. Marker & ink.

Tree in Wright Park

September 11th, 2010

It’s a real treat living close to a real park and arboretum:

Click for larger size.


View Wright Park in a larger map

Here’s an (unedited) picture I took today, which I find makes a great computer desktop image – have at it.

Click for full-size.