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.

Tuesday, March 22

jQuery Slideshow - HTTP Efficient

Why another jQuery Slideshow Tutorial ?



A while ago I posted a tutorial on a Javascript slideshow implemented in Prototype. That was all nice and well, since there weren't a whole lot of Prototype tutorials out there. But also, the specific implementation I did was especially powerful because it had HTTP requests in mind. So now we have a version of that same slideshow in jQuery.

Live Demo:








Here's the logic behind my slideshow is simple


The usual slideshow requires that you list all of the images you want sliding in some sort of list. Then the images, through CSS, are all stacked on top of each other so only the top-most image is visible. Then, every so often the top image fades out, revealing the next one. My issue with this approach is that, suppose you have 10 images in the slideshow, all 10 images are downloaded (10 HTTP requests, bandwidth, latency, etc). Worse yet, what if the user only stays on the page long enough that only the first two images are shown?! You wasted bandwidth and loading time for the other 8 images. Not to mention if you want 100 images in the slideshow...

My approach:


I only list two images at a time. One is the top-most image (the one that's visible), and the one immediately behind it. Then, when the timer fires (the image slides), I fade the top image, reveal the back image, and wait for the next timer event to fire. When the timer gets ready to fire again, I download the next image, place it behind the current top-most image, and repeat the process. Now if the user only views my site long enough that 5 images are rotated through the slideshow, I don't have to download the remaining 95 images I wanted to display.

The Code



As this slideshow is using jQuery, the first thing we do is import the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>



Now we define the basic CSS so the images are self-contained:

The CSS

<style>
#iSlideShell { position: relative; height: 175px; width: 500px; overflow:hidden; }
#iSlideShell img { position: absolute; }
</style>

* note that the CSS above sets the height and width of the slideshow container, but those can be customized to your own needs.



Then we set up the HTML where the images will be displayed:

The HTML

<div id="iSlideShell">
<img id="back-image" src="image1.jpg"/>
<img id="front-image" src="image2.jpg"/>
</div>



It's very important that you keep the ID attributes of those three HTML tags as they are. If you do decide to change them, change them also in the following Javascript.

The Javascript

// keeps track of what image to display next
var i = 0;

// the time each image will display before it fades out
var delay = 3000;

// the time it will take to fade each image
var fadeDelay = 150;

// the filename for each image. Don't include the .jpg extension
var iSlides = new Array("image1", "image2", "image3", "image4", "image5");

// This is where the magic happens
function rigoSlide()
{
// show the top image
$('#front-image').show();

// make the bottom image visible
$('#back-image').show();

// after the image finishes fading, bring the back image to the front
$('#front-image').fadeOut(fadeDelay, function(){
$('#front-image').attr('src', $('#back-image').attr('src'));
});

// increment the array index, but never go beyond the array boundaries
i = (i + 1) % iSlides.length;

// now load the next image behind the image currently showing
$('#back-image').attr('src', iSlides[i] + ".jpg");

// start process over again...
setTimeout(rigoSlide, delay);

}


// call the slideshow when the page finishes loading
$(document).ready(function(){ rigoSlide(); });



Cut and Paste



Now, I realize some of you might not be able to put the above steps together all by yourself... so if that applies to you, just go ahead and paste the following block of code in your website where you want the slideshow to appear. Just make sure to replace the bold text with the names of the actual images you'll be using for your own slideshow:

<div id="jq_rigo_slide" style="width:994px; height: 300px; position: relative; top: 0; left: 0; margin: 0; padding: 0; overflow: hidden;">
<img id="jq_b" src="img1" style="position: absolute; display: block;" />
<img id="jq_f" src="img2" style="position: absolute; display: block;" />
</div>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' type='text/javascript'></script>
<script type="text/javascript">
var i = 0;
var delay = 3000;
var fadeDelay = 150;
var iSlides = new Array("img1", "img2", "img3", "img4", "img5");

function rigoSlide()
{
$('#jq_f').show();
$('#jq_b').show();
$('#jq_f').fadeOut(fadeDelay, function(){
$('#jq_f').attr('src', $('#jq_b').attr('src'));
});
i = (i + 1) % iSlides.length;
$('#jq_b').attr('src', iSlides[i] + ".jpg");
setTimeout(rigoSlide, delay);
}
rigoSlide();
</script>



Conclusion


So there you have it. I'd recommend you save the Javascript externally and include it the same way you're including the jQuery Library, but that's not required for this to work.

Post your questions, comments, or concerns below.

Thanks,

Sunday, January 2

Weird CSS3 Demo & Tutorial


Below is a form with some weird CSS3 effects that you may not know about. But keep in mind this one principle I've learned earlier in my career, and it has served me very, very well:


Just because you can, doesn't mean you should


Just because something in possible, don't be in a hurry to use it or do it. Keyword here is: HTML Marquee and Blink tags


CSS3 Demo Form

Enter your name:
Enter your e-mail:
Enter your phone number:

CSS3 » Outline


The outline attribute is like a border, but is drawn outside the actual border of the element. According to the W3Schools, the purpose of this property is to make an element "stand out". You may have noticed this in Chrome. I personally find it annoying because in Chrome, when you enter an input element (in a form), Chrome draws a yellow line around the box (input box). This is the outline property kicking in.


You can set the outline just like you do a border:


outline: 1px solid #c00


or you can turn it off by either setting it to 0 or none:


outline: 0;
outline: none;


If you look at the source code in Google's main page, they use both the number zero and the value 'none' when setting the outline of elements to nothing.


CSS3 » Zoom


The zoom attribute is a dangerous property, because some people think it's so cool, and therefore they over use it in horrible ways. Basically this works similar to how your browser would zoom in and out of your page when you use the magnification features in it. If you set an object's zoom to 100% (or 1.0), then it will look 'normal'. However, if you set it to something greater than that, the object will scale like it would when you zoom in it. Pretty self explanatory.


Some people used to add hovering effects by changing the text's font-size for the hovered state, but now you can set its zoom to something and affect not only text and the box around it, but also images! This is that terrible two-wedge sword. Could be a great help, or a sure way to flood the web with ugly zooming effects:



.link { font-size: 1.25em; }
.link:hover { zoom: 200%; }


CSS3 » Transformation


The transformation attribute is part of the webkit library. You can use it in Mozilla Firefox using they -moz counterpart. What a lot of people are doing is setting the same property they set to -webkit (which works fine in Google Chrome and Safari browsers, as well as the iPhone, iPod touch, iPad, and the Android systems) set it to -moz, -o (for Opera), -ie (Internet Explorer), and then just list the property with no prefix for the day it becomes a standard. I don't necessarily recommend this, especially if the library you're specifying doesn't support the property (like -ie-transition), but it doesn't hurt. Besides, if a lot of people are doing it, you might not look like a fool doing it too...


To use transformations, you specify the transformation desired, the value, and a unit to go along with it:


-webkit-transformation: rotate(-25deg);


CSS3 » Transition


Finally, transitions are awesome things that happen between the beginning and the end of an attribute change. For instance, when you set a font color, then a different font color for that same text when it get hovered, then you only see the first color, then the end color when teh text is hovered. With transitions (also part of -webkit), you can specify what happens during that change. If you've ever worked with Flash, this should be natural. With CSS3 you specify how slow that transition happens. In the form example above, I specified the transition to take half a second:


-webkit-transition: all 0.5s linear;


Here I was a bit lazy because I didn't want to specify a transition speed for zoom and rotate, so I used the keyword 'all'. the keyword 'linear' specifies how that transition takes place. Other acceptable values include:

  • linear - constant speed
  • ease - gradual slowdown
  • ease-in - speed up
  • ease-out - slow down
  • ease-in-out -speed up then slow down

So there you have it. I hope this helps, but please, use these things for the good of the web =)


Feel free to post any questions you may have or email me directly.