Why do people hate PHP?

August 20th, 2010

I personally like PHP quite well, but I have seen much dislike for PHP on forums, IRC channels etc. So now I have asked a little around to find out what’s wrong with PHP…

The naming of functions seem to cause much hatred. Why is it called str_shuffle(), str_repeat() and str_replace(), but strlen(), strpos() and strrev()?

The order of parameters also seem to piss people off, for instance array_filter ( array $input [, callback $callback ] ) and then we look at array_map ( callback $callback , array $arr1 [, array $... ] ). Doesn’t make sense.

The need to use cURL if you need to work with cookies.

The use if php.ini where you can set magic_quotes, register_globals and safe mode on / off does not make the code very portable. Say you write a program with safe mode = on in the back of your head and then the program are used on another server with safe mode off…

And then we have PEAR as quoted on a dude at reddit.com “Oh, and then there is PEAR. Hey, I’d like to install 5,000 buggy libraries on my website.”

And there is the dollar sign ($) which seems like waste of space, the lack of the opportunity to use threads and it’s easy to write bad and sloppy code, while other languages forces the user to write better code.

But the main reason I personally think is that there are some many people learning PHP as their first language (including myself) and then the language is associated with newbies.

PHP Golf Tips & Tricks

August 13th, 2010

The term Perl Golf comes from competitions where the objective is to sovle programming challenges with as few bytes (strokes) as possible. Read more here.

Golfing in Perl is much more efficient then with PHP, you can tweak and hack Perl indefinitely. But I’m going to show some tips and tricks of how to make PHP code as little as possible.

Of course, use short one char variable names, remove useless whitespace (spaces, newlines, tabs etc). Use echo instead of print. Don’t write the same code twice and in general think outside the box.

Use short php tag you don’t need to close the php tag. So you can do this without any problem:

<?
print "hello world";

and if possible:

<?="hello world";

You don’t need to add quotes on single word strings. It will give a notice, but most golf competitions will ignore notices:

$foo = bar;

Multi assign variables:

$a=$b=0;

Use actual newline instead of “\n”. You will save a whole byte.

print "hello world
";

Don’t use braces {} where you don’t need to. And in some cases add as much as possible inside it.

for($a='a',$b='b',$i=0;$i<10;$i++,$a=$b)echo$i;

Use short ifs instead of the ordinary if operator:

$a = $x == 1? 'a' : 'b';

In the above example you can make it even smaller if you drop the checking of $x being 1, by just checking if its true:

$a = $x? 'a' : 'b';

You can do that in a for-loop also:

for($i = 10; $i; $i--);

You can assign multiple variables and print them out in one statement:

echo $a = "hello", $b = "world";

You can also use short ifs inside echo and decrease $i while you check if its true. This example will print “foo” as long as $i is over 0:

for($a=foo,$i=99;$i;)echo--$i?$a:'';

You can use strings to simulate arrays:

$s = "hello";
echo $s[0], $s[1], $s[2], $s[3], $s[4];

Remove the last “invisible” newline at the bottom of your file. Lets say we have this file:

$a=0;

You count 5 bytes, right? But the filesize says 6 bytes.
Open a hex editor and remove it manually or run this command from a shell:

perl -pi -e 's/\n*$//' file.php

I will continue to update this post as when more tricks comes to my mind…

Here are some sites where you can golf around:
Perl Golf
C Golf
Code Golf (Ruby, PHP, Perl, Python)
PHP Golf (Under contruction by me)

Quick intro to PDO (PHP Data Objects)

August 12th, 2010

PDO is an awsome database interface extension for PHP. It’s written in C and are included in the PHP core.

It’s easy to use and is much more robust against SQL-injections. This is because you explicit define what is a value.

Here are some examples of how to use PDO.

Initalize the PDO object.

try {
    $pdo = new PDO(
        "mysql:dbname=db;host=localhost", 'user', 'pass',
        array(
            PDO::ATTR_EMULATE_PREPARES => true,
            PDO::FETCH_ASSOC => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        )
    );
}
catch (PDOException $e) {
    die ($e->getMessage());
}

PDO::ATTR_EMULATE_PREPARES => true
PDO emulates prepared statements instead of sending them to the sql driver. With the MySQL driver, this will increase speed.

PDO::FETCH_ASSOC => true
Fetching rows from a query will only return a set of associative keys. By default you get a set of numerical keys too, which are rarely used. If you fetch ‘SELECT firstname, middlename, surname’ in $row, you will get $row['firstname'], $row[0], $row['middlename'], $row[1],
$row['surname'] and $row[2]. PDO::FETCH_ASSOC will not return the numerical keys.

PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
Makes an exception on errors, which makes it nice and easy to handle errors.

Here’s an example of how to make a standard query with parameters.
You don’t need to escape the inputs with mysql_real_escape_string(), because PDO knows what is parameters and not.
(This is just and example, you don’t want the users password as plain text in the database.)

$sql = "SELECT id FROM users
          WHERE username = :user AND password = :pass";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':user', $_POST['username']);
$stmt->bindParam(':pass', $_POST['password']);
$stmt->execute();
$result = $stmt->fetch();
print $result['id'];

When dealing with classes. Pass the PDO-object with the constructor and make it protected.

class Foo {
    protected $pdo;
    function __contruct($pdo) {
        $this->pdo = $pdo;
    }
}

When you need to use SQL’s “LIMIT” you need to explicit tell PDO that it is in fact integers we are inserting.

$stmt = $pdo->prepare("SELECT foo FROM bar LIMIT :offset, :hits");
$stmt->bindValue(':offset', (int) $offset, PDO::PARAM_INT);
$stmt->bindValue(':hits', (int) $hits, PDO::PARAM_INT);

This is explained more in detail here:
http://e-mats.org/2009/02/pdo-and-pdoparam_int/

Now go and explore PDO if you havn’t already done so!

Get latest bleeding edge gfx drivers in Ubuntu

June 18th, 2010

Want the latest of the latest updated bleeding edge graphic drivers in Ubuntu?

Open /etc/apt/sources.list:

sudo gedit /etc/apt/sources.list

Add these lines at the bottom:

deb http://ppa.launchpad.net/xorg-edgers/ubuntu lucid main
deb-src http://ppa.launchpad.net/xorg-edgers/ubuntu lucid main

Update and upgrade:

sudo apt-get update
sudo apt-get upgrade

If you don’t use Lucid (Ubuntu 10.04) just change “lucid” to what ever you use, for example ‘karmic’.

Enjoy :)

Generate random string in PHP

June 18th, 2010

Here’s a function to create a random string with the chars ‘a’ to ‘z’, ‘A’ to ‘Z’ and 0 to 9 in PHP.
I have seen many people asking for this, so here it is:

<?php

function randStr($length, $str='') {
	$array = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
    for($i = 0; $i < $length; $i++) {
        $str .= $array[rand(0, (count($array) - 1))];
    }
    return $str;
}

?>