Generate UUIDs in PHP

I’m working on a project currently where I am using UUIDs as unique identifiers. PHP doesn’t have a good UUID function for this, so I wrote one that let me generate one.

<?php
function generate_uuid() {
	return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
		mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
		mt_rand( 0, 0xffff ),
		mt_rand( 0, 0x0fff ) | 0x4000,
		mt_rand( 0, 0x3fff ) | 0x8000,
		mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
	);
}
?>

For anyone who doesn’t know, a UUID, or a Universally Unique Identifier is an identifier standard used in software construction, standardized by the Open Software Foundation (OSF) as part of the Distributed Computing Environment (DCE).

UUIDs are meant to enable distributed systems to uniquely identify information without significant central coordination. In this context the word unique should be taken to mean “practically unique” rather than “guaranteed unique”. Since the identifiers have a finite size, it is possible for two differing items to share the same identifier. The identifier size and generation process need to be selected so as to make this sufficiently improbable in practice. Anyone can create a UUID and use it to identify something with reasonable confidence that the same identifier will never be unintentionally created by anyone to identify something else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve identifier (ID) conflicts.

A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens). For example:

a8d5c97d-9978-4b0b-9947-7a95dcb31d0f

There are several versions of UUIDs, in this case the function uses version 4, which is the random UUID generation. This is generally defined as follows

Version 4 UUIDs use a scheme relying only on random numbers. This algorithm sets the version number as well as two reserved bits. All other bits are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479).

What can I do with a Raspberry Pi?

So you just got a new Raspberry Pi, maybe it was a christmas present.. Or maybe you decided to buy one for yourself and now you want to know what you can do with this little computer?

There’s a lot you can do with it, you can use it for home automation, a file server, a web server, a media streamer running XMBC, a retro gaming console or just a tiny desktop device.

I’ll get into more detail on some of what you can do in a later post (or a couple), but for now, this post is meant to give you ideas.

First, I definitely recommend having the model with 512 megabytes of RAM, as the more memory you have, the better performance you get.

One thing I like about Raspberry Pi is that the hard drive is an SD card, so essentially, you can have multiple computers on one device, so you could have a card with raspbian on it, another card for raspbmc (the XMBC system), etc.

In terms of cases, I’ve used several cases from a case built with a simply project box, to a case built with LEGO, but my favorite is the blue Raspberry Pi SAFE case from solarbotics which also can be purchased with a mount to attach to the back of a TV.

Now, some uses for the Pi:

  1. There’s a nice getting started post over at Engadget for getting your Pi up and running
  2. Retro Gaming Console:Engadget also has a nice starting point for setting up a retro gaming rig using your Raspberry Pi and some emulators
  3. Media Streaming: Raspbmc or OpenElec both work nicely for XMBC / media streaming, and can plug into any TV. Most TVs also have USB ports which can power the little computer as well. I’ve personally been preferring Raspbmc lately as it seems faster and more stable.
  4. Install the Chromium browser for better web browsing: Since your Raspberry Pi is already hooked up to your TV, why not enjoy some big screen surfing? You’ll need a better browser than Midori for this though, so try Chromium. Just drop into a Terminal and type: sudo apt-get install chromium-browser then hit Enter.
  5. Write Games: Scratch is a programming language that’s easy to get to grips with and easy to use, which makes it good for children to start learning with and for creating rich programming projects. Check out this tutorial, featuring a bonus cat.
  6. Run Firefox OS: Although still in the developmental stages, Oleg Romashin an engineer at Nokia, has managed to get Firefox OS running on the Raspberry Pi. FFOS isn’t out until next year, but check out what’s been achieved so far.
  7. BitTorrent Server: If you frequent the various Torrent sites, then why not create a dedicated lean Torrent machine? Just hook it up to your router and leave it to do its business. Full instructions, scripts and downloads come courtesy of the snapdragon:IT blog.
  8. Pi-powered Cloud Server:  Fancy building your very own cloud server? By using OwnCloud you can. Follow the instructions, and the customised script from petRockBlog and you’ll become your own cloud provider in no time.
  9. Home Automation: There’s a new product called PiFace that’s perfect for home automation. It hooks up to the RPi and allows it to detect switch states from a door sensor, a pressure pad or any number of other switch types.
  10. Raspberry Pi Cluster: Many Pi’s make light work. Check out these instructions from the University of Southampton to make a RPi Supercomputer.
  11. Make a wearable computer:  Interesting article on building a wearable Raspberry Pi, with the display on a pair of glasses and a keyboard on his arm.

As you can see, there’s a lot you can do with your Raspberry Pi, I’m just giving some examples to get started. I’ll post some more on here later as I get more ideas for the Raspberry Pi, but the 10 or s0 examples above should be enough to get your started.

Useful Pythonista Links

Pythonista is a great app for iOS that lets you get things done, and there are a lot of useful snippets out there that help make it more useful.

This post is to bring together some of those links, and I will probably update it as I add more. I’ll also tell you why they are useful..

To start, one of the most useful resources is the Pythonista forum, where other users share code for everybody to use. So check it out.

First, to make adding these snippets easier, let’s add some code to download any gist links and create a new script:

  1. Copy the code at this url: “https://gist.github.com/b0644f5ed1d94bd32805” and save it as a new script.
  2. Then go to Settings > Actions Menu and select to add the script to your actions.

Now you can copy the gist URL into your browser and then when you open up pythonista and choose “import from gist” from your actions menu, it will add the snippet as a new script.. Handy.. Very handy..

Now, let’s look at DropBox Integration.. This is handy as you can keep all your files in DropBox and sync between devices..

  1. To start, let’s add the ability to login to DropBox
  2. Once you add this script, you will have to set up an app at http://dropbox.com/developers/apps and make sure it is limited to one folder, rather than all of DropBox.

Now, let’s add the DropBox sync app

This script, when run, will sync your local copy with the copy on DropBox, and update whichever one has recent changes.

I use this to go between my iPad, iPad mini and iPhone and it works well.

I also find this script useful to it as a web server, and download files from your browser. Also, easily customized..

The author of Pythonista also posted this handy Drum Machine script that my daughter loves to play with.

I find The Down For Everyone Or Just Me script really handy when you need to check a web site.

Also, this handy script for installing short cuts via webclips is a little tricky to start out, but works well..

You can also use this script to convert any image in your clipboard into a base64 string.

Also, if you want to email images, then use this script (also good example of using email from inside pythonista).

And finally, I use this script and bookmarklet to send to pinboard for book marking.

Pythonista is growing, and as it grows, so do the useful scripts that are available.. So play with the links above, and also make sure to read the forums on a regular basis so you can get more useful scripts.

An Ajax-Include Pattern for Modular Content

Clever and useful pattern for bringing in non-essential content to a page after its iniital load. I do a good bit of this myself (although not with this particular technique).

The intesting thing to me when this is discussed in regard to mobile, as it is here, is that the “loading…” aspect of web sites and apps is one of the thing that make people like native apps so much better.

They always feel so much faster because once a view appears on screen, it’s all the—theres nothing more to load. Tradeoffs…

Using Dropbox as a Git repository

I use github heavily, but I have a couple projects that I like to work on across multiple machines, but don’t necessarily want to share them on github, and I already use private repositories…

I decided to use Dropbox as a git server to work with multiple machines as it gives you that extra version control in that you have git and Dropbox’s built-in control.

It turns out it is actually pretty easy to set it all up so here are the quick steps for anyone who is interested (these are only applicable to Macs).

This is actually a great way to work collaboratively and remotely with other developers, or simply keep project files in sync between two different computers. In my case when working from home I’m usually on the Mac Mini and on the road with the Macbook Air so this works really well and allows me to work on the same project from different computers without the hassle of remembering to copy files across etc

  1. Firstly make sure you have the Dropbox app and Git installed on your Mac. If not, you can get Dropbox from here (direct download link) and the latest version of Git from here.
  2. With Dropbox and Git installed, you need to create a bare repository which will be shared with your Dropbox account. Open a Terminal window in your Mac and do the following:
$ cd ~/Dropbox
$ mkdir -p repos/your-repo-name
$ git init --bare repos/your-repo-name
Initialized empty Git repository in /Users/xxxxxx/Dropbox/repos/your-repo-name/
  1. Now with our bare repository created, head to your project folder and let’s start a local git repo and link it with the Dropbox one. If you already have a local repo, skip to step 4:
$ cd ~/ProjectFolder
$ git init .
Initialized empty Git repository in /Users/xxxxx/ProjectFolder/
$ git add .
$ git commit --all -m "Initial commit"
$ git remote add dropbox /Users/xxxxx/Dropbox/repos/your-repo-name/
$ git push dropbox master

Essentially what we’ve done here was initialise a local repo, add and commit all files within that folder to the local repo. We then add a new remote location using the handle “dropbox” to this repo and finally push all the local changes to the “remote” repo (i.e. your Dropbox repo folder).

The rest is done automatically by Dropbox – your folder will be synced with your account and accessible from anywhere. For instance, if you wanted to clone the repo to a different machine, all you need to do is make sure Dropbox is installed and the folders are synced – and then issue the following command:

$ cd ~/Projects
$ git clone -o dropbox /Users/xxxxx/Dropbox/repos/your-repo-name/

If everything goes right, you should have a local copy of your remote repo already configured with your dropbox remote. You can start making changes to your project and when ready, push them back to the remote:

$ git commit --all -m "Changes made!"
$ git push dropbox master

And finally, when you want to sync the remote repository with your local copy, you can:

$ git pull dropbox master

You can also use github for mac as your git client, despite the name, it’s not just for github projects.

Using the x-requested-with header to include content on demand

I like using the same PHP script for both AJAX and non-AJAX content requests. Using one script just makes everything easier because it’s only one file to update/edit and it’s one more cache-able request.

One way to try to detect an AJAX request (as opposed to a regular page load) is by using the x-requested-with header when building ajax powered apps..

PHP Code

<?php if($_SERVER['HTTP_X_REQUESTED_WITH']==''){
    include('header.php');
}?>
<blockquote cite="http://ia341030.us.archive.org/1/items/alicesadventures19002gut/19002-h/19002-h.htm">
    <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do: once or twice she had peeped
    into the book her sister was reading, but it had no pictures or
    conversations in it, and where is the use of a book, thought Alice,
    without pictures or conversations? So she was considering in her own mind,
    (as well as she could, for the hot day made her feel very sleepy and
    stupid,) whether the pleasure of making a daisy-chain was worth the
    trouble of getting up and picking the daisies, when a white rabbit with
    pink eyes ran close by her.</p>
</blockquote>
<?php if($_SERVER['HTTP_X_REQUESTED_WITH']==''){
    include('footer.php');
}?>

jQuery Code

$(document).ready(function(){
    $('.ajaxtrigger').click(function(){
        var url = $(this).attr('href');
        $('#target').load(url);
        return false;
    });
});