Posts Tagged ‘PHP’

PDO database layer

Wednesday, January 18th, 2012 | Tech

If you’re not using PDO in your PHP projects yet, you should be.

I finally got round to taking a proper look at it recently, and I’m really impressed. I managed to convert an entire open source project to it in under two hours! Granted, I was helped a lot by the fact that the PDO naming conventions luckily match up with the naming conventions I used in my original data access layer, but still, it was smoother than I expected.

PDO has some great advantages too:

1. It’s cross platform, so you can use it on a number of different database platforms including MySQL, MSSQL, Oracle, Postgres, SQLite and many others! All you do is enter the protocol and login details to the connection and it handles everything else.

2. It has prepared queries so you never need to escape anything again! You simple pass it some SQL with a series of question marks in, and an array of values those question marks represent and all the SQL injection negation is taken care for you.

3. If something goes wrong, it throws an exception rather than producing an error message.

4. It’s easy to extend, to add your own functionality. Just use Class MyPDO extends PDO and you can add extra functionality on top of it.

All in all, it’s a great addition to PHP and one I now wish I had gotten to sooner.

Testing multiple conditions in if statements

Friday, December 2nd, 2011 | Programming

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

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

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

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

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

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

The solution I have eventually come to is this:

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

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

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

Poker Stats Library

Tuesday, August 16th, 2011 | Tech

A few weeks ago, I wrote some tools which would help me out in getting to grips with poker, which in general I fail at.

It annoyed me because it should be fairly simple for someone like myself to get my head around the poker maths (well, it is, pot odds are easy), so even despite the lack of social understanding the life of a computer scientist brings, I should at least be able to achieve a level of averageness in the game. I clearly have failed to do this, and so I decided a bit of work on my basic strategy was needed.

As a result, I built an interactive tool which would teach me what starting hands I should play, similar to the concept of Basic Strategy in blackjack. It presents you with two cards and you have to say what position you can play them from, if any. It will then tell you if you are correct or not, if not it will ask you to try again and if so, it will move on to the next hand.

I also wrote a tool which allows you to select the cards you have, and using the same formulas it will tell you what position that hand is worth playing from. I’ve thrown in a few other simple odds calculations in there as well.

Of course, these won’t make you a great poker play by themselves, but it should provide a good basis to learn from.

Given the tools would otherwise just disappear into the depths of my hard drive somewhere, I’ve decided to publish the code on Github. Should you have any interest, you can download the source from the Github repository. It’s all written in PHP and should run out of the box.

Btw, the images below are screenshots, but the way they have been scaled down looks rubbish. They make more sense when you open them…

Calling the Brain Trust

Monday, May 31st, 2010 | Tech

Ok, here is the situation. I have a website which has two virtual hostnames pointed at it – domaim.com and sub.domain.com. They both point to the exact same location in the file system and serve the same content. However I need one of them to invoke a http authentication and the other not to.

The obvious solutions I see are…

Set up a rule in the .htaccess so it only requires a valid user when accessing the sub domain. This is the simplest solution but I don’t think such a rule exists.

Dynamically serve different .htaccess files based on the host being accessed. This ticks neither box of being simple or actually something you can actually make the computer do. But maybe it is if you start layering your .htaccess files.

Invoke the http authentication from the PHP script itself, detecting the server name and serving if appropriate. This is doable and straight forward to implement but requires quite a bit of coding.

Also maybe I can do the original solution, but only inside the vhosts.conf file? I haven’t really looked into that so that’s just speculation. Question is, which is the easiest solution to implement?

Short tags

Wednesday, August 13th, 2008 | Life

Short tags. My one victory of the night.

It’s been one of those days.

I got my new equipment delivered today in preparation for the podcast. The mic stands are, well, awful. They are way too big. Still I’m sure I can look beyond that if only Behringer had got back to me in terms of configuring my mixing deck so sound comes out. I haven’t got that far yet so I’m now sitting on lots and lots of very expensive equipment that I can’t get to work and we start recording the show in just over a week.

A-Soc. I had to redo the artwork for the membership cards because everyone prints different “standard size” business cards apparently. I don’t know if my artwork has sent because all my SMTP servers sent my email then told me it had rejected it. And I can’t order the hoodies because people aren’t answering their phones after they haven’t responded to my emails. I can’t test the A-Soc website locally because the MySQL server keeps rejecting my connections.

Finance. I’ve had £170 go missing out of my account which means I have had to cancel my card so now at some point I need to go home and get my new card and no doubt spend time on the phone activating it too as well as going through the fraud procedures.

Web. My web host isn’t returning my emails with regards to the fact they have lost my database. I still can’t commit all of my files to the SVN for House Metrics but the one victory I have had tonight is short tags. Having finally got everything running, anything without a full

Log your visitors to a text file using PHP

Sunday, September 16th, 2007 | Programming, Tech

Not all web hosts grant access to web server logs. And even if you do have access to them they may not be that useful. The solution is to write your own script which will log your own stats. And it can all be done without the use of a database. Though databases are great for this not everyone has a spare one so I am going to use nothing more complex than a text file to show the information.

The logging file

The first thing we need is a file to record each hit and log the information in a text file. This is done by creating a function and adding all the variables into it. We can then add information for these variables later in the tutorial.

<?php
function logthis ($sessionid, $pagevisited, $ip, $browser, $refer)
{
$log = fopen("log.txt","a");

$countryfile = fopen("http://ip-to-country.com/gert-country/?ip=$ip&user=guest&password=guest","r");
$country = fgets($countryfile,50);
fclose($countryfile);

This sets up the basic information for the log. I also used a tool which allows you to send an IP address and the site will return the country which that user is from. And therefore we can log which country each visitor comes from.

$now = date("d F Y h:i:s A");

fwrite($log,"$now,$sessionid,$pagevisited,$ip,$country,$browser,$refer\n");
$log = fclose($log);

}

?>

This code writes in the information. Well the top bit gets the date. But the second part at least does the interesting things. All the variables are lined up and the data is separated by comma’s to allow it to be analysed later. There is also the \n to indicate a new line should be gone to after the data is written in.

That is all the code for the logging file. Save it as log.php. We are now done with this file so you can close it down as everything else will be done from the other pages.

Code for the pages

For each of the pages you want to log the stats on you need to insert some code above the <html> tag to allow us to track the visitors to that page. So you will probably want to insert the code into all your pages.

There are two parts to the code that needs to be inserted into your pages. The first includes the log.php file into your page so we have the function. The second gives all the information to be included.

<?php

require 'log.php';
session_start();

logthishit(session_id(), $PHP_SELF, $REMOTE_ADDR, $HTTP_USER_AGENT, $HTTP_REFERER);

?>

After the include line there is a line telling PHP to start a session. Sessions are new to PHP4 and allow each user to be treated individually so you can work out when duplicate users are visiting different pages.

This code can be pasted into all your pages and remain relatively unchanged. The only bit which will need some tinkering with is the path to log.php. So for instance if you had a page in a games folder and log.php was in a folder called stats you would need to change log.php next to require to ../stats/log.php.

A few small tasks

You are almost done! Just a few small things to do and then we are finished. First open up your text editor, Notepad is fine, and save a blank file as log.txt in the same folder as you saved log.php. Once that is done upload the two files and any files which you added the code into to your web space.

It’s best to upload your files to the root directory of your website if you can. You then need to make sure that that text file has read and write properties. It may have already although if it doesn’t or your not sure then make sure by right clicking on it in your FTP client and look for a properties menu or something similar. This is usually how it’s accessed though it may vary depending on your FTP client.

Finally there is one more thing you may want to do. If all your files use .htm or a similar extension and you can only run PHP scripts on .php pages you will have a problem as you may not want to rename all the files. So if you can’t rename the pages and PHP scripts don’t work in .htm pages you need to edit your .htaccess file.

If you don’t already have one then you can copy the following code into a blank text file, save it as .htaccess and upload it to your web space. If you already have one then download the current one and add this code or modify the existing code to look like this.

AddType application/x-httpd-php .php .html .htm

You can add any other extensions you use to the end of these too.

Analysis & Conclusion

Now your server log is complete and the script will begin counting all your visitors and saving them in log.txt. When you want to view the log all you have to do is either point your browser to the file or download it using your FTP client and open it in a text editor.

That is your basic view, however if you would like something more complex then use a spreadsheet application such as Excel. You can open log.txt up in a spreadsheet and it should display fine as we added in the comma’s to separate the data.

You can also use the AutoFilter which can be found in the Tools menu at the top of Excel so you can select one piece of data to filter in the logs such as one users session id or one browser to display all the data from.

Now you not only have great logs but they look shiny too.

Connecting to MySQL in PHP

Sunday, September 16th, 2007 | Programming, Tech

So you have your shiny new MySQL database your web host has given you and you are already to begin your PHP scripting. If not then you can get an account with all this from www.tripod.lycos.co.uk. Or you could when I wrote this anyway.

For those of you used to connecting to Microsoft Access Databases, like I am, the difference here is that rather than the database being a normal file like a word document or a music file which can be easily opened, etc, MySQL databases are stored on the server. So rather than connecting to a file you connect to the server.

First I am going to jump straight in to the code and then explain it after.

<?php
$db = mysql_connect("localhost", "username", "password");
mysql_select_db("database",$db);
?>

That is a basic connection. Ignoring the php open and close tags, the second link in the code makes the connection to the database of your choose. In this case it connects to a database simply called “database” so change this to your database name.

The top line tells the script where the database is. In most cases you can leave this as “localhost” as most hosts keep this as standard. If you get told your MySQL host is different though replace localhost with the new address your web host gives you.

Once you have established a connection you can then enter SQL underneath:

<?php
$db = mysql_connect("localhost", "username", "password");
mysql_select_db("database",$db);

$sql="SELECT * FROM members WHERE posts > 10";
$query=mysql_query($sql);
?>

In five lines you have connected to a database and even prepaed some SQL to select a record set from it. That is pretty simple I recon.