Rodrixar

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:

    ;extension=php_sockets.dll

  • 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:

    extension=php_sockets.dll


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:
currentFrame++;
if( currentFrame > totalFrames - 1)
  currentFrame = 0;

/*** WHAT A WASTE OF BYTES! ***/

// 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( Date.now() - Player.frameUpdated > 70 )
  {
    Player.currentFrame = (Player.currentFrame + 1) % Player.totalFrames;

    // update time frame was animated
    Player.frameUpdated = Date.now();
} 

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.
<style>
.elip { 
  text-overflow: ellipsis;
  overflow: hidden; 
  white-space: nowrap; 
  width: 100%; 
}
</style>

<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!

Sunday, June 26

How to run Python CGI in WAMP


I've had a few people ask me how to install Python in WAMP (Windows Apache MySQL and PHP), so here's a quick tutorial on how to set that up on your WAMP server. What I'll do is assume you already have both WAMP and Python installed, explain how to run your Python .py scripts through WAMP, then I'll have a quick tutorial explaining how to download and install both Python and WAMP individually.

Writing your first Python cgi script


Before you can run your Python scripts on the browsers, you'll need to write a .py script. Here's a quick one just to illustrate the point. Type this in Notepad and save the file as hello.py:

#!python

print "Content-type: text/html"
print ""

print "Hello, World"


Now click the WAMP icon on your system tray, find the Apache option, then select the modules option. Make sure there's a check mark next to cgi_module. If there isn't a check mark next to cgi_module, go ahead and click it. This will enable the module and restart your WAMP Apache server. Now, go back to Notepad and save your hello.py file in the right cgi-bin directory. The precise path to this folder is probably different on each system, but is found inside the WAMP directory, then inside the bin directory, inside Apache. On my system, the path to the cgi-bin directory is

C:\wamp\bin\apache\Apache2.2.17\cgi-bin


Once your Python script file is saved, go to your browser and access the script by going to

http://localhost/cgi-bin/hello.py



That's it. No need to install extra modules or a whole different server altogether. Now to a brief tutorial on installing WAMP and Python on Windows.

How to install WAMP


In this tutorial I'll assume you already have WAMP downloaded and installed. If you don't, click the link above and download the WAMP server. Installing it is really simple (click and follow the prompts), but I'll save the details to another tutorial if the need for it arrises.

How to install Python on Windows

Once you have WAMP installed, the next thing you'll need to do is to install Python. Again, this should be pretty straight forward. Click the buttons and follow the few prompts. Once the installation concludes, you should be able to open a terminal (DOS) window and verify that the installation was successful. Try typing the following command in DOS:

python


If you see a response that says something like Python 2.7.2 (or whatever version you installed), then the installation was successful. If this is the case, you'll see the three >>> indicating that you can start typing Python code and run it right there. If, on the other hand, you get an error message from Windows, then this means you'll need to set up a system variable with the path to your Python install. This is really simple:

How to set up Python environment variable Path on Windows


What you'll do is tell Windows to run a program called python.exe located at a certain directory whenever Windows get a request to run python. To do this, open up your Control Panel and run a search on that window for environment. Windows XP and up (Vista and Windows 7) will bring up a link that says Edit the System Environment Variables. Click that, then click the button that's labeled Environment Variables...

Next, open up a Windows Explorer window and go to the location where you have installed Python. As this could be different for different folks, you'll just have to find where you installed your own. On my home system, I installed Python at

C:\Python


Once you have located your main Python folder, copy the folder path and go back to the Environment Variables window. Under System variables, find the one that's labeled Path, select it, and click Edit. Now go to the Variable value field, and be sure you don't erase anything from this field. Simply go to the end of the field, place a semicolon at the end of the list, and paste the path to your main Python folder. Click OK to save this, and you're done! Now you can open up a DOS window and type in Python, and start coding to your heart's content.