Category Archives: PHP

CSSParser release

So… I haven’t really been doing any work at all on the CSSParser(my own CSS Tidy project for reading and compressing CSS) I started on a couple of months ago. What happened is what always happens with my own projects. After I’ve implemented the initial idea, I start to loose interest.
But I’ve made it further with this CSSParser than I usually do, so I’ve decided to release the source code for the project. Not every function will be well documented but I’ve tried to comment as much as possible.

Download it here.

I’ll do a quick explanation of how the process, just to give an idea of how it all works.

  1. The CSSParser class reads a given CSS, using a single preg_match_all call.
  2. Now then class will start to build up an array of CSSSelector classes. This class will hold all the properties and identifiers of a CSS selector from the given CSS.
  3. Each property of the CSSSelector will be held in a CSSProperty class or a class extended the CSSProperty like CSSBorder and CSSBox. This way it’s easy to add more specific output on properties, simply by extending the CSSProperty class and making your own property class.
  4. Now all the data is structured in the CSSParser class. And by calling the printCSS() function with a CSSOut class as the argument, we can get the CSS out the way we want.

When printing the CSS a very primitive templating system is used, where the template simply is PHP that has access to the list of selectors after they’ve been run through a preProcess function optimizing the data for output.
An example can be the template1.php file (found in the downloadable zip):

1
2
3
4
5
6
7
8
9
10
11
<?php
foreach ($data as $selector) {
    echo implode(",\n", $selector->identifier);
    echo " {\n";
    foreach ($selector->properties as $property) {
        foreach ($property->getProperty($settings) as $key => $value) {
            echo "\t$key: $value;\n";
        }
    }
    echo "}\n";
}?>

Read more »

Checking for a value

Reasoning behind the bench

I’ve been working a bit on my CSSParser (which I will rename to CSSReader og CSSHandler when I get around to it), and one thing I found out was, when reading shorthand values (like: border: 1px solid #00ffff;) you can’t assume they always come in the same order.
If we take a border property as an example:

.something {
  border-right: 1px dashed #00ff00;
  border-left: dashed 1px rgb(255,0,0);
  border-top blue solid 1px;
}

This shows that the border shorthand value can have a different order of subvalues, and the actual value data can change alot (notice the 3 different ways of defining a color, the rgb() still cause me a bit of trouble). So to set an array (mapped with [‘width’], [‘style’] and [‘color’]) I can’t just split the string and set it, I need to split the string and then try to guess every value. To guess the values I’ll be running through the following process: Read more »

Benchmark class, release (& first test)

So as promised I’ve cleaned up and commented a bit on my Bench class. And let me get to it, you can

Download it here.

Bench suite

I’ve also made my first test in my new (and not to pretty, but working) bench suite. The bench suite is a site where I can gather my different tests, and be able to easily access them later on for references. So far it’s a very simple setup, where I have:

  • A list of the tests. This goes through a directory where each test has it’s own test file, and use some of the data in the file to make an informative list.
  • A runner. Which will run each test, and output the results in an easy to read table, along with the actual source code of the test.

Down the road I would like to improve a bit on the interface which is lacking to say the least. I’ve also been planning on saving the test data so I can get an average result of all the tests run.

Empty loops test

So the very first test I’ve done is a simple empty loop(it will run the test every time you, so the result wont be identical to what I’ve displayed below) test. And it also works as a quick how-to for the class it self.
What I wanted to test with this bench, was the difference between the for, while and do..while loops, and as an added bonus I also tested a goto loop (more for the fun of things). I’ve also tested everything with a pre and post increment. Anyway the result of the test looks as following Read more »

Benchmark class v1

So I’ve made a first version of the benchmarking class I’ve been talking about previously. While working on the CSSParser I encountered one of those micro-optimization situations, so I made a quick first draft of the Bench class (I’ll post the actual benchmark in another post).
The outline of the Bench class is as the following:

Function Description
start($test, $subTest = “”) Start a test, with a test title (which is also the identifier for the test). It’s possible to supply additional sub tests to the test, this is helpful when doing the same code test but with different inputs.
end($test, $subTest = “”) Ends the test with the test and subTest identifier.
tick($test, $subTest = “”) Set a mid point in a test, this way we can easily make more fix points if needed.
getResult($dec = 6) Returns all the tests in a neatly packed table, the $dec is the amount of decimals on the time measurement.

Let me show a simple example where we test 2 empty for and while loops and a recursive function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
function recursive($c) {
    if ($c == 0)
        return;
    return recursive(--$c);
}
 
$b = new Bench();
 
$b->start("for loop", "1000");
for ($i = 0; $i < 1000; $i++) {
}
$b->end("for loop", "1000");
$b->start("for loop", "10000");
for ($i = 0; $i < 10000; $i++) {
}
$b->end("for loop", "10000");
 
$b->start("while", "1000");
$i = 0;
while ($i++ < 1000) {
}
$b->end("while", "1000");
$b->start("while", "10000");
$i = 0;
while ($i++ < 10000) {
}
$b->end("while", "10000");
 
$b->start("recursive", "1000");
recursive(1000);
$b->end("recursive", "1000");
$b->start("recursive", "10000");
recursive(10000);
$b->end("recursive", "10000");
 
echo $b->getResult();
?>
simple bench output

for loop 	0.000097	0.000810	0.000454	100.00%
while    	0.000074	0.000629	0.000351	77.48%
recursive	0.001844	0.016954	0.009399	2072.14%

The first column is the name of the test.
The following 2 columns is each sub test, so the first number is the time of our “1000” iterations and the second number is “10000” iterations.
The fourth column represents the Read more »

Starting up my CSS Minify project

This is just a status update on my CSS Minify project, I will make more updates as I progress through the project. It’s basically a journal of my thoughts and design process, so if anything strikes you please do comment with some feedback.

So I started working on a way to minify my CSS files. I know (or well I found out, just after I started working on my own project) that there’s a well written and very functional CSSTidy which does exactly what I want to do. I will anyhow still continue my own project, mostly for the learning process, but also because it’s been a long time since I’ve had a project of my own and I miss that.
My initial thought was to parse the CSS using regular expressions, but the lexical approach CSSTidy uses caught my eye.
I’ve decided to start out parsing with the regular expressions. I will eventually try to copycat the CSSTidy way, just to get a better understanding of lexical analysis, and having CSSTidy as a result sheet.

So far I’ve made the parser, and it seems to work on proper CSS I will need to test it up against some messy CSS.
I had my CSSParser class, with a $selectors array holding all the selectors (my CSSSelector classes). The CSSSelector class had a similar $properties array, holding all the properties (CSSProperties class) for the selector.
This seemed a bit overkill, the arrays were both using a key being the selector/property name and a value being the class, the class it self just being a class with a value property. So I will remove the 2(selector and property) classes, and just use a simpler array structure.
I do however still like the idea of having the selector and property classes, it fits nicely into the whole CSS principal. I’ve been planing to use them when it comes to outputting the CSS again, but in that case why not just use them to start with … I’m torn.

XML-RPC

This is simply a copy of my old XML-RPC article (2005). I’ve done a bit of content editing when converting the article to this blog format, but still most of the content is unchanged.

1. Introduction

So you’ve decided to learn XML-RPC[1], or did the name just sound “freaky” and raised a little interest? If it did I suggest you read on, if you already know what XML-RPC is, then just skip the next intro part

1.1 What is XML-RPC

XML-RPC is a way to make web services, it packs the requests and responses in XML both the client and the server can understand.
For those who don’t know a web service is a function of some sort placed on the net (it could be a function to convert a string into all upper case letters, which we are going to make in the examples below). The smart thing is that, a web service can be programmed in any kind of language, and any other language can use it. Many big sites have a web service, for example Amazon has a web service that allows you to search books and information.
Another smart thing about XML-RPC (and to my knowledge all other web services), is that they can be run from a web server. Not only is this smart, because you don’t need to install some high-end server dedicated to the purpose. But you don’t have to worry about firewalls.

1.2 Installing XML-RPC

If you’ve installed an extension before, this should be no problem at all, just install the XML-RPC extension. But if this is your first time, the following links will help a bit:
Windows users: http://www.php.net/manual/en/install.windows.extensions.php
Unix users: http://www.php.net/manual/en/install.unix.php
OS X users: http://www.php.net/manual/en/install.macosx.php
For you guys(and gals) who compile PHP: –with-xmlrpc. Read more »

Pic2HTML

BeeThis is simply a copy of my old pic2html article (2005). I’ve done some minor content editing, mostly spelling but there still might be a few lines that doesn’t make any sense.

1. Introduction

A long long time ago, I was a little trip by http://romanm.ch (no longer the same site), and well I must admit pretty impressing, try to take a look your self, especially the movies are well made.
Anyway, this gave me the idea of making an image to pure html code. My theory was that it would be simple to make a picture look good even with nothing but html (and as you’ll see later this was the truth, it’s possible to make 100% replicas), even though it’ll be size heavy.
Before we get going, remember to enable the GD library[1], for PHP. If you don’t know how, consult the PHP manual. I wont be going into details about the different GD lib functions, so you’ll need to read up on the GD functions you’re not familiar with in the manual as well.

2. rgb2html

First off we need a function to change the RGB color code to HTML color code (or simple from decimal to hexadecimal[2]). Lucky for us PHP is filled with a lot of helper functions, that sometimes turns out to be, well useful. This time it’s the great comeback for the dechex function, which convert a decimal number to hexadecimal. I’ve packed this down in a little function:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
function rgb2html($clrR, $clrG, $clrB, $intReturn = 2) {
    $clrR = substr("0" . dechex($clrR), -2);
    $clrG = substr("0" . dechex($clrG), -2);
    $clrB = substr("0" . dechex($clrB), -2);
 
    if ($intReturn == 1)
        return array('red' => $clrR, 'green' => $clrG, 'blue' => $clrB);
    elseif ($intReturn == 2)
        return $clrR . $clrG . $clrB;
}
?>

In our code, all we need is the function which spits out the color code as a string, but I got carried away and made a little extra (return as an array). And you can like any other of my functions in any of my articles, (ab)use them like a mad man, if that’s you desire, just as long as you don’t say you’ve written then your self. Read more »

Benchmark class, what do I need?

Although micro-optimizing don’t give the biggest performance improvement, I often find my self wondering if using function X() instead of Y() is faster, and if my own function Z() is better. Most of the time I end up writing a small tiny benchmark test on the two or three functions, which then gives me a quick overview of the functions speed.
So I’ve decided to make a small and simple to use micro-benchmarking class.

Goal

Basically this class is all about being easy to use, so you don’t have to spend a long time setting up a test.

  • Easy to set up. The class should be used for those small tests, where you’re in doubt of which piece of code is fastest. And if one is to test a piece of code, for a tiny performance increase (maybe more out of curiosity than an actual application improvement), it should only take a couple of minutes to set the test up. If it takes 15 minutes to create a test every time, you wont take the time to write the test if you’re in the middle of something else.
  • Readable output. For the same reasons it should be easy to set up, the output needs to be readable when the test is done, without any post-test-processing. It would be good if the output could be chosen, so you could either get the easy to read, or a more in-depth detailed result (maybe formatted for post-processing in another environment).

Nice to have

Again with the intentions of making this easier to work with, it would be great to have a feature, where you would just write the piece of code you wanted to test, and then have the class handle the rest. Read more »

A quick look at the cURL Library

It was only until recently I discovered the PHP: cURL Library. I’ve been using homegrown functions for fetching HTTP requests, but with the cURL it’s not as much a hassle as it used to be. Remember that the cURL isn’t a PHP standard, and you need to install the extension.

The basic functions

I do have a tendency to forget the most basic cURL functions, so I’ve decided to make a quick post here I can use for references my self. It’s basically a small cURL tutorial.
I’ll start out with listing, a few basic functions, sorted in the order in which you use them.

Function Description
curl_init This creates a curl handle, which is passed with the rest of the functions. You can set the URL as an argument to this function, although I prefer to use the curl_setopt function.
curl_setopt Sets the options of the cURL handle (returned from curl_init), an option could be the URL, POST vars, header and so on. There’s many options, so refer to the constants list in the PHP manual.
curl_exec Execute your cURL with all the settings. Depending on the CURLOPT_RETURNTRANSFER option, it will return the content or, true or false.
curl_close Free up the handle when you’re done..

Simple HTTP get

This will use HTTP to call a website, and get the content. Basically this is just a file_get_contents, except you have all the extra options cURL give you:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
// 1) Create the curl handle:
$ch = curl_init();
 
// 2) Set the options you want for the current handle:
curl_setopt($ch, CURLOPT_URL,            "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
 
// 3) Retrieve the data:
$data = curl_exec($ch);
 
// 4) Close up:
curl_close($ch);
 
var_dump($data)
?>
Snippet of the data output<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>

</HTML>

Like mentioned we could use var_dump(file_get_contents(“http://www.example.com”)) to get the exact same output, but as an added bonus (on top of the vast set of options) cURL actually performs better than FGC. Read more »

PHP Ping

pingThis is simply a copy of my old PHP Ping article (2005). I’ve done no content editing, only thing I’ve changed is the layout.

1. Introduction

Notice: I will change between binary, decimal and hexadecimal notations, but if you let your mouse rest above the number, the 2 other notations will apear. Try moving your mouse over this number: 1010 0001

Before you start, let me warn you, that this may seem as some heavy reading, but hang in there.
Remember you have to enable socket programming, if you’re not sure how this is done, referer to the PHP manual, on installing[1] PHP.
This article will walk you through creating a valid ping function in PHP. And in this process I will be covering network programming (shortly, you can always read about that somewhere else) and working with bitwise operations[2]. First off we’ll be discussing how a valid ping (or Echo message, of the Internet Control Message Protocol).

1.1 Echo Message

To make a valid ping to another network device, it’s important you follow the ICMP standard, they can be found in RFC-792[3]. And yes you’re absolutly right RFC documents are just as boring as the dictionary, but sometimes they come in handy. I’ve decided to run through the standard quickly, so we can move on.
It’s build up by 6 fields, which looks like the following:

Type

(8 bit)
Code

(8 bit)
Checksum

(16 bit)
Identifier

(16 bit)
Sequence Number

(16 bit)
Data

(… bit)

Yep, it might seem a little confusing I know, but it’s not that hard to understand. It’s nothing but a single line of bits, starting with type and ending with data, now let me explain them a little deeper:

  • Type: This defines what kind of message we whish to send. What we want to send is an Echo Request, which has the type 1000, there’s a long list[4] of different messages, and their purpose.
  • Code: In our case we set the code to 0000, because the echo message dosn’t have any other options. You can compare the Type with the function and the Code with the parameters.
  • Checksum: The checksum[5] is calculated when then package is assembled, to start with we set the checksum to 0000 0000. Then later the checksum is calculated by one’s Complement. If you’re not use to binary operations, this will be hard to explain, and there’s no easy reading on the net, try to google it[6].
  • Identifier: In the original ping program, this is the UNIX process ID, but in our ping it can be anything. Normaly I just set it to 0000 0000, but it’s all up to you. In some cases it could be smart to make it unique so you can recongnize your ICMP package.
  • Sequence Number: Again just a number, in our case it’s 0000 0000 as the Identifier. But a good use for this, is to increment it if you run more than 1 ping at a time.
  • Data: This can be any data. In our case, we use: “Scarface”

So basicly that is the package we wish to make, for our ping to be correct. The hard thing here is the checksum, we will work with this later on in the article.

2. Sockets

Before we start designing our package (well talking about calculating the checksum), lets talk a little about network programming.
Normally when people talk about network programming, they’re talking about TCP/IP or UDP/IP protocols. But we are going to use the ICMP protocol. But enough about that, let’s start looking at the functions we’ll be using.
Read more »