Category: PHP

Commented-out Code is rotting code

One of the things I really hate, and programmers should really avoid is commenting-out code. Do NOT do this!

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
//curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
//curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($ch, CURLOPT_URL, 'http://www.testingsite.com');
$result1 = curl_exec($ch);

curl_close($ch);
?>

You all have seen code like this. Commented-out code you do not know why it is there and if it should be deleted.

IF you work in team or if you work on the code yourself and coming back to it after some while, you and others will not have the courage to delete it. Everybody thinks it is there for some reason and it should not be deleted, because of too important. In the end they all clutter up fine code and make it a rotting code.

Why are those lines of code commented? Are they important? Where they left as a reminder for a change at hand? Or is it just dead code nobody ever took the time to clean up? Aren’t cookies used anymore and why not? Should it be enabled again? Why was the decision made to comment it out. A million questions arise. Those questions make it harder for the reader of the code to understand the story clean code is trying to convey. Remember you are not just writing programs you are writing stories through code. You are not a programmer, you are a story teller. Stories should get better over time and changed to today’s thinking.

Keep your code clean, just delete the code, today we have source revision control systems as a reminder of old code. Use that. You will not loose the code, SVN remembers. Promise.

Warm winter greetings from Belgium
Nick Belhomme

Zend Framework Bug Hunting Day

Hello World,

I know it has been a while, no excuses.

But I have something important to tell the PHP community. Upcoming Saturday 08 November 2008 it is Bug hunting day. This BHD is  organized by phpBelgium and phpGG,  and sponsored by Zend, iBuildings and ServerGrove. If you would like to learn more about Zend Framework this is the day to do it. As this is the framework that will be worked on that day.

This makes it a great opportunity for beginners and experts in the field to sharpen their skills. Everybody has used a program that had bugs and those were very annoying. You hoped those would be fixed in the next release. Well we are going to open up Zend Framework and look at all the bugs that were committed to Zend and try to solve them. This means digging into the code and learning how everything works from the inside out. What a great opportunity!! We always need pratical uses to make studying pleasant and this is surely one of them. So take out your agenda and reserve this Saturday for a trip to Hotel de Goderie at Roosendaal between 11:00h and 17:00h. You would not only work on your favorite framework but also help the community.

It is free so please confirm your participation at Upcoming or at the website of phpBelgium or phpGG.

What to bring:

  • Good Humor
  • Motivation
  • A laptop
  • Money or a prepared lunch as this is not included in the day for people who have not registered. It has been provided by the Sponsors.
  • Another PHP Enthusiast

I will be joining this day, so I hope to see you then.

Happy Bughunting from Sunny Belgium,

Nick Belhomme
ServerGrove Webhosting    Zend The PHP Company     iBuildings The PHP Professionals

Zend PHP 5 Certification – Self Test

Today and from now on, on a regular basis, I am going to write about the ZCE Test.
http://www.zend.com/store/education/certification/self-test.php

I blog about it, because Zend has this great test online but doesn’t provide the answers. I know some of you will benefit greatly by me telling you the whys on every answer. But you should always take the test first!

Question 1
How can precisely one byte be read from a file, pointed by $fp?

A) fseek($fp, 1)
B) fgets($fp, 1)
C) fgetss($fp, 1)
D) fgetc($fp)
E) All of the above

The correct answer is fgetc($fp).
fgetcGets character from file pointer

But this definition on php.net is faulty. Beware fgetc() returns per byte as in the exam.  So if you use this function on a utf-8 formated file, you may encounter problems trying to display the character. As the ô character in the code below is split up over several lines.

Try the following code:

<?php
header('Content-Type: text/html; charset=utf-8');
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>

and create in the same directory the following file: somefile.txt with the following content: “Bientôt!”

This will result in character encoding problems. Please do not forget to save your files in the utf-8 format. You have this ability in all good editors. If your editor does not support this, throw it away, set it on fire and forget about it. Check out Eclipse Zend, Zend IDE , phpED,  Komodo, …

Question 2
What object method specifies post-deserialization behavior for an object?

A) __sleep()
B) __wakeup()
C) __set_state()
D) __get()
E) __autoload()

The correct answer is __wakeup().

 The magic functions __sleep and __wakeup

__sleep
The standard PHP function serialize() checks if your class has a function with the magic name __sleep. If so, that function is being run prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn’t return anything then NULL is serialized and E_NOTICE is issued.

The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not be saved completely.

__wakeup
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Question 3
Where does the session extension store the session data by default?

A) SQLite Database
B) MySQL Database
C) Shared Memory
D) File System
E) Session Server

The correct answer is the File system. PHP saves session data at the end of every request by default in a file in the system’s temporary directory. This is a great solution as it will serve for most websites. But as websites tend to grow and receive more traffic. With more traffic your server gets slow and at a certain point you will want to add more servers, so the work load can be divided between them. At this point you might consider storing session data in a database. Luckily PHP offers a solution to overide the default. session_set_save_handler().If you want more information regarding this issue check out devshed.

Question 4
Which of the following data types cannot be directly manipulated by the client?

A) Cookie Data
B) Session Data
C) Remote IP Address
D) User Agent

The correct answer is Session Data. Everything else can easily be forged. As this information is all stored client side. And Session data is stored server side by your PHP script.

Question 5
What is the difference between isset() and other is_*() functions (is_alpha(), is_number(), etc.)?

A) isset() is a function call and is_*() are not function calls
B) is_*() are language constructs and isset() is not a language construct
C) isset() is a language construct and is_*() are not language constructs
D) is_*() return a value whereas isset() does not

Isset() is a language construct. These are built-into the language and, therefore, they behaves differently than functions. They have their own special rules. Check out the following code.

<?php
/* Variable functions, PHP supports the concept of variable functions. */
$fruit = array('banaan', 'apple');
$variableFunction = 'is_array';
var_dump($variableFunction($fruit));

/* But Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like.*/
$variableFunction = 'isset';
var_dump($variableFunction($result));
?>

This code will result in a fatal error.

Question 6
What will be the value of $b after running the following code?

<?php
$a = array(‘c’, ‘b’, ‘a’);
$b = (array) $a;

A) TRUE
B) array(‘c’, ‘b’, ‘a’)
C) array(array(‘c’, ‘b’, ‘a’))
D) None of the above

The correct answer is array(‘c’,’b’,’a’) as (array) is a type conversion operator also known as a cast operator.

The casting operators allow you to cast variables to new types. Unlike the settype function, they return a value that is the value of the variable cast in the new type.
It is used simply as the data type you want to convert to enclosed in brackets and placed before an expression.

The casting operators are:

  • (int) or (integer) to cast to an integer
  • (float) or (real) to cast to a floating-point number
  • (string) to cast to a string
  • (bool) or (boolean) to cast to a boolean
  • (array) to cast to an array, in this case it is already an array, so no changes are being made to the array
  • (object) to cast to an object

Question 7
Which of the following function signatures is correct if you want to have classes automatically loaded?

A) function autoload($class_name)
B) function __autoload($class_name, $file)
C) function __autoload($class_name)
D) function _autoload($class_name)
E) function autoload($class_name, $file)

The correct answer is __autoload($class_name).

Question 8
What is the best way to run PHP 4 and PHP 5 side-by-side on the same Apache server?

A) Run one as an Apache module, the other as a CGI binary.
B) Run both as a CGI binary.
C) Just use .php4 for PHP 4, and .php for PHP 5.
D) Use .php for both but use different document roots.

You should run one as an Apache module, the other as a CGI binary.

Of course PHP as a CGI is not quite the same as an Apache module, performance / $_SERVER variable-wise.  You’ll get better performance with PHP setup as a module. Not only will you not have to deal with the CGI performance hit,  but if some of your scripts use basic http authentication, they do not work if you run PHP as a CGI. Naturaly there are ways around this, but that is what Google is for.

I hope you learned some stuff, and I’ll see you at the next Zend Certified Engineer 8 questions test.

Sunny greetings from Belgium
Nick Belhomme

Ps. Do not forget to bookmark: http://www.zend.com/store/education/certification/self-test.php and take the test as it will keep you sharp or prepare you to take the real ZCE  exam!

Another Project Succesfully Completed

Dear readers,

I am really enthused about the project that was completed today. After months of dedicated work the Belgacom Skynet team and its partners really delivered. During this time I have been working in a great team which consists of web developers, integrators, database engineers, managers, editors, functional analysts and testers. The spirit and the drive of this amazing team is through the roof. Like I said in one of my previous posts “Never work a day in your life again” work really doesn’t feel like a job when you love what you do. The project consists of 6 (SIX!!) complete new websites. No matter what age you are, no matter your interest, if you can read dutch or french it will get you hooked in one two three. Let us look at the websites one at the time.

Skynet News
News and Sport:

If you are interested in the daily news the content of this segment is immense. It ranges from the latest news in Belgium, the world, politics, entertainment, economics, sport to the latest results from the lottery.
You can read thousands of articles or view the videos in streaming format.

It also has a handy weather feature. If you want to know the weather conditions for the upcoming days just look it up at the click of a button.

Skynet Lili
Lili:

This site is especially for women. Ranging from pregnancy to showbiz gossip. Read up on wellness, gastronomy, feelings, kids, family,…


Skynet Jack
Jack:

The fast lane. Cars, stock and finance, babes, adventure, lifestyle, gadgets…

Skynet Entertainment
Entertainment:

Concerts, movies, music and so much more. The one stop for leisure time.
You can download the latest charts, view the latest trailers and read up on the blogs of other people interested in entertainment.


Skynet Services
Services
:

A couple of keywords:

  • Route planner
  • job seeker
  • car finder
  • buy and sell
  • dating
  • search
  • yellow and white pages



Skynet Mobile
Mobile:

All proximus customers will be pleased to read that all the services from live.proximus.be are integrated in this easy to navigate segment.



I hope you have fun surfing on the latest project I am involved in. I plan on doing a lot more projects in the future, but this will always be one of the sweetest. The next big thing should be the completion of my book: the lives of the very successful.

Sunny greetings from Belgium

Nick Belhomme
Always looking for ways to stretch my capacity.