Good Old sscanf
February 28, 2008 on 6:06 am | In PHP | No CommentsWorking in PHP, all this time, and the big uses you find in regex, and all the string processing we need to, could make us forget our old friend that can easily solve a problem.
sscanf, do you remember it, well, for quite some time I didn’t, until I saw it in a random code I found online, so this post is a reminder that this function exists.
An example, if we have a date, lets say coming from a Mysql DB, (ofcourse you can use strtotime, but sometimes it has it’s limitations) and you want to get the year, month, day, hour, minutes, and seconds, and you have it in a string, you can parse it with some splits, but 1 call of sscanf can do the job.
$date = ‘2007-05-18 22:15:03′;
sscanf($date,‘%d-%d-%d %d:%d:%d’,$y,$m,$d,$h,$i,$s);
var_dump($y,$m,$d,$h,$i,$s);
and thats all.
PHP5 CAPTCHA
February 16, 2008 on 3:19 pm | In Free Software & Open Source, PHP, Releases | No CommentsI’ve written a small CAPTCHA library, in an OO style, and I love to share it with you
http://sourceforge.net/projects/php5captcha/
Once Again I Failed To Fail
November 25, 2006 on 3:26 pm | In PHP | 1 CommentAfter my first failure to fail, now I hold the Zend PHP 5 Certification, it was a tough day day for me, it was like:
6:30
I started the second Mock-Up Exam, I passed it, but my results were worse than the first, “OK Ala’a, don’t panic, you might just be tired”, So I went took a bath a done some stuff.
9:30
My colleague, who’s supposed to take the exam with me, came online, and he wanted to talk the Mock-Up exam.
Me: but i don’t think that you have enough time left.
He: Do you think so.
Me: it’s 9:30 …
He: Yeah I noticed that.
Me: you have an hour and a half till the test.
Me: Unless you do it fast …
He: do u suggest to review the book! or take the test ??
Me: no take the test, that’s better.
10:05
I’m ready to leave, I closed the computer, and went to the door, I put my hands in my pocket, the keys are not there. “Damn, where did the keys go” I thought. I started looking around, I was starting to panic. “Don’t panic, you’ll find them” I thought.
I started searching, that lasted for 30 seconds, and then I panicked, I started throwing everything, and I found the keys, I don’t want to know how did they get there, I was glad I found them.
10:45
I reached the test center, everything went smoothly.
11:00
My colleague and I started the test.
11:40
I’ve answered everything, but I’m not sure about anything, I hate tests, now I have to click on the “End Exam” button. I clicked on it, and a confirmation message popped-up, I was so unsure, I started moving the message all over the screen, until I had the guts to press “OK”. And my longest period of time in this day was then.
“Processing ….”
“What if I failed”
“Processing …”
“I should’ve answered something else”
“Processing …”
“I should’ve postponed the test”
“Congratulations, you passed”
“Yes!!!!” I screamed.
“Congratulations …”, My colleague said.
“Thanks, Hope the best for you”, I said.
“Pray for me”, he said.
“I will”, I replied.
12:00
My Colleague gets out of the test room, …., He passed.
WoooooooooooooooW, I’m glad that everything went OK today.
Playing with PEAR Net_IMAP
November 22, 2006 on 12:54 am | In PHP | No Commentswhen it comes to IMAP programming, you should be very careful about IMAP commands you are issuing, an unneeded call can make your page much slower, that’s why usually IMAP Developers avoid programming with the php IMAP functions, yes they are written in C (c-client), but they don’t give you the commands you want exactly, so usually you would go for native IMAP (i.e. writing commands to a socket, and parsing the output).
Parsing is never an easy job, lot’s of cases and lot’s of bugs can appear, PEAR have a nice library called Net_IMAP, but of course, it doesn’t give you the freedom you need, so I use the IMAPProtocol class from it, as what I need is parsing only, I know the command, I just want to issue them, and to get them parsed.
for example to fetch the headers of a message
<?php
$imap->cmdConnect($mailhost,$mailport);
$imap->cmdLogin(”$username@$domainname” , $password);
$imap->cmdSelect($mailbox);
$msgHeader = $imap->cmdUidFetch($message_uid,’BODY[HEADER]‘);
$imap->cmdLogout();
?>
That looks fine, but Imagine this case, you have to sort the mailbox according to the From header, well of course you can do something like the code above, i.e. fetch the headers of all the messages, and parse for the From header, and sort accordingly, but the headers of messages are not a small part, you can have 25 lines for each message while you only need 1, which would slow down your page. if you have some experience with IMAP you would know that you code do this with a command like
A0001 FETCH 1:* (uid body.peek[header.fields (From)])
OK if you try this on IMAPProtocol, in the standard way, i.e $imap->cmdFetch(”1:*”,”(uid body.peek[header.fields (From)])”);
you would get lots of errors telling you that it’s not supported, so what should you do????
well here you have to do parsing yourself, but how can you do that, take a look at the code below:
<?php
$imap->_getCmdId();
$imap->_putCMD($cmdid,’FETCH 1:* (uid body.peek[header.fields (From)])’);
$nsarray=explode(”\n”,$imap->_getRawResponse( $cmdid ));
foreach ($nsarray as $line) {
if(strstr($line,”FETCH (UID “)) {
$UID_array[] = (int) (substr($line,strpos($line,”UID “) + 4));
}
if(strstr($line,”From: “)) {
$msgs_to=trim(strtolower(str_replace(”From: “,”",$line)));
$from_array[]=$msgs_to;
}
}
?>
Why would I do that, well My page is full of IMAPProtocol code, and I want to add the feature of sorting, I can’t just drop the whole page, and I want to make the best performance I can, in the less time I can.
Hope it was useful.
Value Design Pattern
October 22, 2006 on 4:00 am | In Design Patterns, PHP | No CommentsSometimes while you are coding, you need some kind of a wrap for some primitive data type such as an integer, just to add some feature that is not available directly from that primitive data type, or just to give it some identity.
A Date, Integer, or Dollar class is a handy - and inexpensive - encapsulation, easily copied, compared, or created when needed.
For example managing Bytes and printing them can be something annoying, for example, when ever you need to print the number of Bytes in a file, you would like to check if it can be represented in KB, MB, or GB.
So what I’m going to do here is to wrap the integer datatype into a Byte class, and override it’s __toString function (one of the magic functions in PHP 5) so every time time I need to print it a simple print would do the issue.
Our example here would be for a mailbox, every mailbox has a quota, I want to give it a starting quota, then increase it, so first I’m going to write the Test for it (Using simpletest).
<?php
// …. includes and stuff
class TestByte extends UnitTestCase {
function testQuotaByte () {
$this->>UnitTestCase(”Test Byte Value”);
$startingQuota = new Byte(1048576); // One Mega
$mailbox1 = new MailBox($startingQuota);
$mailbox2 = new MailBox($startingQuota);
$this->assertEqual(1048576,$mailbox1->getQuota()->getBytes());
$this->assertEqual(1048576,$mailbox2->getQuota()->getBytes());
$mailbox1->increaseQuotaBy(new Byte(524288)); // add 512KB
$this->assertEqual(1572864,$mailbox1->getQuota()->getBytes());
$this->assertEqual(1048576,$mailbox2->getQuota()->getBytes());
$this->assertEqual(1048576,$startingQuota->getBytes());
}
}$test = new TestByte();
$test->run(new HtmlReporter());
?>
Here I created to Mailboxes, and gave them a starting quota of 1 MB, after that I added 512 KB to one of them, and checked that it was added, and that the other mailbox and starting Quota was not changed.
Let’s start with the implementation:
<?php
class Byte {
protected $amount;
protected static $Names = array(”B” => “B”,
’KB’ => ‘KB’,
’MB’ => ‘MB’,
’GB’ => ‘GB’,
’TB’ => ‘TB’);function __construct($bytes) {
$this-$gt;amount = $bytes;
}public function add(Byte $bytes) {
$this->amount += $bytes->getBytes();
}public function getBytes() {
return $this->amount;
}public function getKB () {
return $this->amount/1024;
}public function getMB () {
return $this->amount/1048576;
}public function getGB() {
return $this->amount/1073741824;
}public function getTB() {
return $this->amount/1099511627776;
}public function __toString() {
if($this->getTB() >= 1) {
return number_format($this->getTB(), 2, ‘.’, ‘ ‘)." ".self::$Names['TB'];
} elseif ($this->getGB() >= 1) {
return number_format($this->getGB(), 2, ‘.’, ‘ ‘)." ".self::$Names['GB'];
} elseif ($this->getMB() >= 1) {
return number_format($this->getMB(), 2, ‘.’, ‘ ‘)." ".self::$Names['MB'];
} elseif ($this->getKB() >= 1) {
return number_format($this->getKB(), 2, ‘.’, ‘ ‘)." ".self::$Names['KB'];
} else {
return "$this->amount ".self::$Names['B'];
}
}
}
?>
and The Simple MailBox :
<?php
class MailBox {
protected $quota;function __construct(Byte $quota) {
$this->quota = $quota;
}public function getQuota() {
return $this->quota;
}public function increaseQuotaBy(Byte $addedQuota) {
$this->quota->add($addedQuota);
}
}
?>
OK Let’s run the test.
TestByte
Fail: testQuotaByte -> Equal expectation fails because [Integer: 1048576] differs from [Integer: 1572864] by 524288 at [/some/Location/TestByte.php line 19]
Fail: testQuotaByte -> Equal expectation fails because [Integer: 1048576] differs from [Integer: 1572864] by 524288 at [/some/Location/TestByte.php line 21]
1/1 test cases complete: 3 passes, 2 fails and 0 exceptions.
What happened here? this code now points to ($this->assertEqual(1048576,$mailbox2->getQuota()->getBytes());) and ($this->assertEqual(1048576,$startingQuota->getBytes());) lines, Any Idea?
Here is a hint: in PHP 5 Objects are passed By Handle (Something like reference, yes similar to Java) not by value, is it clear now?
Another hint: They all point to the same Byte Object.
So actually changing one of them is changing them all.
So, how do you implement a lightweight, or easy to construct, descriptive object like Byte?
Lightweight objects should behave like PHP integers: if you assign the same object to two different variables and then change one of the variables, the other variable should remain unaffected. And indeed this is the goal of the Value Object pattern.So now we need to make the Byte Object immutable (i.e does not change once it’s been set).
OK it’s so Simple in our example, for the Byte class we change the add function to
<?php
//…
public function add(Byte $bytes) {
return new Byte($this->amount + $bytes->getBytes());
}
//…
?>
also remember to change the MailBox class increaseQuotaBy function as now $quota is not changed in the add operation
<?php
//…
public function increaseQuotaBy(Byte $addedQuota) {
$this->quota = $this->quota->add($addedQuota);
}
//…
?>
running the test
TestByte
1/1 test cases complete: 5 passes, 0 fails and 0 exceptions.
Viola!!, everything is cool.
Hope this article was useful, once again if you have ant question, don’t hesitate to comment
Testing your code
October 21, 2006 on 7:50 am | In PHP | No CommentsPerhaps no other coding practice is as important as testing your code. Also in the nature of Business Development, where parts of your code always change on the request of a client (including Management), or even when you want to make your code run with better performance, Automated tests are highly needed, you can’t just spread your print statements all over your code every time you need to test it.
With automated tests, you can just be sure that your interface is not broken after some change, you just run your tests, if they succeed, you know that you didn’t break your code (this means you should right good tests).
Let’s start by a simple example, Imagine that we have been asked to test PHP’s built-in Array. One bit of functionality to test is the function sizeof(). For a newly created array we expect the sizeof() function to return 0. After we add an element, sizeof() should return 1. (I know it’s not a big deal, but it’s just an example).
you can do it with simple print statements (i.e. print (1 == sizeof($myArray) ? "OK":"Failure").PHP_EOL; ), but here we are going to do it by using an assertion function.
<?php
$fixture = Array();
assertTrue(sizeof($fixture) == 0);$fixture[] = "element";
assertTrue(sizeof($fixture) == 1);function assertTrue($condition) {
if (!$condition) {
throw new Exception("Assertion failed.");
}
}
?>
Well, we could know if something went wrong if some Exception was raised, of course assertTrue is not the only thing you want to do, UnitTesting has gone far beyond that, usually UnitTesting frameworks provide a whole lot of features that you need for your testing.
Lot’s of Testing frameworks are available for PHP, I’m going to point to 2 of them, the first one is SimpleTest (http://simpletest.org/), it’s written in PHP 4 (Although they are going to migrate to PHP 5 when they reach version 2), so you can use it on both PHP 4 and 5 programs, also it includes a nice HTML reporter for some good looking html results the same test above could be written using this framework as:
<?php
require_once ’simpletest/unit_tester.php’;
require_once ’simpletest/reporter.php’;class TestingFixtureArray extends UnitTestCase {
function TestArray() {
$this->UnitTestCase("Testing Fixture Array");
$fixture = Array();
$this->assertTrue(sizeof($fixture) == 0);$fixture[] = "element";
$this->assertTrue(sizeof($fixture) == 1);
}
}//run the Test
$test = new TestingFixtureArray();
$test->run(new HtmlReporter());
?>
Another Well know testing framework is known as PHPUnit2 (http://www.phpunit.de/), it’s available through the PEAR Repository, you can install it as
$ pear install PHPUnit2
It’s written in PHP 5, and is so widely used within PHP Developers, a good resource for learning how to use it is the free available online book PHPUnit Pocket Guide (http://www.phpunit.de/pocket_guide/index.en.php), the same example could be:
<?php
require_once ‘PHPUnit2/Framework/TestCase.php’;class ArrayTest extends PHPUnit2_Framework_TestCase {
public function testNewArrayIsEmpty() {
// Create the Array fixture.
$fixture = Array();// Assert that the size of the Array fixture is 0.
$this->assertEquals(0, sizeof($fixture));
}public function testArrayContainsAnElement() {
// Create the Array fixture.
$fixture = Array();// Add an element to the Array fixture.
$fixture[] = ‘Element’;// Assert that the size of the Array fixture is 1.
$this->assertEquals(1, sizeof($fixture));
}
}
?>
and you can run it on command line as
$ phpunit ArrayTest
Additional benefits that you can realize by thoroughly testing your code:
- Testing forces you to write code that is easily testable. This leads to looser coupling, flexible designs, and good modularity.
- Writing tests forces you to explicitly clarify your expectations of how your code is to behave, distilling your design into sharper focus from the beginning. Writing tests forces you to consider the universe of possible inputs and the corresponding results.
- Tests are very explicit way of communicating the intent of your code. In other words, test cases act as example and documentation, showing exactly how a given class, method, or function should behave. A test case defines how code works in a non-ambiguous way.
Finally, if your test suite - your set of test cases - is very thorough, you can say your code is complete when all of your test pass. Interestingly, that notion is one of the hallmarks of Test Driven Development.
Test Driven Development (TDD), also referred to as Test First Coding, is a methodology that takes testing one step further: you write your tests before you ever write any code. A nice, brief summary of the tenants of TDD is available at http://xprogramming.com/xpmag/testFirstGuidelines.htm, and a good introductory book on the strategy is “Test Driven Development: By Example” by Kent Beck. (The book’s examples are in Java, but it’s a quick read and gives you a very good overview and introduction to the subject.)
Agile Development
Recently, unit testing - in particular Test Driven Development - has been associated with agile Development methodologies such as Extreme Programming (XP)g that focus on rapid iterations of releasing functional code to customers and welcoming changing customer requirements as a natural part of the development process. Some good online resources for learning about agile development include:
- http://en.wikikpedia.org/wiki/Agile_software_development
- http://agilemanifesto.org/
- http://www.extremeprogramming.org
if you have any question regarding this post, just drop a comment, and I would be more than happy to answer (if I could :P)
Boosting Up PHP Performance with Alternative PHP Cache (APC)
September 20, 2006 on 4:38 am | In PHP | No Comments“Every single server has it [APC] at Yahoo, and it handles billions of requests per day” Said Rasmus Lerdorf, the creator of PHP, at the php|works conference.
Parsing and compiling speed can be significantly boosted with the use of an opcode cache.
In PHP, as with most scripting languages, code is parsed from human-readable to machine-readable instruction. The machine-readable script is known in PHP as opcodes.
An opcode cache stores or caches the compiled code in shared memory so that the code compilation for similar operations only needs to happen once.
PHP 6, which is still in development, will have opcode cache built in by default.
For current PHP 5 users, there are various opcode cache implementations that can be used, including the Alternative PHP Cache (APC), which is what Lerdorf recommended.
Installation (Linux):
APC is available via PECL Repositry, you can install it vie `pear install apc`, but it would fail if you compiled apache alone (didn’t install a binary package .deb or .rpm), so it could be a little bit tricky, I’m going to show you how to install it given that apache and php were compiled alone, and they are in there default locations
download it from http://pecl.php.net/get/APC-3.0.12p2.tgz
$ tar xzf APC-3.0.12p2.tgz
$ cd APC-3.0.12p2
$ phpize
$ ./configure –enable-apc-mmap=yes –with-apxs=’/usr/local/apache/bin/apxs’
you can replace /usr/local/apache/bin/apxs with your location to apxs e.g. /usr/local/apache2/bin/apxs if you installed apache2 in it’s default location
$ make
$ make install
After that you have to load it in php.ini
Be sure that extension_dir = “/usr/local/lib/php/extensions” or whatever your extentions folder is
add a line:
extension=no-debug-non-zts-20050922/apc.so
fix it according to the location of apc.so
try it out, it really Boosts Up your PHP applications performance
Is PHP Insecure?
September 14, 2006 on 5:56 am | In PHP, Philosophy | No CommentsHim - PHP is Insecure.
Me - What makes you say so?
Him - I read it in a book.
Me - And what have you read exactly?
Him - I can’t remember, I’ll send you the book.
and he did actually send me the book, I read it, it was about 70 pages, actually I guess it was first an e-zine or something from some hackers website or mailing list, what ever. after that I saw the guy.
Me - Did you read the book, or just skimmed through.
Him - No, I read it.
Me - Do you know anything about PHP.
Him - Yeah, I wrote some scripts.
Me - OK, first of all the book does not talk about any PHP vulnerability, and the examples he gave for his hacks were just a stupid code, and if anyone working in this industry writes code like that, he should have a capital punishment.
Him - what, no no it just that PHP is not secure.
Me - ok here is the book, tell me where does it say that PHP is not secure.
Him - in the first chapter he says about a vulnerability in the include function.
Me - Yeah I noticed that, first of all include is not a function it’s an operator, second thing the code says something like
<?php
include ($page);
?>
and he says that when register_globals is turned on you can override the $page.
OK where did the $page variable came from, it should have come from somewhere, and at this somewhere it would be set, unless the coder is depending on that register_globals is on, and he is expecting the $page variable to from an input of the user, well it’s one of the extremely basic thing in programming that you have to validate user input. So it’s not a vulnerability in PHP itself, it’s a vulnerability in the developers code, which marks him as an idiot who should not put any code online, unless he is trying to win the most hacked site of the year, which also marks him as stupid cause after the first hack his application would be down, and maybe shredded all over, after the second I guess he would be fired.
Him - but it’s also PHP’s problem, why does it allows such code.
Me - really, a stupid programmer can make this vulnerability in any language you want.
Well the point is not just related to PHP, it’s also related to any programming language, usually lots of inexperienced developers, blame there errors on a programming language. Yeah some bugs could come from the programming language, but it’s very rare, and if so, programmers learn how to avoid it.
And another problem, is that people like Him, believes these things without really knowing, and most of them defend it like their lives.
Story Morals:
Don’t blame others for your mistakes, try to find out where you’ve been wrong first.
Don’t defend ideas you know nothing about, if you think they are right, try to investigate them first, at least when someone asks you about it you would have a more reasonable thing to say other I heard it, or I read it in a book.
Zend Certificate: PHP5 Exam Festival
June 3, 2006 on 12:19 pm | In PHP | No CommentsA PHP5 Exam Festival is being prepared in Amman by the end of July - first of August. Event will be sponsored by Zend.
Taking a look at PHP 6
March 14, 2006 on 8:50 am | In PHP | No CommentsWhile most web hosts are still in the PHP 4 era, the PHP developers are already planning and working on PHP 6. Lets have a look at what’s been keeping them busy.
More
Powered by WordPress with Pool theme design by Borja Fernandez.
Entries and comments feeds.
Valid XHTML and CSS. ^Top^




