PHP MySQL Developer

Welcome to the PHP MySQL Developer series. As a London based PHP Programmer and MySQL Programmer, clean code, commented code and secure code is a must!

Interested in using my services? Contact Me

14th May 10 PHP – Checking for Array Keys

As a PHP Programmer, I recently came up against an error while testing another developer’s code.. Within PHP, testing for the existance of the referring URL:

if (empty($_SERVER['HTTP_REFERER'])) will produce a notice:
Undefined index: HTTP_REFERER

The correct way to check for the existence of an array key is: if (array_key_exists(”HTTP_REFERER”, $_SERVER))

7th April 10 – PHP and curl

Using curl with PHP is incredibly easy. Firstly you’ll need to make sure that you have the PHP curl library installed on your system. On Debian, this is as easy as apt-get install php5-curl

Now you can try the following:

$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, “”);
curl_setopt($handle, CURLOPT_HEADER, 0);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($handle);


You can also check to take a look at the other options that curl_setopt can take.

curl can also post data to the remote server via POST or GET and also has the ability to save and retransmit cookies.

14th January 10 – PHP Security

As a PHP programmer, there are a couple of things you can do quickly and easily to increase the security of your PHP code installation.

Look into PHP’s “safe mode” feature, ESPECIALLY if you’re running a webserver that takes the general public can upload scripts to. Here you’ll find a list of the functions disabled or restricted by safe mode. It is not strictly PHP’s job to restrict these types of functions, however unless you really know what you’re doing, the list of functions restricted by safemode is a good starting point for building secure applications. These are generally functions that allow file and directory manipulation, and socket manipulation. If it’s not possible within your environment to disable them all, disable as many of these functions as possible.

Although not that common, if I’m writing an application that heavily relies on functions that manipulate directories or sockets, I’ll prefer to create a C daemon or similar to handle this side of things and simply use PHP to communicate with it. (more…)

17 December 09 – PHP Programmer – Logical Operators

PHP allows the use of boolean operators.

AND, OR, XOR and NOT. We can combine NOT with AND and OR to form the NAND and NOR operators respectively.

$a = ($b and $c); will return TRUE if both $b AND $c are TRUE, otherwise, it will return FALSE. This can also be specified as $a = ($b && $c)

$a = ($b or $c); will return TRUE if $b OR $c are TRUE, otherwise, it will return FALSE. This can also be specified as $a = ($b || $c);

$a = ($b xor $c); will return TRUE if $b OR $c are TRUE, but not if they are both TRUE, otherwise, it will return FALSE.

$a = (! $b); will return TRUE if $b is NOT TRUE.

$a = (!($b && $c)); will form NAND (NOT + AND)
$a = (!$b || $c)); will form NOR (NOT+AND);

14 December 09 – PHP Programmer – Numeric Shorthand

PHP 4 and 5 offer a few shorthand methods for basic numeric operations:

$n = $n + 1; can be specified as $n++;
$n = $n – 1; can be specified as $n–;
$n = $n + 10; can be specified as $n += 10;
$n = $n – 10; can be specified as $n -= 10;

On the subject of shorthand, also check out the PHP Ternary Operator

3rd December 09 – PHP Programmer – Reading from files

Here I’ll give some file reading examples. There’s a few different ways to do this. I’m going to focus on plain text files only, as opposed to binary files.

If you just want to read the contents of a file into a string variable, then the easiest thing to do is use $mystring = file_get_contents(”/home/adam/myfile”);

For more control over what you’re doing, or if you want to do anything more than reading a file into a string, you’ll need to use the fopen, fread and fclose functions.

To read everything in one go:

24th November 09 – PHP Programmer – strlen, count and substr

PHP Developer – strlen, count, and substr

The strlen function retuns the length, i.e. number of characters in a string:  int strlen(string s)

count will get the number of elements in an array:  int count(array a)

substr will return a “subset” of a string, string substr(string s, int start, [int len]);
$s = “test string”;
echo “String length is: ” . strlen($s);

Will return:  String length is: 11

Why would you care how long a string is? Well, for many reasons, one being that you might wish to iterate through each character of a string to perform a certain conditional check or operation on each character. Alternatively, you might want to check that a certain string is not over a given size, and if so, shorten it. Here’s a common example that shows these three common functions together:

$myarray = Array("This is a very long string", "short string", "some text", "some more text to be shortened");
define(MAXLEN, 20); //maximum permitted string length
$num = count($myarray); //Get the number of elements in the array
for ($ctr = 0; $ctr < $num; $ctr++)
    if (strlen($myarray[$ctr]) > MAXLEN)
        echo substr($myarray[$ctr], 0, (MAXLEN - 3)) . "...\n";
    } else {
        echo $myarray[$ctr] . "\n";

The above will output:
This is a very lo…
short string
some text
some more text to…

This could be used in an instance where we only want to show a predefined “taster”, i.e. replacing … with “(more)” or similar. Alternatively, ensuring that text does not overflow a “<div>” element in a particular instance

20th November 09 – PHP Programmer – strpos, finding the position of a word in a string

In PHP, we can use strpos to find the position of a character or string within another string:

int strpos  ( string $haystack  , mixed $needle  [, int $offset = 0  ] )

For example:

$mystr = “this is a test string”;
$pos = strpos($mystr, “test”);
echo “Position: ” . $pos;

Returns:  Position: 10

We can just as easily use strpos to test for whether or not a given string is found in a larger string:

if (strpos($mystr, “test”))
{ … }

However, that may in some cases unexpectedly fail:

if (strpos($mystr, “this”))
{ … }

This will return 0, as “this” is at the beginning of the string and therefore at position 0, causing the condition to fail. The correct usage is:

if (strpos($mystr, “this”) === false) { … } OR  if (strpos($mystr, “this”) !== false) { … } noting the usage of “===” or “!==” meaning an absolute evaluation. As of PHP 4, “==” means “equal to” and “===” means “identical to”.

18th November 09 – PHP Developer – Serialize

PHP has two ver useful functions, serialize and unserialize.

serialize() generates a string based storable representation of any variable type that you like. Take a complex variable:

15th November 09 – PHP Developer – Loops in General

There are 3 types of loop in PHP:

while (condition)
{ code_goes_here; }

{ code_goes_here; }
while (condition);

for(expr1, expr2, expr3)
{ code_goes_here; }

In terms of the ‘for’ loop above, ‘expr1′ being the starting expression, i.e. $i=0. expr2 being the condition that must be satisfied to keep the loop running, i.e. $i < 100. expr3 being the expression evaluated each time the loop runs, i.e. $i++. Each loop type has it’s uses.

10th November 09 – Freelance PHP Programmer – Managing Estimates

Dealing on larger projects and mediating between my PHP development team and the Client is often a far simpler task than acting as a sole freelancer. Having a very good and reliable team of 12 long term offshore PHP programmers, means that I now have sufficient confidence that I could theoretically just pass their overall estimates straight on to the Client without issue. Even still, I add at least 10% to the PHP developer’s estimates as well as subtracting at least 10% from the Client’s final delivery date. If we’re all happy and can agree on those deadlines, great. This allows for a comfort period for us, as well as the ability to iron out bugs and perform good QA on anything delivered.

05th November 09 – PHP Developer – Looping through database results

As a PHP Programmer, a very routine PHP/MySQL procedure is fetching a set of records from the result of a query.

$sql = "SELECT ...";
$result_set = mysql_query($sql);
for ($ctr = 0; $ctr < mysql_numrows($result_set); $ctr++)
    $my_object = mysql_fetch_object($result_set);
    //do something with $my_object

Now as tidy as the above code is, what’s the big problem? The number of rows returned by the query remains the same throughout. Why are we calling the mysql_numrows function on the same result set, to return the same answer over and over, possibly thousands of millions of times depending on the size of the result set? On a larger web application with a larger result set, things like this will dramatically increase unnecessary overhead. This is one of the most basic optimizations to make:

$sql = "SELECT ...";
$result_set = mysql_query($sql);
$result_num = mysql_numrows($result_set);
for ($ctr = 0; $ctr < $result_num; $ctr++)
    $my_object = mysql_fetch_object($result_set);
    //do something with $my_object

Now, there’s a couple of different methods you can use to achieve the same purpose, some of which may actually be more appropriate, such as a simple while loop, but the purpose of this article was to illustrate the issue above solely. More on optimization later..

13th October 09 – Copy/Export MySQL User Priviledges

I’m often asked how to copy or export MySQL Users from one machine to another. The following SQL query will show your users:

SELECT DISTINCT CONCAT(’SHOW GRANTS FOR ”’, user, ”’@”’, host, ”’;’) AS query FROM mysql.user

In my case on my test server, this shows:

SHOW GRANTS FOR ‘root’@’′;
SHOW GRANTS FOR ‘debian-sys-maint’@’localhost’;
SHOW GRANTS FOR ‘root’@’localhost’;

Now, I’ll need to execute each one of these as separate statements. The output of SHOW GRANTS FOR ‘root’@’localhost’; is:


Copy and paste each ‘GRANT’ statement to your new SQL server, with the hashed password intact and you should be ready to go.

05th October 09 – PHP Programmer – Modulo Operator

All major programming languages have it, it’s the modulo operator, and it has multiple uses. First I’m going to explain what it is, then I’m going to demonstrate one very simple, very powerful use.

Programatically, the modulo operator is most commonly denoted with a percentage ‘%’ symbol. Given two numbers as input, the modulo operator returns the remainder after division. p = a%b; will return the remainder after a is divided by b.

Here are some examples:

2%2 = 0 (2 divided by 2 = 1 remainder 0)
6%2 = 0 (6 divided by 2 = 3 remainder 0)
7%2 = 1 (7 divided by 2 = 3 remainder 1)
18%4 = 2 (18 divided by 4 = 4 remainder 2)

The modulo operator is used extensively in cryptography, Diffie-Hellman (DH) Key Exchange is just one example.

As a PHP Programmer, what can this be useful for?

25th September 09 PHP MySQL Developer – Using MySQLi Prepared Statements to Avoid SQL Injection

I’m going to demonstrate a very short and simple method of avoiding SQL Injection at the SQL query level. You’ll need MySQLi support, on Debian you can apt-get install php5-mysql will contain everything that you need, and would be installed by default with your LAMP Installation.

06th September 09 Security Consultant – PHP Developer – SQL Injection Attacks

One of the most common form of attacks against web applications is SQL Injection. In the most part, the language that the web application is written in is irrelevant, be that PHP, ASP, Python, Perl, C, etc. As long as the back end database uses something SQL based, be that MySQL, MSSQL, etc, again, we’re in business. This probably covers over 99% of web applications out there. Both the security consultant and the php developer or web application developer in general has to be aware of the implications of SQL Injection. Here’s how it works:


04th September 09 – Security Consultant – PHP Developer – Exploiting Common PHP Code Flaws

There are a number of PHP and in fact programming errors in general that PHP Programmers and Security Consultants need to be aware of. Specifically, how can a malicious user use the code to gain access above what he is supposed to.

Cross Site Scripting (XSS), Shell Execution and SQL Injection are all issues that programmers need to be aware of. Luckily, buffer overflows in their traditional sense are not something that PHP developers need to concern themselves with.

Here in it’s most basic sense is an example of how we can read arbitrary files on the filesystem that we should not have access to.

10th August 09 – PHP Developer – PHP Sessions
Sessions are a useful web technology that are used on just about every interactive site out there. Sessions are an important part of all PHP development. A session is a useful method of keeping track of a user’s browser throughout different page requests. The session is dealt with via a cookie sent to the user’s browser, with an expiry time of 0, that is to say, as soon as the browser window is closed, the cookie is destroyed and the session is over.

01st April 09 – Creating an MD5 on Linux with md5sum
An MD5 is a type of Hash, also, a Checksum.

An MD5 hash is a one way verification sum which can be used to verify a string or contents of a file. Once you have a file and an MD5 checksum, the recipient of the file can also perform an MD5 calculation to ensure that the file’s contents are unchanged. They may have been changed maliciously such as in the case of a binary file, or simply by data corruption. An MD5 is NOT a type of encryption. It can not be reversed.

In the case that you know the length of the data, say between 5 and 8 characters for a password, you can attempt to brute force (try every combination automatically until something hits) the password. For that reason passwords are often salted before being MD5′d however salts and their purpose are outside the scope of this article.

27th January 09 – A Beginner’s Guide to Object Oriented Programming (OOP) in PHP5 – Classes, Objects and Methods
***Guest Blogger***
The Personal Home Page (PHP) programming language provides a lightweight framework and foundation for Web application development. It runs on Apache (HTTP) Web server software amonst others, embedded into Hypertext Markup Language (HTML), passed through a Hypertext Preprocessor. As free, open source software – it has low implementation, maintenance and debugging costs. Its latest iteration called PHP5, has incorporated even more powerful object-oriented programming functionalities.

15th January 09 – A rudimentary PHP POP3 example
In my last post I described the basics of PHP’s fsockopen. This script is far from perfect and only contains minimal error checking however it illustrates the basics of fsockopen in action communicating with a POP3 server. More information on the POP3 protocol can be found here

15th January 09 – PHP – fsockopen, TCP and UDP

PHP comes preloaded with a good socket handling function set. Using fsockopen to make HTTP connections however is in most cases obsoleted as the php-curl and set of curl functions covers more HTTP related stuff than you could ever need! fsockopen is available in both PHP4 and PHP5

Regardless, to cover the most basic usage of fsockopen, to establish a TCP connection to “mailserver” on port 110 (POP3)

15th January 09 – PHP – Ternary Operator

I’m going to try and focus some time on building out the PHP section of the site now – here’s a useful technique, in shortening and tidying various cases of if/then/else.

07th October 2008 –
PHP MySQL Apache2 Install HOWTO on Debian
Setting up a PHP/MySQL/Apache2 environment on Debian is really easy. I’ll walk through a quick setup and optimization process. I’ve optimized it for a 1.5Gb to 2GB RAM machine with reasonable load.

1 Comment » for PHP MySQL Developer
  1. Scott says:

    Do you know of any way to do IP based UDP packet capture directly to MySQL in php?

    Something like Wireshark but to MySQL instead of to a log file?

    I’m trying to monitor/capture UDP packets between my local PC and a CNC machine to send a message -or display in a browser- when a fault occurs on the CNC. They are connected NIC to NIC and configured with static (local) IP’s.

    I can see all the data I need with Wireshark but it appears all the output has to go to a log file.

    Any thoughts or pointers to a tuorial would be appreciated.

    Thanks Scott

1 Pings/Trackbacks for "PHP MySQL Developer"

Leave a Reply