Archive for the ‘PHP’ Category

PHP classes autoload (namespaces)

Wednesday, April 20th, 2011

I like PHP, OOP is very easy with it and Zend Framework is a charm once you start to get use to it.

One of the coolest things in the latest release of PHP are namespaces, really they are cool! Weird as it may sound coding in PHP reminds me of Java ;P Namespaces allows me to give some order to my code and avoids overwriting other code, it’s pretty neat but one thing I’ve been meesing around is autoloading namespaced classes.

After a few hours I’ve managed to code a simple classes and namespaces autoloader, it’s the first version so I’ll be enhancing it over the next days.

I’ll try to make it as clear as possible. Code will be commented. Hope it helps someone 😀

Ok there are two kinds of files I want to autoload: namespaced classes and normal classes.

For both of them I’ll need a path:


Now to the function!

For standarization purposes class names can be camelcase but when searching the file’s name it must be lowercase.

I’ll code the body of the autoload function provided by php.

function __autoload($class){
  $class = strtolower($class);
    $class = preg_replace('/\\/',DIRECTORY_SEPARATOR,$class);
    require_once (NMSPCS_PTH . DIRECTORY_SEPARATOR . $class . ".php");
    require_once (CLSS_PTH . DIRECTORY_SEPARATOR . $class . ".php");

That’s it… now I just read about a php function called set_include_path and just saw other way to autoload classes… I’ll leave that for version 2 hehehe

.htaccess maintenance

Wednesday, April 13th, 2011

Again a while since the last post but honestly I have a lot of work to do, fortunately one of the projects I’m involved requires me to learn Python.. at last!

Anyway, one division of the company hired a third party to develop a web page. The provider finished the development and finally sent everything to us. It was a php webpage, it uses the Cake Framework and MySQL so everyone thought it was going to be very easy to release the webpage in the company’s server.

A few weeks before today we decided to order the site folder and create special boxes for mini sites and small projects, even though url may seem as if the folder is directly under the web server root, it isn’t. This is cool because it keeps things from being a mess and maintenance becomes pretty easy.

So, as I was saying, we got the scripts for both the site and the database. Database was easy, we just imported the sql file and voilá! done!

The problem rised when we got to the site’s scripts. We typed the url correctly and ¡nothing! so we were surprised, everything was working fine so it wasn’t possible for a single site not to work. We read the logs, enabled the debug and nothing raised. After a few days we decided that the provider should help us. So he happily agreed to bring his people to help me…. same result. Something strange was happening, finally the provider quit and told us that the development was working on their servers and they were happy with that…. sorry :s

I got mad because of this but my boss and I decided we should dig this in. After a few days we found the cause of the problem. When we ordered the web server folders we enabled an alias to a folder. Cake uses htaccess files to provide MVC functionality. When we enabled the alias folder we forgot to enable htaccess parse, duh! so we learned that each directory that will be included on a web server should have a conf line like this:

<Directory /absolute/path/to/alias/folder>
Options -Indexes Includes FollowSymLinks MultiViews ExecCGI
AllowOverride All
Order allow,deny
Allow from all

We added the proper lines, modified the htaccess rewrite rules to support 2 different domains and now everything works.

We keep learning everyday 😀

Ad Vitam Paramus

Zend Framework 101

Tuesday, February 8th, 2011

Ok, it’s being a while since I last published something here.

I’ve been digging into Zend Framework trying to understand everything so I can code easily. So far I’ve discovered that way too many PHP programmers get confused about three basic definitions.

Zend Framework

As stated before, Zend Framework is a library with a bunch of classes for almost everything (Auth, ACL, DB connections, etc.) this is important, cause I’ve noticed that way too many PHP programmers are confused with ZF being a new way of coding and setting up your application.

With pure Zend Framework you may use any class you want whenever you want to use it, just be sure to include the ZF library path and you’re done.


Now, while reading about ZF programmers may found a lot of talk about MVC, this stands for Model-View-Controller which is a coding paradigm I won’t explain cause there’s a lot of info about it in the web (Google it).

Here is where you start dealing with the bootstrap, configuration file, error handling and main setups.

ZF Tool

This stands for Zend Framework tool which basically is a bat/bash script that you may use from the command line to automatize some coding if you’re using Zend Framework and MVC. It’s pretty useful and you have the possibility to modify/enhance this script as you wish. If you won’t be coding with MVC you might as well forget about this tool.

Having these three basic definitions we can start discussing the framework. ZF, as I already stated, has a bunch of useful classes which are very simple to use. I know some of you will raise your voice and argue that it isn’t and that you have to place code in the bootstrap and then make a later call in a model and it might become confusing, if so let me remind you that right now I’m just writing about the ZF not being used within a MVC coding paradigm. By this I’m trying to make you understand that ZF can be used to code applications as you being doing for years as long as you are used to OOP.

Let’s see an example of how ZF helps you code faster. I’ll do a simple auth script.

I wont be pasting any HTML or javascript code, I’m assuming you can figure those out.

So, suppose you have a form that sends the login and password to dologin.php, in the php file you’ll have something like this:

Include's, require's, session's code.
/* After receiving, validating and filtering your input you'll define where do the user credentials are stored */
$login = $_REQUEST['login'];
$password = $_REQUEST['pass'];
//Create a database adapter
$dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter();
//Create the auth adapter
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
//Configure the auth adapter with the proper table name and credential fields.
//Give the auth object the info to validate
//Call the auth instance
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
//Some code to process the response
//Go to login, credentials are wrong
//Store identity
//Get user data, but avoid retrieving the password
$userData = $authAdapter->getResultRowObject(null,'password');
//Write data to auth object so object is modified
//Do more stuff

So that’s it for the login. It’s pretty simple, and you can make it even more complex by adding some constraints, for example a user row that indicates if that user has been deactivated (Play with it and read the ZF documentation regarding this).

Now let’s say you want a page only to be available for logged in users. You won’t need to authenticate again your user, just call the auth object like this:

//Some code of your own
//Get auth object
$auth = Zend_Auth::getInstance();
echo('You\'re in!');
echo('Ooops! sorry, you need to login first');

So there you go, quite simple isn’t it.

Hope this helps you start playing with ZF. I’ll post more stuff in the go.

Thoughts on Zend Framework

Thursday, October 21st, 2010

Well I’ve jumped into the Zend Framework development… finally!

At first glance it looks like a mess, create the environment, separate models, views and controllers, configure the app, the bootstrap…. When I started working here (my current job, which I can’t give the name due to the terms of my job contract) I was hired because of my knowledge of PHP. Business owners stated that they needed a high profile PHP programmer. They said they were moving towards PHP development under Zend Framwork. Cool! a new learning experience.

I must say that when I got here I wasn’t familiar with ZF so it was a whole new experience. Days went by, and anfter a couple of months I have realized what is Zend Framework and why everybody thinks it’s too complicated. There is a big confusion even from Zend.

The confusion begins from the ZF tutorial. They start explaining you about MVC… here’s the whole confusion.

Zend Framework is a set of libraries that can help you with RAD, it has nothing to do woth MVC paradigm.

MVC is a coding paradigm, such as the three layers paradigm. You can code your whole application in whatever paradigm you wish and still use Zend Framework, but Zend treats both the paradigm and the set of libraries as the same. I’m not arguing that something is wrong, what I’m saying is that Zend Framework is one thing and MVC coding paradigm is a whole different one.

Do not be confused! MVC & ZF are a great, neat way of doing things but, as every technology, you should evaluate if both are needed for every project. If you are coding a simple web service then you might not need to use MVC but still use the framework to RAD.

Do a little research, clarify your needs and make the perfect choice for the case you’re dealing. Sometimes MVC can create a lot of garbage folders and files that wont be used at the end of the day.

Remember: KISS (Keep It Simple, Stupid)

Code maintenance

Wednesday, October 20th, 2010

Keeping track of code through time is a very delicate task.

It gets to be a really important issue when customers are making usability tests to a program. You make some changes, the customer reviews them, approves and you send them to production, a couple of days later the customer changes his mind and ask you to go back to how the program looked 3 months ago.

That scenario gets to be very common in web development and can be a serious problem if you don’t give your customer what he wants. How could you go back to a 3 months old version of a page? Did you backed up your files? Is your presentation layer different from the logic one? What has changed since then? How can I merge those changes?

Changes are part of software life, so they must be documented properly. Changes documentation should answer the following:

Who made the change? If something goes wrong you may identify who made what and the settle responsabilities.

What changes were made? You should keep track of what files were affected, what code lines were modified and what was changed in the logic.

When were those changes made? You’ll keep track of time invested on that change.

Why? Was it because of a user request?, a bug fix?, an enhancement?

If you work for a company answering these questions will prove to be a great way to justify your work. It will even make it easier for your colleagues to keep up with your coding style and logic.

Most developers use inline comments to document changes for example:


* author: Me

* date: October 25th 2009

* version: 1.0.1

* summary: User asked for the color to be changed from red to blue so the code changed from $color = “red”; to current


$color = “blue”;

That’s a nice way to keep track of changes but you’ll get to the point that one change requires a lot of file content modifications, folder creations, code logic changes, etc. which on large projects can be a real hell to keep track of. This just happened recently on my job.

We solved a lot of things by using a version control software. We tested it and finally decided to go for SVN or subversion. It’s pretty easy.

Even though projects creation and repositories administration were a mess at the begining because we wanted to limit access to developer groups only to their assigned projects. We kept SVN and installed USVN on  top of it…. needles to say we are very very happy with the results.

We get to admin our repositories in a very simple way. Since USVN is developed in PHP Zend Framework and you get to modify the code we have made some customizations to it so it works as we want it to work.

One great thing we managed to do with SVN is have a strict control over our stage environment. Developers do a SVN commit which immediately updates a stage environment so changes are visible to QA.  Once QA approves a version we create a tag meaning its a new release which then goes to production.

That’s the main reason I’m posting this, I was the one responsible for implementing those automations and they do work.

How did I do this? Well it’s actually pretty simple. Once a SVN project is created you go into that project’s folder and go to the hooks subfolder. This is where the magic happens.

Though there are several types of hooks I only messed with the post-commit hook.

I granted execution permissions to post-commit file (remove the “.tmpl” part).

Modified the hook so its aware of some important paths and then coded a few lines so, for example, we got SVN to send an email reporting what changed, who did the changes and when was the code commited to project owner so he could keep track of his project.

SVN works for us right now and hooks are a charm. I’m pleased right now and so are my boss and my colleagues :D:D:D:D

I keep repeating to myself: Linux rocks, free software rocks and most of all I rock! hahahahahaha

PHPMailer & Hotmail showing an empty or blank screen

Tuesday, July 27th, 2010

Yes, as it reads.

I’ve been using PHPMailer class for a while but only a few days from now I received a complaint from a customer that told me he got an empty email with his order confirmation.

At first I assumed he was the only one experiencing this so I told him to tweek his Hotmail account or move to Gmail, Yahoo or a better service provider. Next thing I knew a couple more customers sent me an email with the same complain.

So, it’s only happening with Hotmail… Time to do some tests.

To my surprise email was arriving to destination address but it was showing nothing, it was a blank/empty email body. No way! somethings gotta be wrong! I right clicked the message and selected the view source option.

Ok, message content was there so something else is happening. Email headers, boundaries… something is causing the email not to be shown.

After a couple of days of searching and testing I came to this simple solution.

Go to phpmailer.class.php

Then search for code lines that look like this:

$result = ”;

switch ($this->message_type) {

case ‘plain’ :

$result .= $this->HeaderLine ( ‘Content-Transfer-Encoding’, $this->Encoding );

$result .= sprintf ( “Content-Type: %s; charset=\”%s\””, $this->ContentType, $this->CharSet );


case ‘attachments’ :

case ‘alt_attachments’ :

if ($this->InlineImageExists ()) {

$result .= sprintf ( “Content-Type: %s;%s\ttype=\”text/html\”;%s\tboundary=\”%s\”%s”, ‘multipart/related’, $this->LE, $this->LE, $this->boundary [1], $this->LE );

} else {

$result .= $this->HeaderLine ( ‘Content-Type’, ‘multipart/mixed;’ );

$result .= $this->TextLine ( “\tboundary=\”” . $this->boundary [1] . ‘”‘ );



case ‘alt’ :

$result .= $this->HeaderLine ( ‘Content-Type’, ‘multipart/alternative;’ );

$result .= $this->TextLine ( “\tboundary=\”” . $this->boundary [1] . ‘”‘ );



Do you see the line where it reads: multipart/alternative

Change that into multipart/mixed

That’s it! Hotmail will display your AltBody content!

It worked for us so if it doesn´t work for you, then better start messing with the headers 😀

PHP, Oracle and encodings

Thursday, July 22nd, 2010

As I had previously posted I’m involved in several PHP-Oracle projects.

One involves ecommerce.

We’re doing this ecommerce for Latin America so it should handle special characters such as accents, ñ and others. Web page encoding is iso8859-1.

Every time a user made an insert, the database was recording a ‘?’ character instead of accents or other latin chars.

We tested for utf8_encode and utf8_decode functions, they were useless so we figured it out that the database was storing info in some other encoding. We added apache conf and meta headers to view the page as utf8 but again garbagge was being stored.

We were really angry so we started googling for some answers.

First of all we needed to know what encoding was the database using. We found out with the following query:


We got this from here.

After that we understood that we needed to enable the proper encoding for Oracle and PHP, how did we do it?

After a while we ended here.

So the solution was very simple. We added the following line to the main conf file:


After that we added utf8_encode and utf8_decode to the code and voilá! everything is working fine!

It was indeed a very exhausting work to figure this out so I’m posting it here to have a quick access to the solution.

PHP & Oracle

Wednesday, July 21st, 2010

Long time no see.

Changed job and been working on fixing an app.

In my new job PHP and Oracle are the standards so I’m back to Oracle and I already had my first issues.

I have a small database with a couple of related tables.

I wanted to do an insert and get the id of the recently added row, searched for it on Google and there it was, I’ll need to use RETURNING…INTO.

It’s pretty simple actually so I coded it, the primary key is an integer that runs a trigger with a sequence, kind of a MySQL autoincrement field.

So this is how the code ended looking:

$query = “SELECT id, field1, field2 FROM table WHERE field1 IS NOT NULL RETURNING id into :id”;

$con = new connection()

$stmt = oci_parse($con,$query);


$binded = oci_bind_by_name($stmt,’:id’,$id);

$executed = oci_execute($stmt);


$row = oci_fetch_array($stmt,OCI_BOTH+OCI_RETURN_NULLS+OCI_RETURN_LOBS);



It worked fine for a couple of days, then id started working oddly. I analized the code and found out that id was returning a 3 digits id instead of 4 digits, so I’ll be getting 123 for ids 1230 – 1239 besides the previous original 123. That was messing my database integrity and making my code to fail.

Googled it and found nothing! What the hell was wrong with it?

Finally after a day I calmed down and started to remember the old times when I started to work with Oracle and suddenly I remembered!!!!

I was missing a parameter on an oci function. I added it and voila! It worked!

What was I missing? Simple, I was missing the maxLength parameter for the oci_bind_by_name function.

Finally it ended looking like this:

$binded = oci_bind_by_name($stmt,’:id’,$id,100);

Hope this helps others with the same issue.

Sanitizing and validating data

Thursday, March 25th, 2010

Still working on a project I found the typical login form.

This time the login credentials are the user’s email and a password. As always I found myself facing the task of validating an email. I had some php functions to do so but since they were almost a year old I decided to search for a more powerful already working solution.

To my surprise I found some very interesting info about email’s validation that I was unaware.

Some stuff that caught my eyes was that the email RFC actually allows the use of special characters on an email. The followin email is valid:


Noticed the quoted string? what about the escaped @?

In fact the following characters are valid on an email username: !#$%&’*+-/=?^_`{|}~@.[]

Wow! I bet that most of us didn’t knew that, and what’s worst most javascript or PHP validation functions won’t validate with the proper RFC rules. Deep trouble!

The good news are that PHP as of version 5 provides some functions that would help us deal with this problem.

Read the manual and search for filters, you’ll find a couple of very interesting and helpful functions to sanitize and validate data.

As for the email the following gets the job done:

$sanitized_email = filter_var($email,FILTER_SANITIZE_EMAIL);

$valid_email = filter_var($sanitized_email,FILTER_VALIDATE_EMAIL);


echo “Valid email!”;


It’s indeed a very helpful and concise way of validating data. The only bad thing is that it only works on PHP 5 or later. Nevertheless you’ll find some very powerful scripts on the links previously provided.

Hope this helps you as much as it helped me.

When random ain’t that random

Wednesday, March 24th, 2010

Been working on a small project that demanded the use of captcha.

Since it’s very small I decided to create my own captcha class. Nothing very complicated but still enough to avoid most of the spam robots. Anyway In order to create a nice captcha mi code draws some lines whose x,y coordinates where randomly generated through PHP’s rand function.

Later that day as I was finishing a widget I came up with this cool site. It’s all about randomness so I started reading.

To my surprise I found out a specific page that talked about pseudo random numbers generators (PRNG) and true random numbers generators (TRNG). PHP’s rand function is a PRNG and it’s not as cool as I thought.

For what the page explains the rand function should be avoided for true random number generatiosn when on a Windows server. Apparently it behaves oddly and follows some sort of pattern. They recommend the use of mt_rand instead which generates a more random number and also is faster than rand!!!!

Obviously I moved to mt_rand.

Please read the article, you’ll be surprised!!!