PHP: Setting the include_path for quick includes

Saturday, January 2nd, 2010

Tags:

PHP being the first language I loved and used for a long time, I now use it for all sorts of purposes. I also love and use Python but very often I end up coding in php because I am more habituated to this language than the beautiful python :) Again for some simple tasks, php is loads better than Python. Just imagine you need the md5 hash of a string. Will you import the hashlib first, then go through the md5() and hexdigest() methods ? Nope. I will simply fire off a php interactive shell and use the built in md5() function with an echo.

One of the major problems I was facing that all the external libs I use, I have to copy them into my current working directory or have to use some other techniques to import them into my current script.

To get a permanent work around this problem, I decided to use the include_path directive in php.ini :) I created a directory named “phplib” under my home directory and put all the libs in there.

Next, I opened up /etc/php5/conf.d/ with root access and added a new file named phplib.ini with the following contents:

include_path = "/home/masnun/phplib"

Now, whenever I need a library loaded, I just type :

<?php
include("mailer.php");
?>

That imports the mailer class, even on my interactive php shell :)

Interactive shell
 
php > include("mailer.php");
php > $m = new Mailer();
php > $m->setTo("maSnun <masnun@gmail.com>");
php > $m->setFrom("phpGeek <masnun@leevio.com>");
php > $m->setSubject("A bunch of files");
php > $m->setMessage("Hello buddy! Files attached!");
php > $m->sendMail();
php >

PS: Well, since the php interpreter always has your home directory as the CWD, you could just use include(“phplib/mailer.php”); in this case. But what about the php module running with apache? The include_path affects that one as well. It helps! But also it has a negative side. Make sure you upload the respective libs to the web server before you deploy your web application on the production box! :D

One Response to “PHP: Setting the include_path for quick includes”

  1. [...] Follow this link: PHP: Setting the include_path for quick includes « maSnun.com [...]

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">