Archive for the ‘Programming’ Category

Migrating away from register globals

Friday, April 27th, 2012 | Programming, Tech

If you are luckily enough to work in a Web 2.0 start up, you probably won’t have to deal with too much legacy code. But for the rest of us, we can often find ourselves working with code which can be even decades out of date.

One of the big issues in PHP has been the deprecation of register globals. Of course, this happened quite a long time ago, because the idea of register globals was just plain stupid, but recent versions of PHP (5.3 onwards), will now throw a deprecation error.

So, we need to find a way to turn register globals off.

The end solution is of course to refactor the code so it doesn’t use register globals at all. Anything short of this is going to be a security nightmare, it’s like a ticking time bomb sitting on your server. But until then, there is a way you can emulate it in your PHP code while you work to get rid of it, allowing you to turn the register global settings off.

All you need is something like this in your code.

foreach ($_REQUEST as $key => $val) {
	$$key = $val;
}

Install dev packages with Composer

Monday, April 2nd, 2012 | Programming, Tech

Sometimes, you might install your dependencies via composer but find that the tests don’t work for it. You could get an error similar to the following.

phpunit
PHP Fatal error:  Class 'Symfony\Component\Yaml\Yaml' not found in
/home/example/Gherkin/src/Behat/Gherkin/Keywords/CucumberKeywords.php on line 31

This could be because if you have just run composer install, it will only install the main packages, but some packages could be specified as dev only. You may find a “require-dev” section in the composer.json file.

If you do, you can install the packages using the following flag.

composer install --dev

This will install the development packages as well, which should allow you to run the tests.

Compiling APD on PHP 5.3

Monday, April 2nd, 2012 | Programming, Tech

If you try and compile APD on PHP 5.3, you may get an error similar to the following.

error: 'struct _zend_compiler_globals' has no member named 'extended_info'make: *** [php_apd.lo] Error 1

This can be solved by modifying a few of the APD files. To do this, you need to download the APD archive file and uncompress it.

Then make the changes as detailed on the PHP bug tracker. Once this is done, it should install as normal.

phpize
./configure
make
sudo make install

APD should now be installed.

Hashing passwords in PHP

Thursday, March 8th, 2012 | Programming, Tech

If you store passwords as part of a PHP script, you may be using md5() or sha1() to hash the password. This is common practice, but you may be suprised to know that actually, the PHP manual recommends against it.

The reason is that they are both fast but relatively insecure hashing algorithms that can be brute forced by modern computer systems if they get hold of the strings. A better approach is to use the crypt() function, which is a little more expensive in terms of resources, but worth it for the increased difficultly you create for any potential hackers.

List locally modified CVS files

Wednesday, December 28th, 2011 | Programming, Tech

Quick command for listing locally modified CVS files.

cvs -Q status | grep -i locally

Testing multiple conditions in if statements

Friday, December 2nd, 2011 | Programming

This is one of the geeks among you. I’m currently working on a new open source project which uses a series of database models derived from a base model which includes some standard methods and I was having one problem in particular to do with updating data values in an object.

if (
    !$object->setName($d["name"]) ||
    !$object->setSlug($d["slug"]) ||
    !$object->setDateByArray($d["date"]) ||
    !$object->setContent($d["content"])
) {
    $this->setMessage($object->getMessage());
    return false;
}

As you can see, this does an if statement and then runs all the updates – the idea being that if any of them come back as false, it can set the error message and return false to the controller.

This worked as expected but with one problem – as soon as one of them appears false, PHP stops looking at the other conditions in the if statement. This is a problem because it means the user only gets one piece of feedback at a time. Whereas, it would be much better if we could give them all the fields that were wrong at once.

However, this doesn’t seem possible in the above implementation. Even if I switched it round to check that everything is true, and everything must be true, that suffers from the same problem that once something isn’t, PHP will stop checking the conditions.

I considered whether I could implement it using exceptions – putting all the checks inside a try block and then have the update operations throw an exception if they were invalid. I could then catch this exception and add the error to the list of errors. However, this suffers from the same problem – as soon as the first invalid value triggers an exception, the rest of the try block is ignored.

The solution I have eventually come to is this:

$writes = array (
    $object->setName($d["name"]),
    $object->setSlug($d["slug"]),
    $object->setDateByArray($d["date"]),
    $object->setContent($d["content"])
);

if (in_array(false, $writes)) {
    $this->setMessage($object->getMessage());
    return false;
}

All the operations are run, and their values are fed into an array. That way all the checks get run no matter what value they return. I then search the array for any values set to false and if any of them were, I know there has been a error and can flag it up with the user.

Your first Java applet

Friday, September 16th, 2011 | Programming, Tech

In previous columns we have fiddled about with some basic javascript so I thought this month we we do something a little different. We’re going to write a simple java applet. Yes you guessed it, its going to be one of those annoying “Hello World!” applets that every single damn language makes you do to get started. The sad fact is though is that they are great a teaching people the basics.

Article Overview

* Before we start
* The applet overview
* Creating the Java Source Code
* Compiling the source code
* Running the program

Before we start

Since we are going to be compiling the java code for the applet it means your going to need The JavaTM 2 Platform, Standard Edition. Its about 37 MB so it may take a while if your on a 56k modem. Use a download manager such as Flash Get. Also – make sure you download the SDK and not the JRE. You can download it from the following website.

http://java.sun.com/j2se/1.4/download.html

Now no one can say I don’t work hard for you. I wish someone had sold me I needed that while I was wondering why it wasn’t working. Your also going to need to set the PATH perminantly unless you know what your doing. Do to the documentation below and follow the steps to settings your path. You need to add some text to the path command rather than replace it by the way. Again I wish someone had told me that. The documentation on how to do this can be found at the following website.

http://java.sun.com/j2se/1.4/install-windows.html

The applet overview

An applet requires a java enabled browser to work rather than being a stand alone java application. Most major browsers supporrt java now although it may be an optional extra on your copy of Netscape or Opera. Internet Explorer automatically supports it. There are three steps in creating your first java applet:

* Creating the Java source code.
* Compiling the source code.
* Running the program.

Creating the Java source code

Open your text editor (Notepad will be fine but I prefer EmEditor) and type in the following:

import java.applet.*;
import java.awt.*;

/**
* The HelloWorld class implements an applet that
* simply displays "Hello World!".
*/
public class HelloWorld extends Applet {
public void paint(Graphics g) {
// Display "Hello World!"
g.drawString("Hello world!", 50, 25);
}
}

Save this code to a file called HelloWorld.java.

You also need an HTML file to accompany your applet. Type the following code into a new text document:

<HTML>
<HEAD>
<TITLE>A Simple Program</TITLE>
</HEAD>
<BODY>
Here is the output of my program:
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>

Save this code to a file called Hello.htm.

Compiling the source code

Open up command promt (Start > Run > “Command”). Once your at the command promt, go to the directory where you have saved the source code. For expample if you saved them in C:\code you would type cd C:\code. At the prompt, type the following command and press Return:

javac HelloWorld.java

The compiler should generate a Java bytecode file, HelloWorld.class. This file will appear in the same directory.

Running the program

Although you can view your applets using a Web browser, you may find it easier to test your applets using the simple appletviewer application that comes with the JavaTM Platform. To view the HelloWorld applet using appletviewer, enter at the prompt:

appletviewer Hello.htm

Now you should see an application come up with “appletviewer” or something similar at the top. It should then say applet loaded at the bottom and hello world in the middle. Congratualtions! Your applet works.

Don’t work if you got a error from command promt. I got that too saying it was using the default settings etc, but it didn’t seem to cause a problem. For more information on java applets go to http://java.sun.com.

ASP dictionary fun

Thursday, May 7th, 2009 | Programming

ASP has a lot of “interesting” features shall we say. I’ve just been working with the dictionary object which is basically an array with named items, so everything has a key and value pair.

There is a method to add elements to it which accepts variables instead of literal text strings (as you would expect of course) but it doesn’t seem to accept variables in array.

For example, this will not work…

totals.Add RSTdata(“id”), 10
Response.Write(totals(RSTdata(“id”)))

However this will work just fine…

idNumber = RSTdata(“id”)
totals.Add idNumber, 10
Response.Write(totals(idNumber))

This isn’t quite as cool as the way ASP decides the forget about some variables but only after you’ve referenced them for the first time creating a rather nice heisenbug when you put in a few print lines but never the less interesting.

Creating invisible buttons in Flash

Sunday, September 16th, 2007 | Programming, Tech

Sometimes you want to make an area clickable, say part of an image or you have some animation that you do not want to have to convert to a button. What you need is an invisible one.

First draw a square (or whatever shape you want) onto your page. Double click the shapes border and delete it. You don’t need it and it makes the button look weird when you resize it.

Now convert the box into a button. Once you have done this double click it, and add keyframes for up, over, down and hit like you would any normal button.

Go back to the first 3 stages (up, over, down) and delete anything in these frames. The only thing you should leave is the box in the hit keyframe. Now go back to editing the movie (Ctrl + E).

If it worked the button should now appear as a half tranparent blue box. And if it does you have yourself one invisible button. You can now resize this to any area you want it to cover.

Creating a Flash preloader

Sunday, September 16th, 2007 | Programming, Tech

Large movies take a long time to load, especially for users who are not blessed with a high speed broadband connection. Therefore just giving them a screen which says loaded or just giving them nothing at all can leave them a little dazed and wondering what to do. The solution – give them some feedback on what is being loaded.

Movie modifications

The first thing you need to do is have an empty frame at the top. You don’t need anything else – just an empty frame before you content. If it’s easier you could even create a separate scene to house this frame. Make sure it’s a key frame and the next frame where you content begins is a key frame too.

Next create a text box which says loading, or the name of the movie or something similar. This will be our loading object. It should only exist in that first fame. Now with the object selected go to Insert > Convert to Symbol and save it as a movie clip. I recommend the name ‘preloader’ but it has no affect what so ever. It just makes it easier for you to identify it in the library.

The scripting

Now double click on your newly created movie clip and watch it zoom into editing mode. There should currently only be one frame in the timeline now – extend this to three by inserting two new frames. Call this layer text or graphic or something similar. This layer will just remain the normal static text. The scripting will go in a different layer – create a new one for the scripting and make each of the three frames, key frames.

Now we have three key frames in the script layer which we can insert code to. This is expert field so we need expert view on. If you’re not working in expert code view then open the actions panel and click the options view icon. It looks like a little square with an arrow pointing to the top right hand corner. Then click the line which says expert view rather than normal view. This will turn the action scripts window into more of a text editor style window to allow us to insert code.

The first thing we want to do here is to stop the main movie from going any further before it’s loaded. So click on the first frame in the script layer and put the following code in:

_parent.stop();

This tells the main movie to stop. Generally commands like this use the model: object.command. In this example the object is the main movie or _parent as its known and the command is to stop it.

Now click on frame two of the script layer. He we are going to set some variables so we can give the user feedback on how far the movie has loaded so far. We do this by using a few functions built into ActionScript which allow us to get certain values.

kBytesLoaded = getBytesLoaded()/1024;
kBytesTotal = getBytesTotal()/1024;
kBytesRemaining = kBytesTotal - kBytesLoaded;
percentLoaded = 100 * kBytesLoaded / kBytesTotal;
progress = Math.floor(percentLoaded) add "%";

This script works out what has been loaded and how much is to load and then works out the percentage. It’s a great script although I can’t claim responsibility for it. Insert this script into the second frame and that will give us plenty of variables to work with.

Finally click on the third frame in the scripts layer. In here we check to see if the movie has loaded and if it has we send them on their way. If not we continue to loop and give them feedback on what has been loaded so far.

if (percentLoaded < 99){
gotoAndPlay(2);

} else {

_parent.play();
stop();
}

Here you can see if that if less the 99% has loaded then the movie is not fully loaded then the movie clip is sent back to recalculated the variables. If 99% or more has loaded then the movie clip is stopped and the main movie starts again. I use 9% rather than 100% as if there is a little data left which cannot be loaded it will never reach 100% and therefore loop for ever.

Giving feedback

Finally we need to tell the user what is going on. So create a new layer, call it something like feedback. Then insert a text box. This will display the percentage that has been loaded so far. This box needs to be set to dynamic. In Flash MX you can change this in the properties box - look for the drop down menu saying static text and change it to dynamic text.

Also look for the input text box which says var next to it. This stands for variable and will let us make the text box fill with a variable we set. So in the box write:

Progress

This will fill the box with the process variable telling the user what percentage of the movie has loaded. You're done - hit Control + E to return to editing the main movie. You can now export your movie save in the knowledge that users will see how much percentage of the movie has been loaded.