Saturday, July 16

HTML5 WebSocket Server in PHP

This is a video demo of my Javascript stock exchange simulator programmed in HTML5 and PHP. I'm running my websocket server using WAMP (Windows, Apache, MySQL, and PHP). Let me know if you have any questions or comments about any of this.

Get the source code today
If you're interested in playing around with this websocket server, you can download the source code for it at my official website.

Friday, July 15

How to run PHP sockets in WAMP

Lately I've been playing around with HTML5 Web Sockets. This has been pretty fun and educational. Especially since I've ran into a few problems, and very little documentation is available on it. After resisting the temptation of pulling my hair out (since I don't have a whole lot of it left, anyways), and focusing on finding answers to these problems, I was rewarded by a generous universe, who revealed me all the answers I needed. This post will cover 3 ways to help you solve the common error you may run into when attempting to create sockets in PHP using WAMP (Windows, Apache, MySQL, and PHP). This error message says Call to undefined function socket_create().

How to fix Call to undefined function socket_create()

If you're running WAMP, there are two basic ways to fix this. This error is caused by a simple WAMP/PHP configuration that you left out. What you want to do is pretty simple. Simply enable sockets in PHP. To do so, you must:
  • Click the WAMP icon
  • Select PHP
  • Select PHP Extensions
  • Enable the php_sockets extension

Now try restarting all services in your WAMP, and see if the sockets work now. This should solve the problem 9/10 times. However, there are some situations when you will do just what I described above, and your PHP sockets will still return that undefined function socket_create(), which will be frustrating. However, here are some other things that will fix this problem:

Set up your environment variables to run PHP from the command line

A few weeks ago I posted a tutorial on how to run Python from the command line, where I describe how to set up the environment variables in Python. The exact same process is used for PHP and WAMP, so you can use that as a reference. The steps are simple:
  • Click the WAMP icon
  • Select www directory
  • This will take you to the directory where WAMP is installed. Go up one directory level from the www folder, and select the bin directory. Inside bin you will see a PHP directory, inside of which there will be a PHP5.3.4 (whatever version of PHP you happen to have installed). Follow this directory path until you find the one that has a file named php.exe
  • Copy the complete path to this directory
  • In your environment variables window (follow the Python article on the specifics on how to get there), edit the PATH variable, and paste this path to your PHP.exe (the PHP interpreter) file that you copied in the previous step

Now you should be able to go do a DOS window and type in a command like:

php file.php

(assuming that you're in a directory that has a file named file.php, of course)

This will execute your script right in the command window. If you're trying to run a PHP socket server so clients can connect to it, you will need to run it from a terminal (command line), and this is how you set it up.

However, there are 2 more ways to solve the socket problem ("undefined function socket_create()"). They're both pretty similar, although the second one is less obvious.

Method #1: Edit your php.ini file

This basically accomplishes the exact same thing you did in the fist thing I suggested earlier in this PHP tutorial. What you need to do is:
  • Click the WAMP icon
  • Select PHP
  • Select php.ini
  • Search your php.ini file for the following line:


  • This line has a semi-column at the beginning, meaning that the sockets extension is disabled. To fix this, simply uncomment the statement, and save the php.ini file. To uncomment this line of code, simply delete the semi-column, changing the line to this:


Again, after restarting all WAMP services, try running your PHP script with the create_socket() function call, and things should work out just fine now.

Method #2: Edit the other php.ini file

Sometimes your WAMP will install weird, and the PHP will point to a different php.ini file than the one you can access through the WAMP icon. I'm not sure how this can happen, but without using the technique I'll show here, the problem with the sockets will never go away. I came across this problem when I installed WAMP in a virtual machine running Ubuntu (the virtual machine had Windows XP installed in it). To find out what php.ini your PHP is looking at, go to a command line and type in the following PHP command:

php --ini

This will list the information (file paths) about the configuration of your PHP that you need to edit. The second line of the output you get from this step shows where the true php.ini file is located. Go to that path and uncomment the line that points to the sockets.dll file as described in the previous step.

The output from the php --ini command will look something like this:

C:\Users\Rodrixar>php --ini
Configuration File (php.ini) Path: C:\Windoows
Loaded Configuration File: C:\wamp\bin\php\php5.3.4\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)

Notice how in this case the .ini file is located within my WAMP folder, which is why the other steps shown in this tutorial worked. But some times this location will be different from the WAMP install location, and by changing that php.ini file you will be able to truly enable and use those desired PHP sockets.

Saturday, July 9

HTML5 Canvas Animation Tutorial with Nintendo Battletoads

Lately I've been playing around with 2D animations in the canvas element. I know that 3D WebGL is the cool thing nowadays, but for now, I'd like to get pretty good with regular, 2 dimensional animations with the boring, old canvas. Below is a demo of what I've come up with so far. Use the right and left arrow on the key board to more Pimple around (actually, I'm not sure if that's Rash or Zits from the original Nintendo game Battletoads...

Sprite animation in the HTML5 canvas

While this is a tutorial, and you've probably come to this article in an attempt to learn how to animate your own canvas and make cool 2D games in HTML5 and Javascript that can be played on the browser, the main reason I'm posting this is because I'd like to learn more about canvas animation myself. Right now I'm just doing things in a way that makes sense to me, but most likely doesn't follow 2D tile-based sidescroller games best practices. So I guess we'll learn together...

To start out, here's the sprite image I'm animating in this HTML5 demo:

Battletoads sprite sheet

I just found this online, in case you wonder... But what I do is pretty simple, as described in this pseudo-code:

  1. Make an *array with the location of each animation frame
  2. Make a variable that keeps track of the current frame being printed from the sprite sheet
  3. Load the sprite sheet image
  4. Draw a portion of the sprite sheet into the canvas. This is where the array created in step 1 comes in
  5. Increment the frame variable using **modular math
  6. If before drawing the next frame (this should be step 4, but makes sense to explain it here), clear the part of the canvas context where the current sprite frame is drawn

* This is an array of objects, each with the (x,y) position of where each animation frame is located within the sprite sheet, plus a (w,h) pair representing the frame's width and height:

var spriteFrames = [
   {x: 0,  y: 0, w: 32, h: 30},
   {x: 33, y: 3, w: 42, h: 27},
   {x: 78, y: 5, w: 30, h: 33}

Something like that. Note that each frame can have its own dimensions. The image will still be drawn properly (lined up with the previous and next frames) this way, even if the frame is shorter or wider.

** By modular math I mean that you should increment the variable that keeps track of the current frame using the modulus operator. This way you don't have to worry about going out of bounds in your array, like such:

// a lot of people do this:
if( currentFrame > totalFrames - 1)
  currentFrame = 0;


// this is how you should increment your current frame index:
currentFrame = (currentFrame + 1) % totalFrames;

   WHAT? but why do that?
   well... follow the math. If you're not familiar the % (MOD) operator,
   it simply performs division, then returns the remainder, which is never
   greater than the number being divided by, which means you always stay
   within the array bounds.

   var totalFrames = 3;
   var currentFrame = 0;

   currentFrame = (currentFrame + 1) % totalFrames;
   -> currentFrame = (0 + 1) % 3 = 1 % 3 = 1

   currentFrame = (currentFrame + 1) % totalFrames;
   -> currentFrame = (1 + 1) % 3 = 2 % 3 = 2

   currentFrame = (currentFrame + 1) % totalFrames;
   -> currentFrame = (2 + 1) % 3 = 3 % 3 = 0

   currentFrame = (currentFrame + 1) % totalFrames;
   -> currentFrame = (0 + 1) % 3 = 1 % 3 = 1

Clearly, incrementing the frame pointer with one operation is better in most cases, but I'm sure there might be cases where something more verbose might be needed, but for the most part, using the MOD operator will save you time and space.

Other than that, I think I need to research this some more and practice what I learn. As you can see in the demo, the animation only works one way. That is because the original image (the sprite sheet) is drawn like that. There is a simple way to flip the image resource being drawn onto the canvas, but that sort of sounds like it takes a more computations than needed. I'm thinking just having a second sprite sheet with the images mirrored should do the trick. It'll take more space in memory, but once loaded, the animation can run without costing CPU power forever.

Also, my animation doesn't quite seem very smooth. This is not because of the strategy used to animate the canvas, but because the sprite sheet is probably not right. One thing I do have in this demo is that every so many milliseconds the timer is fired, the frame pointer is updated, the (x,y) coordinates of the Nintendo character is updated, and the image is redrawn. However, the animation only takes place if at least so many milliseconds have elapsed since the previous animation frame was updated:

// function drawCharacter() { canvasContext.drawCharacter( frame, x, y ); }

// our main Player object has an attribute frameUpdated, 
// which is the time it was last updated (in milliseconds)
function updateAnimationFrame()
  if( - Player.frameUpdated > 70 )
    Player.currentFrame = (Player.currentFrame + 1) % Player.totalFrames;

    // update time frame was animated
    Player.frameUpdated =;

Anyway, post your questions, comments, and suggestions.

Thanks, and enjoy!

Tuesday, July 5

Cool CSS3 Tip: Text-Overflow = Ellipsis

You don't have to use lots of Javascript or server-side voodoo coding to get overflowing text to look good. With the new CSS3 feature, you can set the text-overflow property of your text to ellipsis, thus letting the browser handle this so-needed task for you.

CSS3 text-overflow: ellipsis DEMO

Dummy text. Move the slider below to change the width of this text and see how this works.

Width = 100%

The CSS Code

While this is a very simple attribute, getting this to work just the way you expect it can be somewhat tricky. All you have to keep in mind is that while the text-overflow attribute is what controls the ellipsis effect, just setting this one attribute by itself isn't enough.
.elip { 
  text-overflow: ellipsis;
  overflow: hidden; 
  white-space: nowrap; 
  width: 100%; 

<p class="elip">Some text to be wrapped by the CSS3 ellipsis attribute<p>

Notice that along with the text-overflow, you also need to make sure you specify two other properties: white-space (keeping the text from wrapping into multiple lines), and overflow (which keeps the text from bleeding through its container).

Other than that, this is pretty simple. Try out different ways to use this and see how it works for yourself. One thing I did notice is that if you use this property with a big paragraph that takes up multiple lines, instead of only applying the ellipsis to the last word or whatever, every line that has a break (either through a br tag or a new paragraph) will be ellipsed. Lines of text that expand beyond the one line will not wrap (due to the white-space property). So I think this will be for useful in situations where the ellipsis is applied to a header or title type text. Anything beyond a line (such as a summary) might not work so well, or at least I haven't figured out how to make it work right with a block of text. But that's CSS3 for you... enjoy!