Get weather info using PHP and Yahoo
Some time ago, I searched for a quick and simple way of getting a weather info for any place and putting it onto webpage. There is a lot of commercial services, which give you great data, but I wanted a completely free solution. After a lot of trying and testing, I decided to use Yahoo services for that -
using Yahoo Weather API, it's very easy to get detailed weather data for almost every place on Earth.
To get the weather data, first we need a WOEID identificator for the place we need the data for. To get it, we can use YQL to query the Yahoo's "geo.places":
Example:
$address = "Brooklyn, New York, USA"; $f = file_get_contents("http://query.yahooapis.com/v1/public/yql?q=".urlencode('select * from geo.places where text="'.$address.'"')."&format=xml"); preg_match("~<woeid>([0-9]+)<\/woeid>~i", $f, $r); $woeid = intval($r[1]);
Now we have $woeid for address "Brooklyn, New York, USA". To get the weather data, we use it like this:
$f = file_get_contents("http://weather.yahooapis.com/forecastrss?w=".$woeid); preg_match("~<description><!\[CDATA\[(.*?)\]\]><\/description>~is", $f, $r); $weather = trim($r[1]); echo $weather;
The weather data is pre-formatted with illustrative weather icon etc., but it's sufficient for most needs.
Demo
See the demo here.
Source code
See the source code here.
GPS EXIF data on Google Map
Modern cameras allow you to store current GPS coordinates along with the taken photo. We can use these coordinates to show the place of taking the photo on Google Maps.
Getting GPS coordinates from DATA data
The stored GPS coordinates are in a special format, which we need to convert to numerical values used by Google Maps. The complete function to do this follows:
function GetGPS($photo) { $exif=exif_read_data($photo, 0, true); if(!$exif || $exif['GPS']['GPSLatitude'] == '') { return false; } else { $lat_ref = $exif['GPS']['GPSLatitudeRef']; $lat = $exif['GPS']['GPSLatitude']; list($num, $dec) = explode('/', $lat[0]); $lat_s = $num / $dec; list($num, $dec) = explode('/', $lat[1]); $lat_m = $num / $dec; list($num, $dec) = explode('/', $lat[2]); $lat_v = $num / $dec; $lon_ref = $exif['GPS']['GPSLongitudeRef']; $lon = $exif['GPS']['GPSLongitude']; list($num, $dec) = explode('/', $lon[0]); $lon_s = $num / $dec; list($num, $dec) = explode('/', $lon[1]); $lon_m = $num / $dec; list($num, $dec) = explode('/', $lon[2]); $lon_v = $num / $dec; $gps_int = array($lat_s + $lat_m / 60.0 + $lat_v / 3600.0, $lon_s + $lon_m / 60.0 + $lon_v / 3600.0); return $gps_int; } }
This function returns an array of two elements - latitude and longitude.
Google Maps
To use Google Maps on your site, you need a Google Maps API, which you can get here.
Then, you need to include this line to your source code (remember to replace YOUR_API_KEY with the key you got):
<script type="text/javascript" src="http://www.google.com/jsapi?key=<YOUR_API_KEY>"></script>
Demo
In this example, you can upload a photo. Then, the uploaded photo is shown on Google Map using EXIF GPS coordinates.
Dynamic PHP watermarking with ImageMagick
In one of our previous articles, we covered a very basic technique to add watermark to image using PHP and GD. This technique will add a transparent watermark to target image - disadvantage being that the watermark is a part of the final image "for good". That means, if you need to change the watermark on already watermarked images, you will need the original images to re-watermark them, and that means more disk space used and generally more data to handle.
In this article, we will show how to make a flexible watermarking routine which enables to change the watermark anytime without the need to store both the original and watermarked images (although the watermarked images ARE in fact stored on disk, but only for caching). The watermarking itself will be done using ImageMagick, but it can be done using basic GD too (but that is not covered in this article).
Let's have a folder with the source images "source_images". Then, we have the watermark image, "watermark.png" and the folder to store the watermarked images, "output_images". The routine looks like this:
$photo = $_GET['photo']; $src = 'source_images/'.$photo; $dst = 'output_images/'.$photo; $watermark_image = 'watermark.png'; $create_watermark = false; if(file_exists($dst)) { $t_img = filemtime($dst); $t_wm = filemtime($watermark_image); if($t_wm > $t_img) $create_watermark = true; } if(!file_exists($dst) || $create_watermark) { $cmd = "composite -dissolve 50% -gravity south-east ".$watermark_image." ".$src." ".$dst; exec($cmd); } header("Content-type: image/jpeg"); $f = file_get_contents($dst); echo $f;
Note that this code does not cover security issues - in a production environment, you will have to sanitize the $_GET['photo'] variable in order to disallow access to other folders:
$photo = $_GET['photo']; // Just a very simple and basic protection... $photo = str_replace('..', '', $photo); $photo = str_replace('/', '', $photo); $photo = str_replace('\\', '', $photo);
The routine creates an image with the watermark when needed. The watermark will be placed in the bottom - right corner (the parameter -gravity south-east in the ImageMagick command line), but you can place it anywhere (see documentation). If the image already exists, it is used without needing to re-create the watermark again. But, if the watermark image itself is updated, all images will be updated too when needed.
The routine is to be called like this (let's pretend we saved the source as watermark.php):
<img src="watermark.php?photo=my_image.jpg" />jQuery Select Box Replacement
NOTE: Updated version in progress. Fixed many things and adds many new features. Check back soon.
Why replace SELECT box?
The standard browser- or OS-rendered SELECT box does not provide many possibilities of styling. Being rendered differently in various browsers, it's usually a waste of time trying to add much styling to it and hoping it would look the same everywhere. So, when we need a fully customizable SELECT box with almost endless options of styling, we need to replace it with something with similar behaviour.
The SBR plugin
The Select Box Replacement (SBR) plugin creates a set of HTML elements to replace the original SELECT box.
You can add various CSS styles to them to make them look exactly as you need.
What does it do?
A picture is worth a thousand words...

Demo
Download
Sorry, no download available yet. But, you can extract the in-progress code from the Demo source code.
jQuery Tooltip plugin
A very simple jQuery ToolTip plugin. Basically, when user hovers mouse pointer over an element, it shows a "bubble" with information. This is the way the default system tooltip work too, but there is a delay before they are shown (usually about a second or so) and that is not ideal - the user doesn't know he needs to stay over the element for a whole second before the tootip appears, etc.
The source code is really simple:
function ToolTip(el, id) { $(el).css('cursor','pointer'); $('body').append('<div class="toolTip" id="tooltip_' + id + '">' + $(el).attr('title') + '</div>'); $(el).mousemove(function(e){ $("#tooltip_"+id).css('display','block'); $("#tooltip_"+id).css('left', (e.pageX + 0) + 'px'); $("#tooltip_"+id).css('top', (e.pageY + 21) + 'px'); e.preventDefault(); e.stopPropagation(); }).mouseout(function(){ $("#tooltip_"+id).css('display','none'); }); } (function($) { $.fn.toolTip = function(settings) { var config = {}; if (settings) $.extend(config, settings); var id = 0; this.each(function() { var ttip = new ToolTip($(this), id++); }); return this; }; })(jQuery);
It basically created a dynamic DIV with absolute position to desired coordinates. The content of the DIV is the TITLE tag of the source element. Then, a class is added to enable CSS styling (it is possible to put in-line css style to the DIV directly, but that is not very flexible).
.toolTip { position:absolute; display:none; padding:6px 12px; background:#ccc; border:1px solid #888; color:#222; }
We then easily apply the plugin to desired elements:
<div id="hovery-test"> <img src="pic1.jpg" width="100" height="100" alt="Obrázek" title="This is the first picture" /> <img src="pic2.jpg" width="100" height="100" alt="Obrázek" title="This is the second picture" /> <img src="pic3.jpg" width="100" height="100" alt="Obrázek" title="This is the third picture" /> </div>
$(document).ready(function(){ $("#hovery-test img").toopTip(); });
jQuery plugins
jQuery is a lightweight JavaScript library, which aims to ease programming in this language (and you bet it does!). You can find out more about jQuery on its homepage, but I would like to focus on something else - jQuery plugin development. It's the plugins that make jQuery such a powerful tool with big possibilities of adding effectiveness, interactivity and a better user experience overall to your on-line projects and webpages.
There is a plenty of jQuery plugins to choose from. With a solid chance of success, you could find a plugin for every need and every situation you would come upon while developing your on-line prodigy. But despite that, sooner or later you will come to point, where you just need to develop your own plugin, because:
- the plugin that solves your problem does not (yet) exist
- maybe the plugin does exist, but you have no luck finding it (or you don't know how to phrase it specificaly for the search engine)
- the plugin does not meet the requirements
- the plugin solves another 518 problems, has 500KB in size and is slooow
So, instead of a long searching, customizing to your own needs and/or reading the documentation, it could be better to just write your own plugin (this is valid for smaller and/or simpler plugins mainly, there is no need to reinvent the wheel, of course).
Structure of a simple jQuery plugin
When it comes to jQuery plugin development, I consider myself still a slightly advanced rookie. Therefore, the following code is just my personal view of a plugin structure (you are more than welcome to criticize me in comments
).
function TestPlugin(el) { // We are working with element "el" here - for example, add a red border to it.. $(el).css('border', '1px solid red'); } (function($) { $.fn.testPlugin= function(settings) { var config = {}; if (settings) $.extend(config, settings); this.each(function() { var plug = new TestPlugin($(this)); }); return this; }; })(jQuery);
This is just a basic useless example - all it does is that it adds a red border to selected elements. And how do we select them?
$(document).ready(function(){ $("p").testPlugin(); });
First, we wait until the document is fully loaded (with help of .ready method applied to the document), and then we apply our plugin to all "p" elements (ie. paragraphs). The result is, that every paragraph on page will have a red border. Of course, we can just select anything instead of P tags:
$(".redBorder").testPlugin(); // adds red border to all elements with "redBorder" class $("li:even").testPlugin(); // adds red border to all even list elements $("img").testPlugin(); // adds red border to all images on page
The goal of these examples is of course not to add red border to elements, but rather show a simple structure of plugin, which can operate with more elements individually (which is important when you need to work with events independently etc.)
jQuery is fun!
jQuery iBox plugin
iBox plugin was written to satisfy eventual more complicated needs, when for example thickbox fails to work (combination with other plugins or scripts, custom CSS positioning, etc.). It is a lightweight image displaying plugin with basic functions like grouping images to gallery sections (via "rel" attribute", see below), arrow keys (and Esc key) controls.
You can define many properties and attributes like maximum displayed picture's resolution, speed of (re)appearing and transition effects, etc.
Currently supported features:
$('.ibox').iBox({ speed: 500, // appear/transition animation speed (ms) keys: true, // keyboard control? (arrows, escape) borderWidth: 10, // box border width (px) borderColor: "#fff", // box border color boxBg: "#000", // box background appearSpeed: 250, // picture fadeIn speed (ms) maxWidth: 800, // maximum width of displayed image (px) maxHeight: 600, // maximum height of displayed image (px) controlsBg: "#fff", // controls bar background controlsHeight: 60, // controls bar height (px) nextText: "next", // "next image" link text prevText: "prev", // "previous image" link text closeText: "close", // "close" link text });
Planned features:
- animated resizing transitions - easing effects available
- slideshow - variable delay, variable transition effects
- zoomed picture with a click'n'drag map - excellent for displaying very large images
- thumbnails filmstrip navigation - switching to specified picture without closing the iBox
Files list & installation:
- css/ibox.css
- js/jquery.ibox.js
Requirements & initialization:
- Apply a specific class (iBox in this example) to A elements containing images.
- Include a jQuery library
- Below this line, add a <script type="text/javascript"> and paste the following code:
$(function(){ $('.ibox').iBox(); });
This will initialize the plugin with default settings that you can find in the .js file. In case you want to slow down the image appearing speed, try this:
$('.ibox').iBox({ speed:500 });
Known issues
Support for Internet Explorer 6 is only basic. If you encounter any problems with this plugin, upgrade to a normal browser
Demo
Download
PHP Image Watermarking
This is a very simple technique we are using to watermark images when needed. Some time ago, we built a project which involved a lot of high-quality photos and we didn't want them to get stolen by anyone. The watermarking must meet the following criteria:
- the watermark image must be large enough and placed well to make the retouch of photos very difficult, if not impossible
- the watermark must consist of various colors to make the retouch even more difficult
- the watermark must be soft and transparent enough not to ruin the viewing experience
Based on point 1, we decided that the watermark must be in the center of the image, and large enough to make the cropping (and using only portions of the image without the watermark) difficult.
Point 2 can be solved by “bevelling” the watermark to add shadows and highlights. This way, we get many shades of gray and such watermark will be much harder to retouch or remove from the picture.
Point 3 just means that we need to find a good balance between visibility (alpha) of the watermark and the softness of it's colors and edges not to ruin the viewing experience.
The code
We use simple GD functions to draw the watermark. For the watermark itself, we use a transparent PNG image. To paint the watermark into the output image, we use imageline() function to draw a single-pixel line to the centre of the image.
<?php $source = “source.jpg”; $watermark = “watermark.png”; $output = “output.jpg”; $pic = imagecreatefromjpeg($source); $wm = imagecreatefrompng($watermark); imagesetbrush($pic, $wm); $siz = getimagesize($source); $xp = $siz[0] / 2 ; $yp = $siz[1] / 2 ; imageline($pic, $xp, $yp, $xp, $yp, IMG_COLOR_BRUSHED ); imagejpeg($output, 90); imagedestroy($wm); imagedestroy($pic); ?>
Download
Intelligent image cropping
Some web applications need to have an automatic thumbnail generation system, which makes nice thumbnails of bigger pictures uploaded by its visitors, registered users or whomever else. Most of the time a simple aspect-ratio-keeping resizing is enough:

Simple and nice. But this is of course an ideal case - basically square picture resized to square thumbnail. That won't be the case every time. Most of the time, the source images would be too wide or too tall to fit nicely into the desired thumbnail size:

Doesn't look too good, does it?. Especially when thumbnails of various wide or tall photos are next to each other, out of whack:

Intelligent image cropping
One of the solutions to this problem, which we use a lot, is what we call „intelligent image cropping“. The idea is based on two simple rules:
- the thumbnail should always be fully filled with the image, no empty borders
- the image must be resized with aspect-ratio preserved
Because of these two rules, it is clear that most of the time, the source image will have to be cropped to some extent. And why not? The purpose of thumbnails is not to show the whole image, but to give the visitor a rough idea, what the big picture is about.
The code
Here is the whole thing:
static function cropTo($pic, $dest, $dw, $dh) { $siz = getimagesize($pic); if($siz[0] >= $siz[1]) { $fact = $dh / $siz[1]; } else { $fact = $dw / $siz[0]; } $new_w = $siz[0] * $fact; $new_h = $siz[1] * $fact; switch ($siz[2]) { case 1: $src_img = imagecreatefromgif($pic); break; case 2: $src_img = imagecreatefromjpeg($pic); break; case 3: $src_img = imagecreatefrompng($pic); break; default: return false; } if (!$src_img) return false; $xp = $dw/2 - $siz[0]/2; $yp = $dh/2 - $siz[1]/2; $tmp_img = imagecreatetruecolor($new_w, $new_h); $dst_img = imagecreatetruecolor($dw, $dh); $xp = $new_w/2 - $dw/2; $yp = $new_h/2 - $dh/2; imagecopyresampled($tmp_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, $siz[0], $siz[1]); imagecopyresampled($dst_img, $tmp_img, 0, 0, $xp, $yp, $dw, $dh, $dw, $dh); imagejpeg($dst_img, $dest, 99); imagedestroy($dst_img); imagedestroy($tmp_img); imagedestroy($src_img); }
No need for long explanations here - just a set of basic PHP functions along with some calculations. Use the function and see for yourself
Caching
It's obvious that this function can be quite resource-demanding, especially when generating large numbers of thumbnails. Re-using already generated thumbnails would be a nice idea. We just add a couple of lines to the source code:
static function cropTo($pic, $dest, $dw, $dh) { // new code - caching: if(file_exists($dest)) { $ti = filemtime($pic); $to = filemtime($dest); if($to > $ti) return; } // old code continues... $siz = getimagesize($pic); if($siz[0] >= $siz[1]) { ...
This code allows us to reuse already generated thumbnails when needed - or in other words it prevents the regeneration of already existing thumbnails. It compares the modification time of the source and destination files (destination file = the generated thumbnail) and only generates a new thumbnail when the source file is newer than the stored thumbnail.
Download
Minimal JSON + PHP example
JSON (JavaScript Object Notation) is a great way to interchange data (not only) between JavaScript and PHP. Why use JSON and not XML, for example? It's a lightweight format and it is a subset of JavaScript native code, which makes it easier to use and read. With the help of various JavaScript libraries which have built-in support for JSON (for example jQuery, which we will be using in this tutorial), it is a breeze to have the basic system working in minutes.
In this tutorial we will build a very simple search engine. It will search in U.S. state names (based on our search keyword), assemble the results to JSON object and send it to JavaScript. Then, we will use jQuery functions to output the result to the webpage. As a side-effect everything will take place without a single reloading of the page, thanks to AJAX.
Step 1: Prerequisites
We will be using jQuery in this tutorial, so go ahead and download the latest version. Alternatively, you can download this tutorial's source files archive, which has jQuery library already included.
Step 2: The data
For the purpose of this tutorial we will be using a simple database of USA state names. We will search in those names, send the results as JSON object to JavaScript and output them to the webpage.
Step 3: The webpage
Simple layout will be enough, with a search form, which allows us to enter a keyword. There is no need for the <form> tag, because our form will never be really submitted - when we submit the search, just one JavaScript function is called and the page does reload at all. Therefore we don't use the type=”submit” button, we will add just a generic type=”button” input with an onClick() handler attached.
<h1>JSON and PHP Example</h1> <p><input name="q" id="q" size="40" type="text"> <input onclick="javascript:doSearch();" value="Search in USA state names" type="button"></p> <div id="result"> <ul> </ul> </div>
The “result” DIV is a container with an unordered list, which waits to be filled with our search results.
Step 4: JavaScript function
Firstly, we need to include jQuery library:
<script type="text/javascript" src="jquery.js"></script>
Then, our function comes into place:
<script type="text/javascript"> function doSearch() { var q = $("#q").val(); $("#result ul li").remove(); $.getJSON("index.php?json=1&q="+q, // get JSON results function(data){ $.each(data, function(i, item) { // output results to list $("#result ul").append("<li>" + item + "</li>"); }); }); } </script>
This function is called by the fake submit-button mentioned earlier (the one with the onClick handler). Now, we get the searched keyword:
var q = $(“#q”).val();
This retrieves the content of the input box, which is our keyword. After this we need to ensure that the results list is empty, because we need to make a new list every time the function gets called:
$(“#result ul li”).remove();
This line removes all <li> items from the UL inside the <div id=”result”> div. Then, we use the helpful jQuery's getJSON function:
$.getJSON(“index.php?generateJSON=1&q=”+q ...
This calls our PHP script with generateJSON parameter set to 1 and our keyword attached as parameter “q” (these parameters are handled by PHP script - this will be mentioned later).
function(data){ $.each(data, function(i, item) { // output results to list $("#result ul").append("<li>" + item + "</li>"); }); });
The getJSON function returns JSON data sent by the index.php PHP script. We can iterate through the data by using the $.each function, which gives us one item at a time. In this tutorial, we are only using state names as the data item, so the “item” variable just holds a single string. In more complex cases the „item“ variable could be an Array and would be utilized accordingly.
$(“#results ul”).append(“<li>” + item + “</li>”);
This code injects item into the results list.
Step 5: PHP Code
require 'states.php'; if($_GET['json'] == 1) { $keyword = trim($_GET['q']); $results = array(); foreach($states as $state) { if(stristr($state, $keyword)) $results[] = $state; } echo json_encode($results); exit; }
First, we need our data we will be searching in. As mentioned earlier, we are using a simple list of U.S. state names.
require 'states.php';
The states.php file holds a PHP array of U.S. state names, nothing more:
$states = array( 'Alabama', 'Alaska', 'Arizona', 'Arkansas', ... );
Are we being called by JavaScript?
if($_GET['generateJSON'] == 1) { ... }
(We could use a special header etc., but for the sake of simplicity, let's just pass a parameter).
$keyword = trim($_GET['q']);
This gets the keyword passed to the PHP script by JavaScript and trims possible 'white' characters from beginning and end of keyword.
$results = array(); foreach($states as $state) { if(stristr($state, $keyword)) $results[] = $state; }
Let's iterate through the state names and remember the ones which contain our searched keyword. The stristr() function searches for keyword in a string, case insensitive.
echo json_encode($results); exit;
Using the json_encode function we generate the JSON object from a simple array. We need to stop the script using the „exit” command, because we already echoed the JSON data and we don't want to output the HTML code aswell.
Step 6: We're done!
That's it, we've made a very simple search engine with JSON data exchange. There are of course much better and complex examples and situations to use JSON, but purpose of this tutorial is to cover the bare basics of it all.
Have fun!