Amateur Protagonist Blog

  1. Do I Need SSH On My Shared Server?

    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.

  2. SimCity Digital Deluxe Edition Review

    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

  3. When Should I Use A PHP Framework?

    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.

  4. Secure PHP, MySQL and jQuery AJAX Login

    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.

  5. Amazing Game Ideas That Need To Be Made

    Some game ideas are so amazing that no one dares to take them on. Here are a few of the most amazing game ideas I have but not the time to complete. Feel free to poach my ideas like the bottom feeding pawns you are.

    The Ex - A Game About Getting Over It
    This is a rouge like first person emotional interactive drama. You have broken up with your ex but you stay friends. She was cheating on you the whole time and they are set to know get married as you are out the picture romantically.

    The game follows you supporting your ex as everything goes perfectly in her life, all the time you have a sanity and friendship meter. If the friendship meter reaches zero (you didnt spend enough time with her or are mean.) then she bans you from the wedding and spreads lies about you. The game over screen is her husband beats you up in an alleyway and leaves you for dead. You can crawl around on the floor but cant leave the alleyway. The only way to end the game at this point is to power down your computer.

    The other meter is the sanity meter which goes down by spending time and being nice to your ex. If it gets to zero then the game ends with you in a broken down home drinking vodka, this is all you can do. Every three drinks the character stands a chance to break down in tears. The only way out of this screen is to turn off your computer.

    The game sees you playing best man, not sleeping with any of her friends or anyone that is part of the wedding. You have to keep secrets and wish every to be happy. The best outcome in the game is you get hit by a bus at the end of the wedding. The game is also score based on how fast to reach to questions and tasks. There are high scores to keep the game competitive.

    Ragdoll - You Are Not The Player
    This is a Kinect only exclusive. In the game you have to move in time with the commands that show up on the screen. The only catch is on your monitor is a fat overweight unemployed pervert. Then sit on their bed playing the game using a controller. This translates into what you have to do in the game.

    You can choose between playing a shooter, adventure or MMO game. For each of these you can choose how good the player is, the worse they are the more often you have to redo the same sections.

    Also as an added bonus you dont get to see the game you only get to move as told. This game will also include day one DLC with is multiplayer. One player plays a normal game and the actions of the protagonist you have to follow along with.

    Depending what you select the player may make you do embarrassing poses while pleasuring themselves. This would be designed and done in such a way to be as disgusting as possible, if you can make someone throw up then you are on the right track.

    Power Down Land - The Trails Of Time
    This is a timeless classic, a 2D side scrolling plat former. In charming and non-opposing 16-bit style the characters will jump and run their way to the end game. It is a simple and easy game designed for casual play. The games length is around two hours with no real new mechanics, just a fun one time run.

    The twist is very few people will ever complete the run. The game will randomly close, this is a completely random chance whenever the game timer clicks over. It is roughly a 30% chance. This chance is rolled whenever the user does an action or a second passes.

    This game also features party mode when up to 16 players can all join in to complete the game. The game also is perma death with no save points. When the game closes it completely closes, on the Xbox the machine shuts down and on the PC it will close the window.

    The end of the game the player gets to see a random woman flash them, also the women is too 16-bit as to not break the style of the game. There is nothing else to this game.

    Crowd Sourced - The Interactive Free Help
    In this fourth-wall breaking experimental title the user will program a computer game. This is a pure multiplayer experience. Users are not named and have no interaction with each other but a score. The idea is in four hours the randomly teamed group must produce a game. Over the next two weeks a panel of random players will review the game. They each score it out of 10, this directly adds score to the players who made the game.

    The biggest part of the game is every six months a selection of the highest rated games get reviewed by a larger player base. The winner of out these games will each receive $60! Yes thats right its the game that pays its players BACK.

    Also all the code produced is owned by the Crowd Sourced developers. This means if this game is not a massive hit you have tones of stuff to make the next big it, all for $60 every six months. What a great deal!

    Well that is a big list of pure gold if I say so myself. I look forward to seeing these hits on stream and xbox live arcade over the coming weeks.

  6. Helpful Tips For Handling Customers Financial Details

    Now everyone knows when you handle someone elses money or financial details you have to be careful. If you are too lax you could give away their details or money to the wrong people. However there are a few banks and companies which have taken a no-shit approach. I am sure we are all very thankful for the delays caused by the high levels of security regarding when I can access their website, one day.

    If you deal with overseas customers the first and most important factor to consider is a simple one. Different time zones, how can you maintain high levels of customer service if you are asleep? You could tell your customers that their requests will not be dealt with until next business day in your own time zone. If that scares you, then you could simply not function outside highly restrictive business hours that match only your own country!

    Why should I be angry at the six hour window I have to transfer money overseas from an account I own? Hell its not like England and Australia can have a 12 hour time difference or anything. Oh wait, they can totally have a 12 hour time difference. So guess what I am doing during your business hours? Relaxing the fuck out.

    Even better is this service does not run on weekends or public holidays, after all we all can clearly see the chaos that putting a request in without the monkeys typing it out would cause. Its not like this is the internet or anything?

    Sometimes you need to go into your bank to sort out some details. You know the types of moments when you simply have to go into the bank, the moment you have called three different people and they all say go in and see your bank manager. My bank manager? Heck I met the guy once and he couldnt pronounce my last name, oh and he is always busy or on holiday. Maybe I should go to the bank and stand there until my personal bank manager shows up to help me with my problems of pounds and pennies.

    So how can you as a bank make this as easy as possible? Well like with the overseas method there are ways around it, however if we cant offer the service maybe we can cover it up by simply not being open! Genius, everyone in the boardroom screams. We simply close the bank and open in crazy peak of business hours so its really bad in the bank and only people with no jobs can visit us.

    Now this happens with a lot of banks so its hard for me to pick on them for that. I mean its not like its the government regarding your tax file number and where your tax rebate goes. Oh wait no its them fuckers too. I have to take a day off work and book an appointment two years in advance and bring everything from a picture of my birth to a blood sample so you can send me the bit of paper that is charging me more money? Did you guys every study anything ever about anything? Why the fuck would I drag my dick through shards of glass only to have you squeeze a lemon over me? Why not make it easy to encourage me to be on top of this?

    Still in between people just shutting down important services designed for customers who need it at all hours and having bricks and motor shops closed, its not like you are hiding my money?

    Let me just go check my superannuation online, by having my online banking and super linked into one I can see it all any time 24/7. I mean what an amazing system, huh its not showing up. The account is there but no money is showing up. Maybe I can click the name? Nope thats not a link. Oh I see to get access for a number of how much money is in that account I have to go into my bank and ask

    But the bank is closed

    Fuck you.

  7. Minecraft 1.2.5 Server Running PVP Vanilla No Whitelist

    Our UK (London) based server provides you with the best Vanilla, fully PVP, no whitelist, always online, always up to date Minecraft Multiplayer Online Action. We pride ourselves on maintaining a secure no rules server. We do enforce a no mods policy however.

    What do you mean No Rules?

    We wanted to create a normal vanilla Minecraft Server that you could join without applying or paying for. We want you to play the game how you play in single player, only with friends.

    If no rules why do you not allow mods?

    We feel mods unbalance the game, everyone has an equal chance on our Minecraft Server. It doesnt matter if you are new or been playing from Alpha, our always free, always open server is welcome to you.

    Do you always have the latest version running?

    We currently have around a 3 or 4 hour delay from a new Minecraft Server Version being released to us going live. By running the standard vanilla version of Minecraft you do not have to worry about slowdowns or delays.

    Sounds great what is the IP?

    You can join in right now with the following details to our 1.2.5 Minecraft Server.

    46.20.119.7:30265

    Is the server full PVP?

    Yes it is! You can attack anyone at any time, we feel changing that fact makes the game dull and uninteresting. Once you have built your massive castle you need to protect it! From Monsters and Players!

    What is new in the Minecraft 1.2.5 Server Release?

    Now you can shift-click inside the furnace for after smithing as well as the direct connect remembering the last IP you joined (so you can come back to us even quicker.) Also there has been some changes to the TNT block, even with a flint and tinder you can punch a block of TNT to get it back (however setting it on fire will activate the TNT!)

    Also this new version is bringing in heaps of bug fixes, so be sure to have fun and join the forums!

  8. When And Why Should I Use Static Functions?

    Now I am by no means the best developer, not the smartest or even the cleverest. I learn new things every day and this is one of the things I learnt some time back that I want to revisit. When I first started programming using Classes I heard about Static Functions but never used them. Yesterday I once again used a Static Function and it struck me that I done so without a second thought.

    Like many other programmers who are still learning what many would consider "core skills" I am always eager to try new things in my code, without my thought to if I require it. Part of being a better programmer is knowing when to use the right tools and techniques. The reason for this lengthy introduction is because I have fallen into the trap where I have a hammer and everything looks like a hammer.

    Onto Static Functions, now I assume you are aware of the basics of a Class in programming. For this article I will post any code in PHP however the idea and reasons remain the same for almost all Object Oriented Programming Languages.

    First to make use of a function inside a Class you are required to declare the Class (normally with a new statement like so.)

    $fish = new Fish();
    

    After that you have the class (also known as the object.) in your code and accessible. From here you have access to all public methods and functions within that class, because you have declared it. However lets say you want to check if the name of the fish is already taken. For example:

    $fish = new Fish();
    $fish_name_free = $fish->is_name_free('carp');
    if($fish_name_free) {
        echo 'party';
    }else{
        echo 'do not worry, there are plenty more fish in the sea!';
    }
    

    Now the code above can easily be improved in a number of ways (for one there really is no need to assign the return of is_name_free to a variable.) however this is a simple example which shows that sometimes creating a new object or class is overkill. What if I told you we never make use of the fish object / class ever again in that section of code?

    There really is no need for use to declare the new class /object for such a simple task. Now this is just one example. How about this one:

    $endangered = FALSE;
    $fish = new Fish();
    $fish->load_fish('carp');
    $locations_of_fish = $fish->all_locations();
    foreach ($locations_of_fish as $location) {
        if($location->is_endangered()) {
            $endangered = TRUE;
        }
    }
    return $endangered;
    

    Again this code can be improved and really is just proving a point. With the code above all the code we are using can be inside the class, inside protected functions. Do I really need access to all functions I have listed? What if I need to do this pattern in multiple places? No good creating a new function for it as I still in to instant the class / object every time.

    A Static Function allows you to make use of the class without ever declaring the class. Now if you need to interact or use the class in multiple ways a Static Function should be avoided. However in both cases I displayed really all I need is a TRUE or FALSE back from the class. I am not going to use the class anywhere else in that script. It is just a one off reference. Also what if I need to use these scripts in multiple places? If I change how my class works I could break a lot of stuff.

    Here is the first example but as a static function.

    $fish_name_free = Fish::is_this_name_free('carp');
    if($fish_name_free) {
        echo 'party';
    }else{
        echo 'do not worry, there are plenty more fish in the sea!';
    }
    

    Again that code can be improved but as a basic easy to reuse line it makes sense. And now the second script as a static function, even less this time around as we would move all the code to inside the class.

    return Fish::is_endangered('carp');
    

    That's it. Now you can reuse that piece of code without worrying about making future changes. Now note that I did not reference any updating, deleting or editing of data in my examples. Generally speaking a Static Function is very handy if you need minimal data back and don't want to be rewriting large chunks of code everywhere.

    Now the temptation is to simply have a Static Function that returns the object but doesn't create the class. So basically you can access all the variables the class would normally set but none of the functions. Unless you really have to lock down your code and don't want people using your functions this is not a good idea. You will end up limiting yourself unless you have a very good reason to use the Static Function.

    Some examples of Static Functions I have seen range from simply performing checks if something is TRUE or FALSE and even the crediting of customers' accounts, if there is an error the Static Function just returns and exception prompting the client to get in touch with the develops (because there is very little that could go wrong.) the reason it was in a Static Function was so it could easily be called and if any changes were made to the class it would not affect the customers getting their credits, because that is still called in the same way.

    Anyway I hope you find Static Functions as exciting as I do!

  9. Helping You Understand JSON And Why We Love It

    So who is this JSON fella and whats he doing fooling around in my PHP. Well first thing my English Chap is lets get the tools very clear here. Firstly, if you are going to be making an AJAX application chances are you want to use JSON to transfer the data in between requests.

    So for lets not reinvent the wheel and end up with a square. I mean thousands of years of evolution and the wheel is still round. So lets get it right with our tools to help us debug and get writing some sexy AJAX using JSON. First ensure you are using Google Chrome as your browser. The debugging in Chrome is extremely fantastic, sure you can get FireFox and then get FireBug plugin, I find most people who do that than get Chrome also enjoy dicks in their arse. Just sayin'.

    Now we want to use jQuery as our JavaScript "framework" the reason for this is jQuery is polished and wants to do everything it can to make our lives sexier. Simply using jQuery day to day will increase your chances of getting laid (not verified.) Now what we want to do is basically an AJAX post/get to a PHP which returns some useful information that we then display on the page.

    So lets clear up what JSON is and why we are not using the AJAX XML. JSON stands for JavaScript Object Nipples. The important bit is Object. JSON works with JavaScript Objects, so you can serialise a form into an object or if you use a PHP framework like CodeIgniter chances are you are already using objects in your code. Well I hope you are.

    So lets come up with some example that we can use JSON for Erm Should of done this before hey? Why not get a random insult display thing? I like that idea. We will make a button that triggers a JSON request to pull back an insult. Or something, lets see what happens.

    First lets make a basic index page, something fun maybe. Tell ya what lets shake this up and make the index page HTML, so make an index.html file. Be sure to reference jQuery in your header as well, just get it from Google than dicking around with downloads for now. Here is my code.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>Damn Girl - I Like The Way You Move</title>
    <style>
    * {font:14px verdana;padding:0;margin:0;color:purple;}
    body {text-align:center;margin-top:50px;}
    h1,h2 {font-size:18px;margin-bottom:7px;}
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    </head>
    <body>
    <!-- We will play around with these! -->
    <h1 id="header"></h1>
    <h2 id="subheader"></h2>
    
    <!-- Better have a button or something -->
    <a href="http://www.amateurprotagonist.com" onClick="OnShitBusta(); return false;">
        There Are So Many Things I Like About You
    </a>
    
    <!-- Feel free to delete the next bit, if you don't mind me hunting you down, game on bitches -->
    <p>I stole from AmateurProtagonist.com because I am a cheapskate.</p>
    
    <!-- Yeah I am putting script stuff here, deal with it -->
    <script type="text/javascript">
    // This means when the page has finished loading do this
    $(function() {
       OnShitBusta();
    });
    
    // This is a JavaScript function, you knew that right?
    function OnShitBusta() {
      
    }
    </script>
    </body>
    </html>	
    

    As you see here I have some JavaScript setup already. Now basically I am going to call the function we want on page load. So not only do you learn about your friend JSON but you learn about loading elements of a page after the page has finished loading. This may save your life on day. (Note it may not, but is helpful.)

    Note in my code the A tag that links to my site which has an onClick event. This call the same JavaScript function as the document ready. Also it has return false after it. Try clicking the link and nothing will happen. The return false stops it from working as a link, yet still activates the JavaScript function.

    Lets start by editing OhShitBusta to make a get request to a PHP file (which we will write in a mo.)

    function OnShitBusta() {
      $.getJSON("WhoMe.php", function(data) {
        $('#header').html(data.headline);
        $('#subheader').html(data.lovethemsubs);
      });
    }
    

    So he is a break down. getJSON is a jQuery function that takes a number of parameters. We have no need to send data so we will simply get data back. By using getJSON we are saying we are expecting a JSON postback from the PHP we are calling. This means we don't need to do any decoding or anything unexpected. We then take the data (postback from the script) and fill them suckas in. Now reloading the page does nothing but give you errors. You should get a 404 error in your network tab. If not you must be off track or some kind of God. I say off track.

    Now then, lets create this sexy PHP page. I will comment some of it so you understand it. Be sure to pay attention as lots of people get lost at this point. (PHP file is called WhoMe.php)

    <?php
    // We store stuff in the array
    $result = array();
    // The key is how we reference it on the other end, remember what we were calling from data postback
    $result['headline'] = 'But Most Of All';
    $result['lovethemsubs'] = 'But YEAH Most Of All';
    // Encode it like you have never encoded before
    echo json_encode($result);
    ?>
    

    Now this is pretty easy, so after you complete the page save it and then rerun your index.html file. Nothing happens, then the page finishes loading and BAM. Code bitches. Have a look at the network tab and you can see the data coming back from the request. Now in situations where you have tones of data or information that is hidden unless requested then using this method of loading (maybe even on click than page load) can save you seconds when it comes to showing the user what they really want. Save the extras unless they need them.

    Now this is pretty unimpressive. You see how easy it is to use JSON in the JavaScript, it is already an object so JavaScript loves it. Let's make the PHP more interesting so when you click the link something happens.

    <?php
    // We store stuff in the array
    $result = array();
    
    // Make this random
    $random = array(
    'Bitch Please',
    'I Like The Way Your Friend Moves',
    'I Hate So Many Things About You',
    'I Hate The Way You Smell So Strong',
    'I Like The Way You Cant Dance',
    'I Like The Way You',
    'YEAH Most Of All',
    'But Most Of All',
    'I LIKE THE WAY YOU MOVE',
    'I Wish You Didnt Put Your Hands In The Air',
    'I Wish You Didnt Stare So Much'
    );
    // Get a random element for each line
    $headLine = array_rand($random);
    $subLine = array_rand($random);
    
    // The key is how we reference it on the other end, remember what we were calling from data postback
    $result['headline'] = $random[$headLine];
    $result['lovethemsubs'] = $random[$subLine];
    // Encode it like you have never encoded before
    echo json_encode($result);
    ?>
    

    Nothing to be scared of here, just creating a random array which we then select an element (key/index) from and then call that element for each line, I find this combination of lines is pretty funny what comes up.

    So load up the page and see the random message. Then click the link and it will change! Keep an eye on the network tab to get an idea of what is happening and what the magic happen.

    I LIKE THE WAY YOU MOVE
    I may have been listening to this.

    My personal favourite that came up was:
    Bitch Please
    I Wish You Didnt Put Your Hands In The Air

    Hehe, anyway I hope this was a fun and different intro to using JSON in your PHP projects to load elements of a page after the page has been loaded as well as basic jQuery usage. No need to thank me, just give me all of your money.

  10. GIT vs SVN In NetBeans The Basics - What Not To Do

    Currently where I work we use SVN for our version control. This makes a lot of sense for the original project. One main project which everyone should have the same code to, at no point should there be a conflict.

    Sadly the real world does not fit around perfect situations, to quote a co-worker. Nothing is perfect but that's ok. It was not long before the need for splitting and merging trees reared its ugly head. Suddenly using SVN seemed like the final nail in a coffin. Merging two trees in SVN is like getting a chocolate and vanilla ice cream cone and smashing them together considering the end result to be vanilla with a hint of chocolate.

    GIT luckily does a much better job of merging and managing code, it is also faster (however in general usage of larger projects it is not really worth mentioning.) Where GIT comes into its own is the merging. SVN has one centre point that everything references. GIT everyone has a local as well as a remote copy. You can play with your remote copy all you want then merge your local to the remote location to merge with everyone else.

    This is a good and a bad thing. The good thing is this method does not require a consent internet connection to commit changes (as they commit to your local until you push them to the remote location.) it is also good for the graceful merging of documents. This make three-way vendor merging very simple (not easy, three way merging is never easy, if anyone says it is, kick them in the fucking balls.) The bad point is because of the extra process (the local repo) there is an extra step involved in learning and using GIT over SVN.

    I can see the advantages of GIT and wish to learn more so I jumped in like the stupid person that I am. I signed up on BitBucket to get a remote repository for free (turns out you get loads more free too!) From there I downloaded my code from my FTP server. Now you can't simply upload code to GIT as a first commit.

    One does not simply
    ONE DOES NOT SIMPLY UPLOAD GIT FILES.

    I had to create a new folder and turn that into my local repository. Then I had to push the first commit from my local to BitBucket (nice and easy with push.) Then my files were all on the remote repository. Now I had to boot up Netbeans to use GIT and get editing some code.

    Now here is where I went majorly wrong, so I will say the way I think it should be done. My problem was I already had the code and I was attempting to simply say "Hey GIT here is my code keep an eye on that while I do unspeakable things to it KTHXBI." To which GIT gave me the middle finger and was all like "Hey why not fuck you?"

    So first you need to create a new local repository from NetBeans and then you need to do a pull/fork request on the remote server. From there you will get all your code and it will be correctly setup. I had no idea it was a twostep process. Remember GIT uses a local repo to do all the work which you then go outside of NetBeans to push your local to the remote.

    This is more involved than the more simplistic SVN. However there is an argument for both, in my personal example SVN would have been a better option, as internet connection and having my code in different places at the same time is not a beneficial factor for me. I was looking for version control of my own personal code.

    GIT however should be your first move for group projects, sooner or later merging will come up and everyone will look at someone and say "Who suggested this fucking crap?" That said it is worth having some experience in both, like most things in programming it is more about knowing the right time to use one of your tools than picking the best for everything.

    When you have only a hammer everything looks like a nail.

    When you only have a screwdriver everything needs to be screwed, which is a chat up line I have yet to see work.

Older PostsRSS Feed