Amateur Protagonist Alister Sneddon

I once almost won a procrastinating contest, but I turned up.

Witcher Three - Wild Hunt - Terrible Ending?

29th June 2015
By Alister Sneddon

70 hours, level 37, countless collectables and tones of side quest later I finished The Witcher Three - Wild Hunt. I've never been so upset and left down by an ending since Fallout Three (do bad things come in threes?)

So what went wrong? What happened?

I first tidied up as many quests as possible before starting the ending sequence. Then suddenly everything felt rushed. The missions were fast and gave you huge amounts of experience very quickly. Yet the story seemed to be closing as many lose ends as possible. When I ended this "end game" state I was told the side missions would wait for me. So any missions that came up I figure I would wait till later.

The final battles of the game were filled with never ending spawns and basically cannon fodder. The final bosses were forced multi stage boss battles, which annoying enough my hits that triggered the next stage would see the boss recover health.

Suddenly the game was over.

Just like that the game ended.

A new mission starts, I hunt down a missing piece of the puzzle and have a final fight. Then Geralt, completely out of character basically breaks down. Monsters swarm around him and it heavily shadows that he died there. Yet all of these monsters I've killed a hundred times each, in bigger packs.

Then the final "this is the end" slide show kicks off, just like Fallout three (you're a fucking mutant get in the fucking chamber you greedy fuck.)

I got the worse ending, ended up alone and doomed all non-humans. Seventy fucking hours I put into that game. Seventy fucking hours for this game to give me the middle finger. You're a terrible father figure, you couldn't commit to one person and most of all you doomed everyone because you are selfish.

I was told my decisions would matter in this game. Yet all that mattered was what happened when I ended the "end game".

So let break this down. The whole fathering side of things. Turns out all the decisions were binary yes or no answers. The problem is this game isn't fucking Mass Affect. So your lengthy game changing decisions are built from three word prompts. There is one section where saying destroying someone's home because you're in a bad mood was a negative. Telling someone not to go nuclear over nothing was a fucking NEGATIVE. Maybe it was designed to be confusion so you would go back and play it again or maybe get the guide. I looked up the correct answers and they were a push at best. All of the decisions were objective, you could argue them either way. Is it my fault Geralt is a shit negotiator?

So those binary confusion three word answer got me the bad ending. Because I didn't ruin the fucking end I was punished.

Next was the love life side of things. Remember when I said I done all the side quests. I done Triss first and kissed her, at the end however I let her go. Then I done the other love quest and stuck with her. Turns out the choice was not based off who you pushed away or who you was closest too. No it was fucking based off the kiss option. In the game I played the events were so far away from each other and I clearly pushed away any advances from Triss, yet the game had spoken. So because I wanted to finish the side quests before the end of the game I was punished. I wanted to play through to the end and experience the amazing story yet the binary irreversible choices had already been made. Again back to Mass Affect, in that game when you have a love life tangle the game tells you so and give you a chance to correct the course or push both away.

Finally the death of all non-humans. Guess what? There is a quest that comes up during the end game sequence that is required for the good ending. Even better is the quest automatically fails if not completed before the end of the game. So I missed out on a whole section of the story line and was told I neglected everyone. The game told me my side missions will wait, it told me the world would wait. Yet it flat out lied.

Once all was over the game kicked me back, put me back in the world and told me to what point in time the game was rolled back to.

The game started to bug out and lag. I had to restart the game as it became unplayable. Once back in the game I revisited all the locations to have a look at what was going on. No reward, no happiest and all the best main characters were locked away as they only showed up in the end game which was now finished.

I installed The Witcher Three and I don't know when I will go back to it.

The Witcher game play is not my favourite type and the fights where not the strong point of the game for me. With the game over and after getting the big middle finger surprise I had no desire to play it again.

I played an hour of Witcher One, 20 minutes of Witcher Two and seventy hours of Witcher Three.

After such a long commitment to one game it ended up feeling like my time was not respected. Even if I go back to the save before the end game I will never correct the love life decisions due to how the game made its decisions.

Using Google Spreadsheets to stream FTSE 100 Data

10th May 2015
By Alister Sneddon

A long time ago you could use Google Finance API's to get a lot of information about the FTSE 100 (and beyond, it allowed full access with rate limiting.) However those golden days are gone.

This article is going to be a little bit of a special one in my eyes. Why is that? Well this is a system I have personally used to stream (using AJAX polling) 15 minute delayed FTSE 100 prices.

So let's get into the Google Spreadsheet side of things.

First thing that is important to know. You can inside a Google Spreadsheet use the following function:

This allows you to query a number of different things about a symbol. We are going to get the following data:

  • Current Trade Price (also known as last trade price)
  • Last Trade Date Time
  • Opening Price
  • Current Day Trading Volume

Google has a great help page on the functions you can use and the types of data you can request. Google Finance usage in Google SpreadSheets, however you are limited in the number of times you can use this function inside a spreadsheet (1,000 requests per a spreadsheet, if you go over the limit just make another spreadsheet with different data sets.)

Open your Google Spreadsheet and give it a half decent name "Google FTSE 100" sounds good to me. Now we are going to need six columns for this to work. Let's try this with just two equities to get us started.

The only downside to using the spreadsheet method is you to know what symbols you are requesting.

The first row in our spreadsheet will make up our headers. Now do NOT include any spaces, this WILL cause you problems and stop you from being able to query the data using PHP (or whatever language you like.)

My headings are:

  • Symbol
  • Name
  • Price
  • Volume
  • PriceOpen
  • LastTrade

Now you have that setup let's put in some data so skip down to the next row (row 2 now people) and let's add our static data.

  • Symbol: AAL.L

Now let's add our dynamic query data (note: you HAVE to use double quotes.)

  • Price: =GoogleFinance(A2, "price")
  • Volume: =GoogleFinance(A2, "volume")
  • PriceOpen: =GoogleFinance(A2, "priceopen")
  • LastTrade: =GoogleFinance(A2, " tradetime")

What this allows us to do is be very lazy. It is very easy to get the symbol and name of FTSE 100 companies, paste them into column A and B then you're formula will cleanly copy down and provide you with some nice data.

If this is all you was interested in, getting dynamic numbers into your Google Spreadsheets, then you have everything you need to get started.

The ones who want to now connect to this spreadsheet read on.

First thing you now need to do is make your document public. Click on the Share button and make sure the doc is publically accessible. Take note of the key parameter inside the share link. This key should also be inside the URL you are currently looking at anyway.

There are a number of ways to read a Google Document but I like the JSON method the most.

Here is the PHP code to read the JSON file and print each row. If you have been following my example it will be just the one row.

// Enter the key to complete the URL we will query
$key = 'Enter SpreadSheet Key Here';
$url = '' . $key . '/od6/public/values?alt=json';

// You could be fancy here but I am making a point, just get the content of this URL
$file = file_get_contents($url);
// This is a JSON file so you can expect decode to work
$json = json_decode($file);

// We only care about the rows
$rows = $json->{'feed'}->{'entry'};

// Loop each row and print it out as we go
foreach($rows as $row) {
  echo '<p>';
  echo $row->{'gsx$symbol'}->{'$t'} . '<br />';
  echo $row->{'gsx$name'}->{'$t'} . '<br />';
  echo $row->{'gsx$price'}->{'$t'} . '<br />';
  echo $row->{'gsx$volume'}->{'$t'} . '<br />';
  echo $row->{'gsx$priceopen'}->{'$t'} . '<br />';
  echo $row->{'gsx$lasttrade'}->{'$t'} . '<br />';
  echo '<\p>';

I am sure you can agree that is pretty amazing. You can either query this direcly as your AJAX call or make a page to handle just this logic and then query that page for a formatted slimmed down response.

Have fun!

Step by Step Guide to Becoming an Investment Lad

1st May 2015
By Alister Sneddon

You might be sitting at work or home thinking to yourself "I wish I could invest my money and generate easy revenue for myself." You might have even done the odd Google search for investments and even watched a little bit of the budget announcements. Investing is hard and everyone keeps telling you that you can lose all your money.

Now while your lack of effort and the very real risks to completely ruin your life are extremely serious barriers at entry, they are also lad point multipliers.

You might be cruising the night life of London and meet a few investors or people who claim to have great tips. The problem is when you ask them about their investments it is always the same thing. "Oh based on my fundamental research" or "I use CFD's to turn my monthly wage into a boat every month." Now these people might be living the dream, but they sure as hell as not racking up the lad points are they?

So here is a simple step by step to becoming a man of the manor, a lad investor and a legend of the financial world.

Has this company ever sponsored your team?

Let's be honest, if they don't have the time for the finer things in life then why should you? Everyone knows the rules about all work and no play. You don't want a Shining situation with your investments now do you?

Is it a bank?

Old men invest in banks. No lad goes on the pull with RBS or Barclays printed on his shirt, what does that tell you.

Do your mates know the company?

Did you think this would be easy? Half of investing is telling people you are investing and what you are investing in. No one wants fucking war and peace to explain they print posters or make the little bristles on the bottom of the shit stick.

Are you prepared to sell them if you hear anything which goes against your image?

Picture the moment, you are down 30 percent and not in a position to sell, you are looking at going long to make the cash back. Suddenly news comes out that said company removed their adverts with half naked women because of complaints. Remember an investment is a reflection on your inner person, gun manufacturers, beer companies and sporting equipment providers are the only sure bets.

Will it get you laid?

Try telling some lass BP is a smart long term investment. After the 10 minutes of being told you are the scum of the earth, plus all the small animals that were too slow to evolve to your level are dying, your dick is shrivelled and you regret waking up that morning. Be a smart lad. If you are ever in a bad spot just remember "If charities where publicly listed companies I would invest in them."

You might be thinking you are ready to start investing; maybe you were going to start some free account with fake money. Do you also put fake money on England to win the world cup? An Investment Lad is all in or all out.

Full disclosure, I might own some of the shares I mentioned. Hell I might even own the shares you are looking at right now. In fact just assume I am completely biased towards everything, literally everything. You see that rock outside your place? Yeah that one, I have a bias on that too.

PHP Make Or Die Send An Email

10th January 2015
By Alister Sneddon

Let's get this straight out there right this now second. If you are using the die function in your code you are a terrible person. Always handle your errors and end things gracefully.

That said sometimes it simply does not matter or you do not have the time or maybe you have a good reason for using die. FYI I have never outside of local testing found a good reason for using die.

Now this site uses die to handle really big database errors or any issue which could be a threat to the system. The reason for this is to protect the system. I use CloudFlare to protect against my server buckling under pressure and I use die to protect against single user mistakes or servers which I depend on not being available.

Again die is never the solution. Never.

However when you do use die it is nice to know that you had to use it. For a long time this site was using die and that was the end of it. I never had a need or care beyond not spitting out raw errors.

For a very long time I also had a memory leak issue relating to my database on this site. The fix was simple but I had to know it happened. My site uptime is only checked every 5 minutes and it needs to fail two times in a row. Basically my database would have to be offline for 10 minutes before I am emailed.

So I made a very simple change so I would be emailed what went wrong. This is an extremely basic function made to replace die. You do not want to copy the function and start using it. Make some changes, figure what you need to see and what matters to you.

Here is the code, after this block of code I will quick talk about each section and then some examples.

function die_and_email($body) {
    $mailto = "MYEMAIL";
    $mailsubj = "Website Used Die!";
    $headers = "MIME-Version: 1.0\r\n"; 
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
    $headers .= "From: MYEMAIL\r\n";
    $mailbody = "<html><body><h3>Your website just used Die!</h3>\n";
    $mailbody .= "<p>The die was triggered and this email has been sent.</p>";
    $mailbody .= "<p>Die was stamped at: " . date("Y-m-d H:i:s") . "</p>";
    $mailbody .= "<p>The following message was passed in:<br />";
    $mailbody .= $body . "</p>";
    $mailbody .= "<p><small>All the best,<br />Alister Sneddon</small></p></body></html>";

    // Send the mail
    mail($mailto, $mailsubj, $mailbody, $headers); 
    die('<h1>Sorry!</h1><p>This is real bad, I have just sent an email to myself.<br />You should leave.</p>');

So this code would be used in place of your standard "or die(Helpful message');" The first variable would be who gets the email. The second variable is the subject line to use. Then we have the headers. The first two headers make it a HTML email. The third header is who the email comes from, I recommend you make this the same as the address which will receive the email for now.

Then there is the mailbody variable. This is simple HTML with some flavour text. The email will pass in the message you write as well as the time stamp in MySQL format. This is super helpful for working out the accurate time of the issue.

Then we send the email and display a HTML die.

This is a pretty basic setup so let me show you its usage in the wild.

mysql_connect($host, $username, $password)
	or die_and_email('Failed to connect: mysql_connect($host: ' . $host
		. ', $username: ' . $username . ', $password: ' . $password . ')');

In this case we simply respond with the function which has failed and show what parameters we were passing in. This is handy for situations where the variables you pass in might change or vary depending on system (so you can pick up the wrong system has the wrong version.)

Here is another example in which we pass in a simple string as reference. There is no or in this situation, the user has completed an action to which we simply want to die.

die_and_email('Test script attempted to run.');

Finally you can use this to give basic information as to who caused the problem

die_and_email('User from the IP: <strong>' . $_SERVER['REMOTE_ADDR'] 
	. '</strong> loaded <strong>test.php</strong>.');

Hopefully this has given you some ways to improve your visibility on errors. If you have access to your servers error log then I suggest you change the script so that before the die you do "error_log($body);" that way you will pass the same message from your email into your error log which is automatically time stamped for you.

Symlink Alias Files PHP And IIS

10th August 2014
By Alister Sneddon

Through and through I would say I prefer using a Windows machine over a Macintosh. However if you work on a LAMP stack it can be tough replicating your live environment on a Windows machine. As much as I hate it, developing PHP for a Linux environment on a Windows machine is tougher.

Sure you can use things like WAMP if you are a bitch arse pussy who wants to be spoon feed (or you want to learn more about LAMP without using a virtual machine.) however I enjoy using IIS. Using IIS for PHP and MySQL is not really the best environment and honestly I had no reason to use that setup for my local development.

A problem came up the other day when attempting to replicate one of our production systems. The system used a folder structure very common for fast multiple releases. The structure would mark every release with the date, and then a symlink is created called current which sits outside of the releases folder and simply points to the latest folder.

This system is a fantastic way to manage production releases before you get your hands on deployment tools. It means you can checkout your code and then easily switch folders with very little risk.

The problem was there is no out of the box method to create symlinks in IIS. Now I looked into this for a few hours and the general solution is Oh just use the virtual directory sadly depending on the complexity of your system more often than not, this just does not solve the issue.

Sure if you want to go to a different folder it's ok. Even then I do not believe it to be a good solution.

Another real problem is for users who might have a file which never changes e.g. settings.php or config.ini which must always be the same, it could contain database credentials or even just the salt you use. Either way the file must never change. Do not risk having it in your repository. This file should be symlinked in.

That is where IIS really hits the ground and frankly shits itself. The decision was then made I would scrap my function environment and attempt to use WAMP like the other developers. Again this all went well and somehow I got around the permission errors that follow me like the Black Death.

However we ran into the same issue. The problem is really at the OS level. Windows just does not have a nice solution to this issue. At one point I was creating shortcut files and even copying real symlink files and attempting to run them through Apache in hopes of tricking the system into working.

I love working with Windows, however every now and again you do have to throw your hands up and recognise a better solution. With a LAMP stack if you have a local development environment a Macintosh is a better solution. It really is a shame I just hate how a Mac works e.g. go fuck yourself case sensitive path names which doesn't work with Photoshop.

So really what I am saying is as the complexity of your live system grows you need to be able to replicate it better and better. In an ideal world you should have a box setup which is separate and that you remote/SSH into. However that is no always possible.

Also in regards to using a Linux system and then developing locally, that is like buying a cow because that is the only way to truly get fresh milk. You have to draw the line between practically and functionality. While running just Linux as your developing environment is extremely function it is very unpractical regarding support for tools you may require. Hopefully this changes one day.

PHP Type Hinting In Functions

10th July 2014
By Alister Sneddon

Don't you hate it when PHP stops listening to type hinting in your function parameters? I came across this strange issue with the Elgg frame work.

Long story short, the parameters in my functions where not forcing the type which was required. Take for example the following code

function get_money_then_get_bitches(ElggUser $user, array $extra_params) {
	$to_return = array();

	// Amazing code which updates the array and returns a standard type

	return $to_return;

In this case ElggUser is a new Object we have created, also we are asking for an array. However in PHP it is possible to pass in NULL or FALSE for both parameters. Heck you can pass in whatever the hell you want.

The problem we ran into was we did not always have the correct object. In the Elgg framework passing in 0 or an empty object it tends to pull back everything it can. So you would not end up with the money and bitches for that user, but for every user on the system.

Thanks Elgg, you dicks.

Either way this is not the frameworks fault, it is our setup. The issue is with debugging and dealing with multiple developers. It really is not good enough to leave a comment above your function. If your variable/parameter must be a set type then take it upon yourself to detect and deal with any problems.

I would always recommend setting a variable at the start of your function which you intend to return. The next thing you should do is check the parameters which have been passed in.

Let's improve the function we had before to account for any bad types. We will not force any type casting but we will check the type hint to ensure it is as expected.

function get_money_then_get_bitches(ElggUser $user, array $extra_params) {
	$to_return = array();

	// Make sure the variables have the types we need
	if(!$user instance ElggUser || !is_array($extra_params)) {
		return $to_return;

	// Amazing code which updates the array and returns a standard type

	return $to_return;

What happens now if you pass in NULL or the wrong variable type the script will return an empty array. This way your code will not break down because of unexpected values being returned. You know you will always get an array back, now you just check if the array is empty or not.

PHP is not your standards dad's Object Oriented Programming language. If you want to use PHP like C# or Java (etc.) then you will have to work for it.

Frankly you should be checking what parameters are getting passed into your variables. You can never assume the data which will come in is safe. You might be the only one using the function now but another developer might come in and use it to handle direct user inputs.

Never trust any variable, check all your parameters and fuck Elgg.

Do I Need SSH On My Shared Server?

10th June 2014
By Alister Sneddon

Five years or so ago you would be hard pushed to find reliable SSH for your shared hosting environment. However as web development has grown in popularity and the barrier to entry has lowered, SSH is becoming a more common offering.

Firstly what is SSH? Secure Shell, a secure encrypted command line interface which can be accessed remotely (normally.)

Now SSH offers a lot more freedom and flexibility in a standard server (assuming you are running a Linux distribution.) The idea behind using only SSH is you have no need to consume resources for a GUI when performing basic tasks. You can install everything you need and get a web server up and running using just SSH.

Now the major advantage to SSH is the complete and true flexibility to do whatever you need. However on a shared server they heavily restrict what you can and cannot do with SSH.

Now if SSH is part of the offering for your normal web service then you can start using it no problems. However if you are looking to change or buy new web hosting then should you be looking for SSH?

There are a few questions you need to ask yourself. Firstly do you require a service which does not have a good GUI? In which case SSH may have to be for you. A prime example would be using GIT on your server. If you are looking to install custom programs/software then you cannot use SSH on a shared server.

If you only need the bare basics of SSH and you are not paying extra for the SSH then by all means go for it. However if you are paying extra and do not require any command line features, you might be better off looking for cheaper more basic web hosting.

SimCity Digital Deluxe Edition Review

10th May 2014
By Alister Sneddon

Now the dust has settled after a problematic launch I feel I can talk about SimCity without being clouded in media/press arguments.

So the first thing you should know about me and SimCity is I pre ordered the game based on the SimCity I played 10ish years ago. There was a lot of noise regarding the always on DRM and the fact the game will not have a single player mode, however I have a good internet connection and don't mind setting my game to private.

I had to choose between ordering the normal dirty commoner version of SimCity or the SimCity Digital Deluxe Edition, I went for the SimCity Digital Deluxe Edition. What really sold me was the fact I would be getting Elizabeth Tower to place in the middle of my city and turn everything into London.

The first problem with the launch was the staggered release. Why for a purely online experience do I have to wait for my country to have a turn? The worst part was the people who brought the game, lied about what country they are in, got the game early and could select their local region to play in. So the whole idea of a staggered release was total bullshit. That left me with a sour taste but life isn't perfect.

Now as I am in the UK my release day was three days after the USA. Between starting my game and the USA launch the swarm of connection issues started to come to light. When I finally got home after work at 8:30pm I was unable to boot into the game. The start screen updater kept crashing. Sadly there was no help or support so I just had to re-install and keep on trying.

Around 10pm I got my first taste of SimCity. I was unable to boot into the tutorial city which is required before you can play the game as you wish. Due to the game struggling with the connections with my every interaction the experience was painful and unplayable. Around 12pm I finished the tutorial and was no longer experiencing connection issues.

For the next two hours I made my first city.

The city building is always exciting, you never feel cheated if you run out of money/power/water because that is your job. If you fail to make place for a building you brought then that is your problem and poor planning.

My biggest issue was the traffic. It just didn't work how I expected it to. The problems with the motorway that was passing through my city was insane. The traffic down my main street was a 24 hour stand still. I stopped playing for the night when 12 buildings burned down due to the fire department being stuck two buildings away in traffic.

Next day I tried to log back on, sadly the connection issues where back. I moved to a different server only to find my cities are not cross server. Also I had to play the tutorial again. My second city has far more success, sadly the traffic woes kept coming back. After a while your city has an explosion of growth. All of your major buildings start turning into skyscrapers. Suddenly your energy, garbage, water, waste and population become un-manageable.

This is the core fun of the game is the back and forward, trying to survive. It is at this point the game tells you to move to another city. I opted to keep on trucking.

What happened next was what I love and hate about SimCity. My power went out because the traffic was so bad the coal couldn't get to the factory. My population started to drop and my services shut down causing a bigger loss of money. I had to destroy my coal power plant and build a nuclear one. By that point it was too late, my city could no longer sustain itself, I had lost too many people and the taxes/factories where not making as much money.

Before my city went bankrupt I started a new city and then moved back to my original one, from there I moved all services to my new city as well as all my money. Then I went back to my new city. Suddenly everything was sorted, I could never go back to my original city out of fear it was run out of cash any moment. By playing in other cities the problems of my first city were frozen.

SimCity is still riddled with problems but if you want a SimCity game then you can only play a SimCity game. The multiplayer is shit and not live, the servers are crappy and you can expect them to pester you to buy add-ons. However if you want to play a city building game and suffer some real rage as it tears its self apart, buy SimCity.

Maybe wait till it gets a little cheaper

When Should I Use A PHP Framework?

20th April 2014
By Alister Sneddon

An interesting question at my last job was raised in my direction. I was asked for some consultancy advice on how to improve the PHP development for future external projects. To give you some background the projects should be promised as waterfall development and quickly boil down to rushed agile fixes and changes. There were no development standards or any real development plan.

My first suggestion was to create a development standards document for the programmers. Once a standard to compare work is in place you start to create realistic goals and understand the quality of work VS timescale. My second suggestion was to implement SVN. If nothing else this would help enforce a structure.

While helping with the development documentation and implement/training users with SVN I was asked my opinion regarding classes in PHP. Now classes do work in PHP, however it is arguable in smaller projects if a library of global functions is more useful when you have no real grounds to build classes. I explained that due to the skill set of the programmers and the size of the projects he would suffer if he went "the whole nine yards."

After a few meetings as was asked what "the whole nine yards" really entailed for me. I said that the inclusion of a PHP framework in their development strategy would be going all the way.

This brings me in an interesting point, would they have seen any real improvement over the quality of their code by bringing in a PHP framework? The development work was almost always ad-hoc and normal not performed by trained programmers; more often than not it was anyone who would pick up a PHP book.

By using a framework they would go against the very reason I warned against using PHP classes, they would raise the entry level to who would successful modify the code. A major issue was changing the code and not understanding the impact it would have across the project. When you deal in single pages it is extremely easy to isolate problematic code.

With the implementation of the SVN going successfully they would be able to track where and when the issues happened but that does not means that would be able to work around the problems faced.

Looking back with hindsight it is clear to me that a PHP framework would not only hinder their development but would also create a greater divide on their resources. Higher entry level to understand the code might come with performance improvements but it will heavy restrict the employees you have which can contribute.

Ideally in a company where you do require PHP development you will hire a dedicated developer, they will be able to call the shots regarding PHP frameworks and the usage of classes. However as their only developer was leaving with no replacement it would be short sighted to believe the hobbyist programmers would successful contribute. This is not to down play the abilities you can learn when teaching yourself but a realistic opinion of a professional VS someone who is going above their job description to help.

While picking a PHP framework it is important to consider the learning curve and who will be working on the project. As much as I feel I have moved on for completely separate PHP pages written independently of each other, in that work environment the ah-hoc speed in which pages where modified and created called for such a practice.

While many attempts were made to unify the source code the project was simply too large, this was also hindered by the fact multiple users had attempted a "from scratch" approach resulting in more fragmented code.

The inclusion of a PHP framework would not only have called for a massive rewrite of an unknown amount of code but also the knowledge for someone to understand uncommented code from two years ago against legacy systems.

While PHP frameworks come with a truck load of advantages even when you read up on the different frameworks available they all support the same methodology.

PHP frameworks are fantastic however they are like tools on a work-man's belt. It is up to the work-man to understand when to use each tool. Your screwdriver might fix all of your current issues but it is not suited to deal with nails.

When consulting PHP development it is as important to understand the current skill sets and resources available as well as the desired outcome.

Secure PHP, MySQL and jQuery AJAX Login

5th April 2014
By Alister Sneddon

Throughout my time developing login's I have never made a real AJAX login that covers all my security concerns. Now a login/registration system I consider the bread and butter of any web developer, and AJAX login tutorials are all over the internet. Yet when it came to making my own AJAX login I found myself worried about how secure it really was.

The basics of a dynamic login system are as follows:

  • Main login page
  • Another page to handle incoming requests and respond with XML or JSON
  • A good JavaScript framework because doing it from scratch gives you little benefit (normally)
  • Your collection of logins, normally a database

What happens if your end user is looking at a login form, then they enter in their details before pressing login. Once they have kicked this off your JavaScript comes into play, the button that would normally start the POST process has some JavaScript functions assigned to it.

The JavaScript will then go and pass the login details to your other page, this page responds as if it was accessed directly like any other web page. The JavaScript then carries this postback information and transforms it into something we can use (turns XMLs/JSON into objects to access in our code.)

Now with the postback information the JavaScript will work out if this has worked or not. Depending on the yes or no that came back the JavaScript will display a message to the user.

This is all well and good however there are a few more complicated issues for what I wanted to achieve.

These where my objectives:

  • Lightbox that will prompt the user for login details, this lightbox needs to be reusable from any location on the website.
  • Upon a successful login the user will be redirected to the "home page" for logged in users.
  • Upon failure the lightbox will be updated with what details are missing.

This may sound very simple however I had one major issue. The successful login had to redirect the user. My problem with a redirect is I do not have the option to POST values when redirecting the user. Any values I want to push across must be done via GET. My second issue is due to the way my PHP framework was constructed I am unable to assign a session or cookie to say the user is logged in.

Another issue is the highjacking of logins. While I can do my best to encrypt the username and password of the user in the AJAX process, how can I assign them a value which links them to their account without compromising their account? A common issue often overlooked is shared computers. Using an insecure GET can result in users having their accounts abused by the history function of most browsers.

So how can you get around these issues?

A very simple solution is to use a token. Here is the plan, expand the database to hold a timestamp/datetime as well as a random 64 random character string. The idea is the first request that comes through will not only respond with a success or fail but also with the token assigned to that login.

The first POST of data will send the username and password to the waiting page, this waiting page will check the login details, if it finds a match it will update the row with the current datetime as well as updating the randomly generated token.

Now we will respond with a JSON success or failure, the failure contains the message of why it failed. The success will also respond with the token.

Once the token has come through the JavaScript will redirect the user and pass the token via the URL (GET.)

The redirected page will then simply look at the token and check the timestamp, once a valid record has been matched we then assign the session and deem them logged in. This extra security given by the token allows us to be more flexible.

Hungry For More? RSS Feed