Category Archives: PHP

How to update an extension with OpenCart installer

OpenCart installer is a great tool to install new extensions on OpenCart. However, if you have modifications in the extension it could become difficult to update it.


Unable to update an extension because ID already exists.


To update your extension using opencart installer follow this steps:

  1. Go to Extension > Modifications
  2. Remove the extension you want to update
  3. Go to Extension > Installer
  4. Update your new version of the extension
  5. Click on continue when the list of files show up
  6. Go to Extension > Modifications and hit refresh just to make sure

That’s all, I hope it can help you.

Run Code Igniter scripts as CronScripts

Yesterday I was planing a CronScript to run every night and do some processing tasks. I was coding over Code Igniter (CI) and had my application structured to fit the MVC model.

CronScripts are usually small scripts that do some maintenance to the database, send e-mails, clean cache files, generate reports and other periodic tasks or longer tasks.

After done my script algorithms, I starting thinking how can I get the information from the database. Many of the information that I need from the DB were already done in the models use with CI. However, this models are based in the CI environment and don’t run without it. Other catch is that CI was developed to work over an HTTP connection. So, we need to make a connection, use the TCP stack, check the security, creating access logs and most important for big jobs, deal with timeout issues. In the recent versions of CI, the only thing that really matters is one information from the $_SERVER array. By default the CI uses the PATH_INFO property, but you can configure CI to use REQUEST_ID, to select witch controller and method to run. This way we can easily emulate this information and run a CI script without a browser and an HTTP connection. I also set DOCUMENT_ROOT property emulating a browser and allowing file system manipulation without know the real_path.

In fact, is really easy to run the CI environment from a cronjob or command line. There are some steps you must follow:

  1. Copy the index.php file, that is the file that starts the CI environment, from the DOCUMENT_ROOT and give it a different name. I call it bot.php.
  2. Now you have to do some changes to the copied file in order to execute it from the command line/cronjob. You can start by removing the timeout expiration. This is a really “pain in the ass” when we want to process a lot of data. So, add this line to the top of the file:

    // remove execution timeout

  3. Then you must emulate the browser by setting the value that CI uses to select the contoller/method that it will run. You can do it statically but I did it using an argument, allowing this file to run several scripts. This way you create an entry point from many cronjobs. Just for sanity check, you may had some verifications to the argument passed. This is unnecessary to protect from direct connections to the bot.php file, because when you use CI you have to set mod_rewrite and if you configure it well you will have almost any URL pointing to index.php, but it can be useful for value format mistakes.

    // emulate the browser setting path_info passed by argument
    if (!$argc || $argc!=3 || !eregi(“^([^\\’\”;]*)$”,$argv[1]) || !eregi(“^([a-zA-Z0-9/\\_ -:.]*)$”,$argv[2])) exit;
    $_SERVER[“PATH_INFO”] = $argv[1];

    // emulate browser setting DOCUMENT_ROOT
    $_SERVER[“DOCUMENT_ROOT”] = $argv[2];

  4. In my case, I put the bot.php just besides the index.php. So, I don’t need to change the system_folder variable neither the application_folder one. However, if you put it in an inner folder you must adjust these paths.
  5. Now you are able to use the CI environment resources, the controllers, libraries and models that you want. At this time you may code your controllers and methods and run them as a cronscript from the cronjob/command line. Don’t forget to protect your cronscript controller from connection from a web browser. To do this you must only add the following code to your controller constructor.

    if($_SERVER[’SCRIPT_FILENAME’] != ‘bot.php’)

Now that you can run CI scripts from the command line or from a cronjob that you added to the crontab like following:

# execute cronjob every day at 2am
00 02 * * * /usr/local/bin/php5 $HOME/system/scripts/clean_cache.php

Thanks for user Thoer and Mhort from code igniter Wiki for the great job. Check the CI wiki post.

Clean file name in PHP with Regular Expressions

In Web developing there are some main features and many concerns that we all must be aware. The file uploading is one of the important and indispensible features that we certainly will use sooner or later.

I’m sure that many of you have had troubles when uploading files that have names with special chars, especially if we run our application in a Linux SO. In fact, using Linux we have to be aware of case sensitive names and special chars. In Windows, we usually don’t have this problem and we can name our files without many limitations. This problem has a higher importance in Latin countries like mine (Portugal), here is normal to name files like “Activação Telefónica.doc”.

So, I decided to code a simple function that cleans the file name and post it here to be sure that when I need it again I known were this little simple but useful function is. I use the PHP function preg_replace to replace special chars with standard ones. This is only an example and don’t clean all special chars. You should add more chars to the filter by simple adding more arrays to the cleaner one. See the function bellow:

$txt = "Activação Telefónica.jpg";

function cleanFileName( $str )
$cleaner = array();
$cleaner[] = array('expression'=>"/[àáäãâª]/",'replace'=>"a");
$cleaner[] = array('expression'=>"/[èéêë]/",'replace'=>"e");
$cleaner[] = array('expression'=>"/[ìíîï]/",'replace'=>"i");
$cleaner[] = array('expression'=>"/[òóõôö]/",'replace'=>"o");
$cleaner[] = array('expression'=>"/[ùúûü]/",'replace'=>"u");
$cleaner[] = array('expression'=>"/[ñ]/",'replace'=>"n");
$cleaner[] = array('expression'=>"/[ç]/",'replace'=>"c");

$str = strtolower($str);
$ext_point = strripos($str,”.”); // Changed to strripos to avoid issues with ‘.’ Thanks nico.
if ($ext_point===false) return false;
$ext = substr($str,$ext_point,strlen($str));
$str = substr($str,0,$ext_point);

foreach( $cleaner as $cv ) $str = preg_replace($cv[“expression”],$cv[“replace”],$str);

return preg_replace(“/[^a-z0-9-]/”,”_”,$str).$ext;

echo cleanFileName( $txt );

I hope that this function will be useful to you.

Advanced XPATH – Nested predicates

Extensible Markup Language ( XML ) is a standard way to store and share information , describing data and to focus on what data is.

Xpath is a language that makes possible find information in an XML document. This language has a huge importance in the W3C’s XSLT standard and is the base of Xquery and Xpointer. With Xpath we can navigate through elements and it’s attributes. The wide use of XML and the importance of Xpath turns it in a fundamental knowledge in the ITs world.

In this post I’ll answer a friend that has an advanced question. However, I will try to give some basic explanations for those who don’t want to study XML and Xpath from the beginning.

If you want to learn Xpath I recommend the Xpath tutorial from wschools.

Let’s start showing the data that I will use to answer. The information shown bellow is only for the example.

<?xml version=”1.0″ encoding=”UTF-8″?>
<available value=”yes” />

<available value=”yes” />

<available value=”no” />

The information shown below is a XML content that has some elements structured like a tree of nodes. In XML there are many nodes, like elements, attributes, text, and others.

Now is time to think in my friend’s question. He wants to get all identification information from the products that are available.

After see the XML content let’s check how to navigate through it and get the information that we want. Xpath has some expressions to select nodes lile:

Expression Description
Nodename Selects all child nodes of the named node
/ Selects from the root node
// Selects nodes from the current node that match the selection no matter where they are
. Selects the current node
.. Selects the parent of the current node
@ Selects attributes

With the expressions above we can build the path to the identification information that we want.


This expression can be built in other ways and returns all product identification nodes.

Now we use one predicate to select only the products that are available, this information is in an attribute of the available element. The basic use of predicates is apply a condition to an element or an element that is a sibling like the current one, e.g. an element is the same level of the current. The doubt is that we want the attribute of an element that isn’t in the direct navigation path and we will to use the elements name and check it’s attribute with another predicate.

We can put a predicate insider another one? Yes. We will use it on this example.

The predicate applies to an element or a parent element or a sibling element. Its position in the query affects the expression in the predicate. In this case, we must be aware that the element in the predicates expression shouldn’t be a full path because using one, we check if there is some available element, inclusive from another product, with its value attribute set to true.

Then, using tow predicates we have the following query: /store/product[available[@value=”true”]]/identification

Xpath have functions that can be use to solve some problems. In this one, the use of a predicate inside another solves it without have to use functions.

To check this example working I used PHP and its DOM extension to work with XML. A very easy way of navigate and find information in a XML document. Check the source code below:

echo “Starting checking available products <br />”;

$xml = new DOMDocument();

$xpath = new DOMXPath($xml);
$products = $xpath->query(‘/store/product[available[@value=”yes”]]/identification’);

for ($i = 0; $i < $products->length; $i++)
if ($products->item($i) && !$products->item($i)->hasChildNodes()) continue;

$childs = $products->item($i)->childNodes;

echo “<br />Full name: “.$childs->item(1)->nodeValue.”<br />”;
echo “Model: “.$childs->item(3)->nodeValue.”<br />”;

Send e-mail with inline image attachment

Since I start coding in PHP that one of the key feature were send and simple e-mail by a form. This can be done with many API’s that exist to work with the e-mail system. With the evolution of the Internet, sending e-mails with a design and not only with text has become to be normal and widely used. I’ve used many solutions like php mailer, xpert mailer, version 2 and 4, code igniter e-mail class, but still using the version 2 of xpert mailer, also known as XPM2.This older version, already with lack of support by its developers is simpler and easier to include in one project and do everything I need to send e-mail, from normal text based e-mail to rich content e-mail in html and attachments.

There are many ways for doing that by using html e-mails. This task isn’t as simple as it looks like, because html e-mail has some limitations and some rules that we can’t break if we want to see our e-mail well formed. One of the principal limitations is use a table based layout instead of a div one.

While using rich e-mails we face some difficulties and issues. The way we put images on the html e-mail is important. We’ve to choices to doing that.

  1. The first one is use full path to an image that is store in a web server accessible everywhere. This has some problems because we may not have space on a web server to put the files. Another problem is the limitation of the domain. If we want to change our domain or use our script in another one, we’ve to change all image and file path.
  2. Another way to put files on the e-mail, especially images, is putting them inline of the e-mail like an embed attachment. This solves the problems described but is much hard to use and to understand. Some API’s are simplifying the programmers work by offering a simpler to use Mime content inside an e-mail. The XPM2 have this feature and turns it simply to use when we do it right.

The code shown below is simple and sends an example e-mail with an inline image.

// XPM2 with attach inline example

// Create XPM instance
$mail = new smtp();

// Select delivery mode

// Set timeout

// Set e-mail priority

// Set from e-mail

// Set to e-mail

// Set body content has HTML dining is encoding
$mail->Html(‘<html><head><title>Test</title></head><body>Test<br /><img src=”image.jpg” alt=”Inline image” /></body></html>’,’ISO-8859-1′, ‘base64’);

// Attach file to the e-mail
$mail->AttachFile(‘image.jpg’, false, ‘autodetect’, ‘inline’ );

// Send e-mail and set the subject and it’s encoding
$sent = $mail->Send(‘Hello World!’,’ISO-8859-1′, ‘base64’);

// Check the status and see the result if error
echo $sent ? ‘Success’ : $mail->result;

The method attach file is used to add files to the e-mail, either as a normal attachment and an inline one. If we see the parameters we find a disposition that allows us to define the type of attachment. Using the second parameter we can set a name or use the full file name. Is this example, I attach an image as inline content and use it in html. It’s so easy and clean.

This API also allow you to choose the better way to send your e-mails using local, relay and client letting you use your servers e-mail layer or connecting to an SMTP server. Other feature is the possibility to connect to a throw POP3.

See the documentation about XPM2

I haven’t use the XPM4 because I had some header encoding issues and haven’t tried to fix the problem yet. Besides, I still use XPM2 because allows sending e-mail the way I like and is too small and easy to deploy and integrate with some frameworks, like Code Igniter.

WordPress blogs SEO

Today there are so many blogs that if you want to let people know that you have one, you must try to optimize it. Sometimes this optimization is right in front of our eyes and small changes can make a difference. In this post i’ll give some advice to improve your wordpress blogs index position in search engines. However, this are not proved actions to improve blog indexing, but are some SEO improvements discussed in SEO world.


Permalink is the permanent URL of your blog pages. This is the URL that visitors will see and that other web bloggers can use to refer a post of your blog. WordPress allow the configuration of the URL format. It offers different options, some of then very ugly and not well accepted by search engines. However, you can define your own format. This way you can either have a good and simple URL and a format that the spiders (search engines bots) like and extract your keywords from it.

The format that i choose to my blog and that i recommend is the “/%category%/%postname%”. The result is a simple and friendly URL that is parsed by the spiders. This bots get the keywords in the URL using them to define your pages value. If you’ve a URL with the date of the post or with a code what the meaning of the URL?

Visit WordPress permalink page

Post and category slug

To complete the benefit of permalinks, the WordPress allows you to choose the name that appear in the URL for each post or category. With post and category slugs you can define a much friendly URL. By default, the WordPress put your post title separated with ‘-‘. Some keywords are not necessary and can be removed. This way you can define your category and post parts of the URL format defined above.

Meta Tag

Another step to improve your blog value to the spiders, is defining some meta tags. Beside the definition of the page title, one of the most important information, we must define the description, the keywords, and other tags.

Bold fields

Some SEO professionals says that we must put strong tags on the keywords that we want to highlight either to the users an to the spiders.

WordPress Slug fields and permalinks

The search engines are the primary source of visitor to a web site. This engines have some crawlers that analyse our blog frequently and check our content. However, the content is not everything. One thing that matter to the spiders (name called to the engines that analyse our site) is the web site url’s. Like i said in WordPress blogs SEO, this engines don’t like query strings with many parameters and give more importance to first keywords in url.

WordPress have some fields that must be used to provide a crawler and user friendly urls. The called post slug and category slug can be filled with url friendly names that are well parsed by the crawlers. For example, if we create a post with the title like “WordPress Slug fields and permalinks”, wordpress will transform in a postname for url “wordpress-slug-fields-and-permalinks”, this if we have our permalink well optimized. With this slug fields we can set the best keywords reducing the url size and rising the crawlers position. In this post i set my post slug to “slug-permalink”, making the url with the keywords wanted with wordpress (category), slug and permalink.

Using this fields and with a optimized permalink strcture and a good category organization we can rise our index pontuation and, who knows, get more visitors.