Showing all articles tagged with PHP
31 October 2007
Programming, PHP

I had 2 hours to kill so I thought I'd write a LOLCode interpreter.
I know there's already a few LOLCode interpreters around, but I couldn't help myself. Plus I've always been interested in interpreter design.
It's still a work in progress at this stage, so a lot of the language hasn't been fully implemented.
Here are two working programs...
Hello World
BTW the classic hello world program
HAI
VISIBLE "Hello world!"
KTHXBAI
Output:

Accepting User Input
HAI
VISIBLE "Hello there, what is your name?!"
I HAS A NAME ""
BTW ask for the users name
GIMMEH NAME
BTW welcome the user
VISIBLE "Welcome to LOLCode " N NAME N "!"
KTHXBAIOutput:
11 September 2007
PHP, Programming
Here's a quick tip for working with the command line in PHP.
If you've ever run a PHP script via the command line, you would have noticed that output from the script is not printed until the script has finished.
If you need your output displayed in real time, you can open a stream to the command line...
$stdout = fopen('php://stdout', 'w');Simply write any output to the stream and it will be printed on the command line in real time...
fwrite($stdout, "Hello CLI\n");
28 August 2007
PHP, Programming, Security, Web Design
One thing I keep noticing is the use of background noise or clutter in CAPTCHAS. It's now well known in the OCR (Optical Character recognition) field that background noise can be easily removed by computers. It's basically useless at hindering spam bots.
It's so easy that I was able to clean the following CAPTCHA up in only 20 lines of PHP code.
Here's how...
At a glance, you can see the CAPTCHA's background noise has a blue tint.
Looking at the RGB value of the image in Photoshop, I can see that all parts of the background have a blue value higher than 180.
That's the only piece of information needed to remove the background.
The code simply loops through every pixel of the image and checks the RGB value of it. If the blue (B) value is higher than 180, color it white.
Here's the final image. The characters can now be easily separated and identified using OCR software.
So you can see why most background noise is basically useless in CAPTCHAS.
23 August 2007
Programming, PHP
Ray Casting is a extremely fast method of generating 3D images using high-school level mathematics.
Remember playing Wolfenstein 3-D? This was one of the first games made using the ray casting technique.

The graphics in Wolfenstein don't even come close to today's gaming standards; but it was still impressive for it's time. It was also fast, considering the speed of the hardware it ran on.
Although ray casting is an outdated method, it's a good introduction to 3D imagery and game design. It's also quite easy to recreate yourself (if you can remember pythagoras theorem).
The basic idea of ray casting is very simple. To transform a 2d image map into a 3d representation, "rays" are projected from the viewer towards the light source. If a ray hits an object on the 2d map, a vertical line is drawn on our "3d" image to represent this section of the wall or object. Think of the image as vertical slices.
This diagram might do a better job of explaining.

Textures can be applied using texture maps but unfortunately other effects like reflections aren't so easy to create. They can be faked though.
If you've got nothing to do for a few hours, consider creating a simple ray cay caster in your favourite language.
Here's a few resources to get you started.
16 August 2007
PHP, Programming, Security

Most developers have now heard about Facebook's leaked index.php source code, which was anonymously posted here. If you haven't seen it already, there are a number of links listed on Techcrunch.
I've seen a few bloggers criticize Facebook developers for using procedural programming rather than classes and object oriented techniques. I'm not exactly sure why they've chosen to develop the site like this; but I am going to take a guess and say it was to improve speed and efficiency.
Object oriented programming was first introduced to PHP in version 4. However, the language wasn't originally designed around objects and classes, so the implementation was clunky and awkward. This meant that procedural code was often much faster than object oriented code.
Considering the size and popularity of social networks, I'm not surprised they chose procedural code over objects. That tiny boost in performance would easily outweigh the advantages of using classes.
Fortunately, most (if not all) issues with objects have been solved in PHP 5, which is now closer to a truly object oriented language.
05 July 2007
PHP, Programming
Here's an easy way of filtering empty variables from an array, without using a loop or multiple if statements.
<?php
$var1 = '';
$var2 = 'dog';
$var3 = '';
$var4 = 'fish';
$my_array = array($var1, $var2, $var3, $var4);
print_r(array_filter($my_array));
?>
Output:
Array ( [1] => dog [3] => fish )
27 June 2007
PHP, Programming
PHP errors are ugly and should never be shown to your users. Luckily with PHP we can handle errors our own way using the set_error_handler function.
I'll start by defining the error handling function which will write the error to a log file and stop execution.
function handleError($level, $error, $file, $line)
{
if ($logfile = fopen('log.txt', 'a'))
{
fwrite($logfile, date("F j, Y, g:i a") ." $error on line $line in $file\n");
fclose($logfile);
}
die('An error has occured.');
}
Then set it as the error handling function.
set_error_handler('handleError');Trigger an error to see if it works.
echo 100 / 0;You could also get your function to notify you via email. Or you could forget about logging, and just display better looking errors...
function handleError($level, $error, $file, $line)
{
$errorhtml = '<div style="border: 4px solid #bfbfbf; font-size: 12px; font-family: arial, sans-serif; padding: 1px">';
$errorhtml .= '<div style="background-color: #a3503f; color: #ffffff; padding: 3px;">ERROR</strong></div>';
$errorhtml .= $error.'<br />';
$errorhtml .= 'Line: '.$line.'<br />';
$errorhtml .= 'File: '.$file;
$errorhtml .= '</div>';
echo $errorhtml;
}
21 June 2007
PHP
A lot of PHP developer's don't know about PHP's support for variable-length argument lists.
This is a quite an easy feature to use and can be useful when you're not sure how many arguments a function should accept.
To declare a function with a variable-length argument list, declare it with an empty argument list.
function add_scores()Calling the function with multiple arguments is easy...
add_scores(88, 37, 99, 32);Processing the arguments inside the function is also an easy task using the func_get_arg(), func_get_args() and func_num_args() functions.
function add_scores()
{
return array_sum(func_get_args());
}Output: 256
14 June 2007
PHP, Ruby, Programming

Here is a short comparison between Ruby and PHP. The task was to print the location of all HTML links in a webpage using regular expressions.
If anyone knows of a cleaner or more efficient way to do this in Ruby or PHP, please post it in the comments!
Ruby
require 'net/http'
#connect and get the webpage
host = Net::HTTP.new('www.site.com.au', 80)
body = host.get('/index.php', nil ).body
puts "Links found..."
#find link URIs
links = body.scan(/<a(.*?)href="(.*?)"(.*?)>(.*?)</a>/)
#print all link URIs
links.each {|id,uri| puts uri}PHP
<?php
$page = file_get_contents('http://www.site.com.au/index.php');
// find links
preg_match_all('/<a(.*?)href="(.*?)"(.*?)>(.*?)</a>/', $page, $links);
// links found
foreach($links[2] as $link)
{
print "$link\n";
}
?>
03 May 2007
PHP
A lot of PHP beginners tend to steer clear of regular expressions,
sometimes resorting to using an ugly mixture of str_replace and explode.
That's not surprising, regular expressions can be intimidating. Take a look at this pattern for validating an email address...
^[a-zA-Z][w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][w.-]*[a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$Fortunately, we can accomplish most programming tasks with much easier patterns.
This isn't meant to be a comprehensive guide, so I'll keep it very simple and just demonstrate how easy it is to grab the number of new links from dzone's homepage.
Here is the HTML source code surrounding the new links number.
<li><a href="/links/queue.html" >New links (217)</a></li>And here is the PHP code to fetch the number of new links.
<?php
// fetch the source of the homepage
$dzone = file_get_contents('http://www.dzone.com/');
// find matches for the pattern
preg_match('/<li><a href="\/links\/queue.html" >New links \((.*)\)<\/a><\/li>/', $dzone, $matches);
// print result
echo $matches[1];
?>
We use PHP's preg_match function to search in a string for a pattern.
As you can see, the pattern is just the surrounding HTML with all /)( characters escaped and "(.*)" replacing the number. Too easy.
27 March 2007
PHP
Of course, there is no "better" language, each language has its own strengths and weaknesses. When starting a new project, you need to chose the right tool for the job.
For me, the right tool is still PHP.
If I was starting a web development business tomorrow morning, I wouldn't be writing my codebase in Python or Ruby (although they are nice languages), I would chose PHP for the following reasons:
- Everyone knows PHP
PHP experts are never hard to find, which means a greater selection of job candidates. - There are more PHP resources available
There are many PHP commmunity websites, tutorials, frameworks, classes and articles. - PHP is well supported
Most linux web hosts supports PHP4, and more are starting to support PHP5.
When you're betting your business on a language, you don't want to take any risks. At the moment I see PHP as still the safest choice.
22 March 2007
PHP, Programming
I've been an advocate of seperating logic from presentation for a long time now. But after working on a few large PHP projects lately, I've decided that I need to have loops in my template class, it's too time conusming creating seperate templates to be placed inside loops.
I started off by defining a readable syntax for the loops inside my templates.
<@loop(contacts)
{
<p>Name: {name}<br />
Sex: {sex}</p>
}
@>
'contacts' would be the name of the array I'm going to loop through.
Here is the function that will process the loop. Simply pass a string containing the loop, and it will return the output.
<?php
function parseLoop($loop)
{
$loop_result = '';
// get the name of the loop
preg_match('/loop\((.*)\)/', $loop, $loop_name);
// get the loop contents
preg_match('/\{(.*)\}/s', $loop, $loop_contents);
// get all the vars from loop_contents
preg_match_all('/\{(.*)\}/', $loop_contents[1], $vars);
// loop through the global array
foreach($arrays[$loop_name[1]] as $item)
{
$loop_item = $loop_contents[1];
// loop through every variable found, and replace it with its value in the global array
foreach($vars[1] as $var)
{
$loop_item = @str_replace('{'.$var.'}', $item[$var], $loop_item);
}
$loop_result .= $loop_item;
}
return $loop_result;
}
?>
And here is the array containing the contacts.
<?php
$arrays = array('contacts' = array(
array('name' => 'jane', 'sex' => 'f'),
array('name' => 'bob', 'sex' => 'm')
);
?>
To use the function you need to find the loops in the templates using regular expressions, pass it through parseLoop(), then replace the loop block with the output.
09 March 2007
PHP, Programming
I needed to make a script in PHP to scan a page of text and return the top 10 keywords.
I decided to give more importance to words starting with uppercase characters. I couldn't find any PHP functions available, so I thought I would write my own. Hopefully someone finds this useful.
<?php
$string = 'Titanic';
function isFirstUC($string)
{
if(strstr($string[0], ucfirst($string[0])))
return True;
else
return False;
}
echo isFirstUC($string);
?>