From the blog

Welcome to the blog, I tend to blog about work related things, so you'll often find useful snippets of code for Wordpress amongst other things.

How to copy a database with mysqldump from remote server to another via ssh

How do I copy a MySQL database from one computer/server to another?

Short answer is you can copy database from one computer/server to another using ssh.

SSH is the only secure method of transferring so i will not even talk about using mysql.

Use ssh if you don’t have direct access to remote mysql server (secure method):

$ mysqldump db-name | ssh user@remote.box.com mysql db-name
OR
$ mysqldump -u username -p’password’ db-name | ssh user@remote.box.com mysql -u username -p’password db-name

You can just copy table called foo to remote database (and remote mysql server remote.box.com) called bar using same syntax:
$ mysqldump db-name foo | ssh user@remote.box.com mysql bar
OR
$ mysqldump -u user -p’password’ db-name foo | ssh user@remote.box.com mysql -u user -p’password’ db-name foo

Tagged: 1 Comment

Php preg_match simple string examples

Due to ereg being deprecated in php 5.3.0 + I decided since it was at the core of one of the most heavily used functions on a site of mine, to make the move to preg_match this afternoon. More for my own benefit than anyone elses im just blogging it for future reference.

Some simple preg_matchs I wrote this evening to replace some old ereg functionality.

Firstly a simple match whole string of numeric and alphanumeric characters also including: space, (!), (_), (-), (|) and being between length of 1 and 200 characters. Like I said simples icon wink Php preg match simple string examples


if(!preg_match('/^[-A-Za-z0-9_!| ]{1,200}+$/',$data)){
return false;
} else {
return $data;
}

Heres another: This time only numeric characters are allowed, with a string length of 1-30.


if(!preg_match('/^[0-9]{1,30}+$/',$data)){
return false;
} else {
return $data;
}

Also like i said more for my own benefit than anyone elses, but feel free to comment if you’d like more examples.

Tagged: 1 Comment

Programming large scripts in javascript using object orientated style coding

This week whilst coding a large javascript / jQuery script for one of our online games which started to grow to an unmanageable size and needed to be compartmentalized I decided to review my techniques.

Previously for scripts which were quite large I would create an object which contained lots of different methods like so. As you should already know in js its all about scope.

So here’s what I used to do:

function page(){
this.funcName = function(param){
alert("hey man this is a cool little function);
}
}

I’d then go and call this function into the page like so.


var mypage = null;
function init(){
mypage = new page();
}

$(document).ready(function(){
init();
});

Which then gives you full access to call objects of page via access of the mypage var.

This works fine, but meant that all of my code was inside one very big ass object. Not so great. 2000 lines later, even less great. 2000 lines later and finding out I need to use aspects of it for one page and not another, awful.

So I set out to find a change in practise and this is what I came up with. This is not a new technique, nor do I personally claim I came up with it. Just my take on things I read.

My new plan was to create a base script, which was then interfaced by several smaller scripts dependant on the view.


Post={
newmsg: function(){
alert("hey there man, how goes it?");
}
};
pgAjax={
request: function(options){
//could add some extension of the defaults for a jquery ajax call here
}
}

Hopefully from the above you can start to see its benefits. By compartmentalising it, I made it much easier for me to keep code housed in segments, the objects can also be called via inline commands like onclick=”Posts.newmsg();”

I interface the base with a series of smaller files based on the view, similar to this.

leadview.js
$(function(){
$("input[type='button']").click(function(){
Posts.newmsg();
});
});

Obviously this is massively simplified, hopefully this might help though. Feel free to leave a comment if you wish for me to expand on this.

Tagged: 2 Comments

How to reselect a default option in a select box on the fly with jquery

How to reselect a option on the fly in a select element using jquery.

This always annoys me a little bit as I seem to have a tendancy to forget the solution, so I thought i’d just blog it this time round for future reference and hopefully it might also help someone else.

What I need it for quite often is setting a select box back to the default when using the select box to repopulate other elements on the page ie using the .change() function on the select box element.

Normally my solution for resetting it now is just this.

$("#elementID option[selected]").removeAttr("selected");

This will just set the focus back to the selected=”selected” element in the original html. Of course you could extend this somewhat further and perhaps actually set a new one if your list is not populated dynamically like so.

$("#elementID option[value='Today']").attr("selected","selected");

Hopefully this will be useful.

Tagged: Leave a Comment

Removing and Replacing Apple iMac 8, (aluminum) hard drive.

First and foremost this tutorial covers from personal experience how to remove the outer shell of your iMac safely to get down to your main board.

Yesterday my hard drive in my iMac decided to fail on me for some beknown reason.

My symptoms and the apple support help page

Tried holding c during boot as suggested it might try and relocate the boot drive if it has lost track of its start up disc.
Secondly tried inserting the mac os x install disc and finding the hard drive in disk utitlity to repair.

If either of the above work for you, then you really don’t need to keep reading.

However in my case both of the above failed! My hard drive wasn’t even visible in the selectable list of drives recognized. (Bummer I thought).

My first thoughts were that if it were a normal computer i’d just open it up and see if it were some loose cabling or something visibly wrong with the hard drive. However as you should by now know, imacs are a all in one unit, meaning they are complexly put together and compact. Upon googling gaining access to the main board on an iMac, I immediately thought to myself do “woah this looks a bit complicated” and “maybe I shouldn’t do this”. Having now come out the other side i’m glad I didn’t let face complexity phase me.

I found this youtube video particuarly helpful, when looking into taking apart my iMac http://www.youtube.com/watch?v=2YsCTNVEYt8

In written format these are the steps that I took to gaining access to my main board and replacing the hard drive with a new Samsung f1 1tb 7200rpm drive (which was a bargain at only £43 from ebuyer) icon smile Removing and Replacing Apple iMac 8, (aluminum) hard drive. In replacing it, I traded it for a Western Digital 500gig drive that came with the iMac from new just over 18 months ago.

  1. First of all remove the ram slot at the bottom of the unit, turn it on its back and lay it flat on the desk, its only one screw and its pretty simply just a case of taking it out and removing the fascia it holds in.
  2. At this point you might also want to remove the ram modules for safe keeping, you can do this by first removing the black protective tape, then using two small flat head screw drivers and just wedging them either side of the module and levering it out gently.
  3. Next find a suction style pad, if you have dent pullers they will work, but we found the best size and most effective suction pad was actually for a car sat nav (my suggestion here is just get creative – any decent suction pad will do)
  4. Put the pad to the screen in the middle at either the left or right hand side it doesn’t matter, or if you wish you can use two, one on each side and do both at the same time.
  5. You will find the plastic screen comes off really easily, take it off gently and place it to one side.
  6. This will reveal the fascia screws, which are 8 torx screw size 8.
  7. Un-screw all of these, this will make the fascia loose and removeable, so go ahead and remove it, at the top you will find that the webcam lead will need disconnecting before removing.
  8. Next you’ll be wondering, do i really have to take the TFT out to get to the main board? The answer to this is yes you will!
  9. Its simple though so don’t worry too much. Another 8 screws and you will release the tft monitor, be careful when lifting this up though as there are 3 leads connected to it, it will help you to have someone else hold the TFT screen whilst you unplug it for care reasons here.
  10. Once you have un-screwed the TFT and un-plugged any cabling to it and made a mental note of what came from where, simply lift it up and put it somewhere safe.
  11. Now you will have access to the whole main board icon smile Removing and Replacing Apple iMac 8, (aluminum) hard drive. it should be fairly self explanatory as to whats what.

Removing the Hard Drive

  1. Identify the hard drive and remove the SATA cables and the thermometer.
  2. Handily apple have installed a nice easy to remove little catch, which you just pull down to release the drive, simply do that, remove the casing when detached from the mainboard and attach it to the new hard drive and simply replace it.

I’ve now attached some screenshots of the whole event.

20101102 eyqf11x6e931j55qx2e8ahfqxa.preview Removing and Replacing Apple iMac 8, (aluminum) hard drive.
Uploaded with Skitch!
20101102 gddimyxjssjgt5adx17ke7djqm.preview Removing and Replacing Apple iMac 8, (aluminum) hard drive.
Uploaded with Skitch!
20101102 tnb2f28eadeqe54fm7xsasjjm1.preview Removing and Replacing Apple iMac 8, (aluminum) hard drive.
Uploaded with Skitch!
20101102 b23i24g83wsbhb4j8rsf631b13.preview Removing and Replacing Apple iMac 8, (aluminum) hard drive.
Uploaded with Skitch!

Tagged: Leave a Comment

PHP Weighted Random Choice & Selection Remove / Replacement

For something I have been doing in a php project of late, I needed to weight an array of values and as I go round and select the values remove the value or -1 from the weight depending on how many of the value are left in the weight.

If you have any improvements or suggestions then id very much like to here them icon smile PHP Weighted Random Choice & Selection Remove / Replacement

$starttime = microtime();
$startarray = explode(" ", $starttime);
$starttime = $startarray[1] + $startarray[0];

/**
* weighted_random()
* Pick a random item based on weights.
*
* @param array $values Array of elements to choose from
* @param array $weights An array of weights. Weight must be a positive number.
* @return mixed Selected element.
*/
function weighted_random($values, $weights){
$count = count($values);
$i = 0;
$n = 0;
$num = mt_rand(0, array_sum($weights));
while($i < $count){
$n += $weights[$i];
if($n >= $num){
break;
}
$i++;
}
return $i;
}

function recalc($val,$values,$weight){

//two steps to consider here, -1 from the weight and if the weight is <=0 unset both the value and the weight.
if($weight[$val]-1<=0){
unset($weight[$val]);
unset($values[$val]);

$new_values = array();
$new_weight = array();

foreach($values as $k=>$v){
$new_values[]=$v;
$new_weight[]=$weight[$k];
}

return array($new_values,$new_weight);

}else{
$weight[$val]=$weight[$val]-1;
return array($values,$weight);
}

}

//in the context of what im doing lets get this right.

$values = array(0=>"164-2",1=>"164-1",2=>"2-2");
$weights = array(0=>1,1=>2,2=>1);

//now we wanna select 4 values but edit them as we go round.

$find = 3;

for($i=0;$i<$find;$i++){

$val = weighted_random($values,$weights);
echo $val.' | ';
echo $values[$val].'
';

list($values,$weights) = recalc($val,$values,$weights);

}

echo 'The new weights are ';
print_r($weights);
echo '
';

$endtime = microtime();
$endarray = explode(" ", $endtime);
$endtime = $endarray[1] + $endarray[0];
$totaltime = $endtime - $starttime;
$totaltime = $totaltime;
echo "This page loaded in $totaltime seconds.";

?>

Tagged: Leave a Comment

Do’s and do nots of business websites

Earlier today I decided to have a little think about what makes a business website great and what, well, really doesn’t! The very first thing I thought was it’s, making a wonderful looking website, so wonderful infact that all your clients will immediately be like woah these guys really have talent, I want my site designed by them. Essentially this is a good way of thinking or at least the correct mindset. I’m sure that, I’m not alone in thinking this! However, there’s a little more to a wonderful website than it’s cover. As the sayings go “beauty is only skin deep” & “you cant judge a book by its cover”.

So what really does make a wonderful, purpose serving business website? Good question.

Here are some Do’s and Do Not’s from my own personal experience and view.

Do’s

  • Do make your new site look really eye catching, but more importantly remember the user experience. Don’t make it so eye catching and out there that the average client or onlooker is immediately put off, and won’t bother to find the information they want. Make sure navigation remains simple, nice menus rather than hidden buttons and links. Remember if you look at alot of the most successful websites used by the biggest base of users out there, most of them won’t have any massively out there or exciting UI. They will all have basic, easy to remember, easy to use UI and thats important to remember! Users are thickle and generally make there mind up about a site in the first minute of being on it.
  • Do make sure you don’t hide important information behind too many pages of link depth, users will not want to siv through to much stuff to get to what they want.
  • Do make sure you don’t forget thats its all very well having a nice new site that utilises jQuery or other javascript language to minimise the amount of pages you have in your website, but remember the consequences of doing so. Less content to be ranked, less pages to be indexed and altogether less chance of search engines picking up your site well (this particuarly applies to small businesses, intending to rely on search engine traffic to drive business).
  • Do make your unique selling points readily available.

Do Not’s

  • Do not Hide important information about who you are behind, to tricky or clever UI.
  • Do not hide information that you want a client to see at all, make sure they are confronted as early as possible with the information.
  • Do not make UI’s to clever, that anyone but the designer will struggle to know what to do.
  • Do not make the entire website based on one page (if you wish to rank well for numerous things in search engines).
  • Do not play any annoying sounds on load of your homepage or any other page, a customer who is confronted with loud sound all of a sudden is likely to first port of call close the browser window, that plus its just plain annoying.
  • Do not bury contact forms and ways to get a quote behind a form asking for an information overload, carefully design it so that you get exactly what you need to a minimum.
Tagged: Leave a Comment

Opening Up For Advice

Over the last year I’ve been constantly if not more than constantly trying to ask myself, are we doing things the right way?

There are a million and one different ways to accomplish some of the tasks we undertake on a day to day basis.

Preferences are always going to change and perhaps there is not one best method of practise at all.

Im trying to open myself up here to ask anyone in the context of my company and I, what the next step could be.

We build lots of text based games, driven by simple php and mysql, php = mixture of functions and classes. I generally don’t like the idea of php frameworks for use with game design of this type, as games quickly grow code base hugely and you get the annoyingness of extra overheads in load time. However im very much open to new ideas as to how we could improve code. Maybe a new language, or maybe a different approach.

I wondered really if anyone out there has built a complex game on anything other than there own custom php code and mysql (obviously in the context of text based, browser based games and improving on php).

Also we do alot of client work, nice designs, baskets and checkouts all the usual stuff. Does anyone use a particular framework for similar things and found its really good? We spend far too much time repetitively coding things like checkouts and baskets for each customer.

Ideally its all about taking things up a notch and what could improve what we do.

I’d also like to know if anyone uses any particularly good checkout bundles or companies, to manage all there payments really easily. Ours is very disjointed atm. With payments for different sources ie mobile, card etc all being taken by different companies.

Tagged: Leave a Comment

Connecting To Server With Putty Using SSH Keys & Port Forwarding

Quick and dirty tutorial to connecting to a remote server with ssh keys and putty.

Firstly you need to download putty and puttygen which can be found:-

Here – Putty Client
&
Here – PuTTYgen

Yes they are both the same page, you will find the download links for both here.

Once you have downloaded both the clients you will need to first generate yourself a key using the puttygen and then save it out to a file in a location you will easily be able to remember. Remember you need to generate a public and private key, but the private is the one of most use to you.

Im going to largely breeze over adding your ssh key to the server, as you should really know how to do this already before attempting to use putty with ssh keys and port forwarding.

Open up putty, enter the host as whatever it needs to be either an ip address or a host name like google.access.me.com and specify the port as 22 if it isn’t already.

Then head down on the left hand menu to the SSH list which will probably be shut, click the plus to expand the list and head to the AUTH tab. Here enter the user you want to auto login with and specify the path to your key using the browse file function.

If all is correct head back to the “session” tab and move to the right hand side, and save your settings under any name you like, this is to ensure that you can pick up where you left off when returning to the same connection again.

Now you have done that hit open and you should with any luck either be presented with a enter passphrase for key authorisation, enter that and youll be in.

Port Forwarding Mysql From Remote To Local

Should you like us sometimes want to dev locally to a remote database, Putty can be used to tunnel a mysql connection from a remote server to your local mysql port. To do this in most cases simply forward the following or well at least for me.

Navigate to the following.
Connection -> SSH -> Tunnels -> Options Controlling Port Forwarding

L 3307 port destination to
the remote database.
remote.db.name.net:3306

Add that in, head back to session save it and then open it and wollah you should now be able to dev locally to the remote database, by forwarding mysql to your local ports.

This is just a quick and dirty tutorial and not meant to be a fully comprehensive guide, however if theres something you want to know I may be able to help, so leave a comment.

Tagged: Leave a Comment

Simple Directory Protection with .htaccess

To deny access to a folder or directory, simply create a new .htaccess file inside that directory.

Then depending on the authorisation type you want to use you can make rules to allow or deny access.
View some examples below.

Allow by Ip

order allow,deny
allow from 85.189.58.21
deny from all

This denys anyone not on ip 85.189.58.21 access to your folder.

Leave a Comment