Archive for the ‘Programming’ Category

Storing monetary values in MySQL

Sunday, October 5th, 2008

Just a quick one. I was doing a bit of work earlier today and I needed to store a price like “0000.00″ in a MySQL database. As you can see there are quite a lot of options for numerical data types, and the first thing that came to my mind was FLOAT.

However, I ended up settling on DECIMAL which allows you to set the precision (significant digits) and the scale (digits after decimal point) and this seems to work (as far as I’m aware you can also do this with FLOAT too). So for example I defined my field like so:

DECIMAL(4,2)

I can’t remember off the top of my head what the difference is between FLOAT and DECIMAL. I think it’s to do with the way they are stored internally, with DECIMAL working in the way you’d most often expect. Anybody know any different?

PHP session problems

Monday, September 29th, 2008

Sessions are funny things. Most of the time they work first time and you never have to think about them again. Other times you run into a few issues.

Tonight I thought everything was fine, then I did a simple page redirect. On the other side I tried to read from $_SESSION and everything had disappeared. I spent too long pouring through the code before I realised what was wrong.

Apparently PHP / Apache regards “www” as a subdomain. I was redirecting from http://example.com to http://www.example.com so everything got dropped. A simple mistake to make and easily overlooked. When I figured out the problem I found this post on PHP.net.

Strangely I’ve never noticed this behavior before. I wonder if it has always been there or it varies between Apache 1.3 and 2.

A bit on PHP security

Sunday, September 21st, 2008

PHP really is a smashing language, allowing you to knock out rich applications quickly and easily. As anyone with half a brain will realise though, giving power to people that don’t have a clue is a recipe for a disaster.

This is by no means a comprehensive list, but here are some common security issues that I have encountered with some simple fixes.

1. Use mysql_real_escape_string()

SQL injection can be a big problem, but it is easily defeated. Validating every input into your web application is a must, whether it comes from $_POST or $_GET. If it passes this validation then you should wrap mysql_real_escape_string() around the variable to escape dangerous characters. For example:

$query = “SELECT id FROM logins WHERE username=’”.mysql_real_escape_string($_POST['username']).”‘ AND password=’”.mysql_real_escape_string($_POST['password']).”‘”;

2. XSS protection

Cross site scripting is a real danger, but is something that can be protected against without too much work. Simply remove HTML / Javascript tags from any input by using str_replace or an equivalent. I find that I only need to worry about this when dealing with textareas, because text fields are usually a lot more locked down to the type of data that needs to go into them.

3.URL Manipulation

Web applications typically pass information through URLs. Consider the following link:

view_personal_info.php?my_user_id=123

In this example I think we can probably take “my_user_id” to be my id on the system. So what happens when I go to the URL with id 124 or 125? Will I get information on other users? Probably, and that’s why on every page you need to check that the current logged in user has the correct access to view the information.

This isn’t hard to do, so I’m not going to explain the solution here. However, if you’re passing a lot of information through a URL and want to make sure it’s not tampered with, then there’s a straightforward way to achieve this. Creating a hash of the data with a password only the application knows, passing it in the urlĀ  and revalidating it on the target page works a treat.

4. Use forms, not links

I’m guilty of having done this once or twice, mainly due to ignorance, but when you’re doing any database modification it should always happen through a form, not a link. Otherwise people can craft links to pages like delete and trick you into clicking on them. If the pages aren’t properly password protected, then it’s also possible that search engines can crawl your site and wreck your database.

5. Other

There are plenty of other little tweaks you can make to your PHP configuration to improve security, depending on what you’re doing and how locked down you want your server to be. Two little things I do when putting code on a live site are turning error messages off, and moving pages that don’t need to be read directly outside of public_html.

I think the hardest thing about PHP and web application security in general is the range of scope for attack. Every input has to be validated, and in a big application this can be easily overlooked. Unfortunately, it only takes one error to bring your entire application down.

getElementsByName IE fix

Sunday, September 14th, 2008

I was recently writing a bit of javascript to collapse / expand sections on a page. These sections are output by a bit of PHP and I don’t know how many there are likely to be, so I gave them the same name and looped through them with getElementsByName().

Now this works fine with Firefox, but I ran into a few problems with IE. It turns out that IE doesn’t support it, but luckily someone has posted an alternative solution here which I thought was rather clever. Here it is again incase the site isn’t available later on.

function getElementsByName_iefix(tag, name) {

var elem = document.getElementsByTagName(tag);
var arr = new Array();
for(i = 0,iarr = 0; i < elem.length; i++) {
att = elem[i].getAttribute(”name”);
if(att == name) {
arr[iarr] = elem[i];
iarr++;
}
}
return arr;
}

Have some code

Tuesday, January 29th, 2008

I’m writing a fair amount of code nowadays, both at work and at home. It’s my plan to release bits I think are useful so others can use them as they see fit. I’m sticking all of this in /code, so browse over and take a look.

Firstly, I’ve written an RSS Feed generator in PHP which allows you to produce RSS feeds effortlessly.

Secondly, I’ve written a small class for managing file downloads in php. This allows you to track how many people are downloading certain files on your site.

More are on the way, as is a new site design.

Any code I stick on here can be freely used in any commercial / non-commercial projects unless otherwise specified. If you do end up using anything I’ve written then letting me know is a nice way of expressing your thanks. :)

Simple PHP app to grab Twitter status

Wednesday, October 17th, 2007

This evening I joined twitter and immediately got mobile support and facebook integration going. Having a central place for all my status updates is great, and the fact I can update on the move is amazing too. However, I wanted this integrated with my website so people can go to mikelaming.com/status and see what I’m doing. I wrote a little bit of PHP to get the desired effect, and if anyone else wants to do the same, here’s the code. Enjoy! (This could be rewritten to use SAX which would be faster, but DOM is so easy)

<?php

$data = file_get_contents(”http://twitter.com/statuses/user_timeline/mikelaming.xml?count=20″);

$doc = new DOMDocument();
$doc->loadXML($data);

$status = array();

$main = $doc->getElementsByTagName(”status”);
foreach($main as $sub)
{
$temp = $sub->getElementsByTagName(”text”);
$status[] = $temp->item(0)->nodeValue;
}

for($i = 0; $i < count($status); $i++)
{
if($i == 0)
{
echo(”<h2>My Current Status</h2>”);
}
else if($i == 1)
{
echo(”<h2>Older…</h2>”);
}

echo(”<p>”.$status[$i].”</p>”);
}

?>

Obviously replace my username ‘mikelaming’ with yours.

UPDATE: You can see what I’ve done with this here.

Developing Java Web Services

Friday, September 21st, 2007

For the past week I’ve been in London (Accenture Learning, Lime Street) on a training course for work, entitled “Developing Java Web Services” and it’s been very interesting. The only problem is the sheer amount of material it covers, which is hard to keep enthusiastic about after 5 days of the guy at the front of the room (literally) throwing knowledge your way.

If any one gets the chance to attend this course I really recommend it as it’ll make you an expert in XML/REST/SOAP/WDSL/SAAJ/UDDI/JAX-RPC/JAX-WS and any other acronym you can think of in no time at all. :P

dsc00145.jpg

First Steps with Java Servlets

Tuesday, July 17th, 2007

‘Murach’s Java Servlets and JSP’ popped through my letterbox this morning. I need to get a headstart on learning JSP/Servlets before I start work and this book looked like a fairly good introduction to it. I briefly glanced through the 600 or so pages over lunch and although it seems a little basic I’m sure it’ll be a good stepping stone to something a little more complicated.

murach_cover.jpg

Talking of complicated: after lunch I installed Tomcat. Now I like to develop code on my machine and not have to upload it onto a server half way around the world to test. I’m not a fan of having to install Apache / MySQL / PHP individually either so I really like XAMPP for linux because it makes my life a lot easier.

Unlike the Windows version of XAMPP Tomcat isn’t provided in an easy to install addon. There is one listed on the addons page but it only works upto version 1.47 of XAMPP which isn’t much good. After messing around with old versions for a while and having no luck I decided just to install it on my Windows Server 2003 box, which worked perfectly straight away. Unfortunately now I have to do Servlet development over my local network, but that’s the price I pay for being lazy. I wonder if Apache Friends will make a properly supported Tomcat addon for XAMPP Linux soon.

Can anyone recommend an easy way to get this running on Linux?

Yardsnap Ltd. and Google Checkout

Tuesday, June 26th, 2007

Woweee! A day or two ago Aaron registered Yardsnap with Companies House, so now I am one of three legal directors for Yardsnap Ltd. along with Aaron and Shazz. Exciting stuff (I just have to make sure the guys keep the Inland Revenue happy and it’ll be fine. :) ).

The super-duper brand new shiny website is coming along. It’s nice to see it finally take shape and work as a whole instead of being a mishmash of random components. Still a lot of work left, but with 5 weeks to go before I enter the world of full time work I think I can just about squeeze it in.

Today I implemented the first stage of the shopping cart using phpgcheckout. For those of you who don’t know, phpgcheckout is an “Open Source PHP Google Checkout Toolkit”, that is, on the whole, very easy to use.

logo_phpgcheckout.gif

The second stage is implementing a GC callback web service that can receive messages from GC and update our database. This is going to be harder. phpgcheckout has all the code available to use, but it’s pretty poorly documented and I could only find one example online which was a bit hardcore. When I figure it out I’ll post an example here for all to see.

Watch this space.