Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Saturday, March 7, 2009

PHP - How to import contacts from all major email providers and social networks

What is OpenInviter ?

Open source OpenInviter (Open Inviter) is an free import contacts (addressbook) script from email providers like Yandex, Apropo, Walla, Lycos, Mail.ru, FastMail, IndiaTimes, Azet, Uk2, Evite, Care2, Mynet.com, Mail.com, Gawab, Doramail, Rediff, Live/Hotmail, Bigstring, Terra, Wp.pt, 5Fm, Nz11, Netaddress, Zapakmail, Interia, Yahoo!, Hushmail, Web.de, KataMail, Rambler, Popstarmail, Libero, Abv, Inbox.com, AOL, OperaMail, GMail, Sapo.pt, Clevergo, GMX.net, Mail.in or social portals like Eons, Famiva, Tagged, Plaxo, Flickr, Fdcareer, Meinvz, Cyworld, Twitter, Faces, Skyrock, Flingr, Plurk, Hi5, Mydogspace, Xanga, LinkedIn, Last.fm, Xing, Kincafe, Plazes, Livejournal, Xuqa, Bebo, Perfspot, Facebook, Lovento, Multiply, Motortopia, Konnects, Hyves, Brazencareerist, Mycatspace, Mevio, Orkut, Vimeo, Friendfeed, Friendster, Badoo, MySpace, Flixster. This contacts importer script is integrating with content management systems (aka CMS) like JamRoom, Boonex Dolphin, phpizabi, PhpBB, Joomla1.0, PHPMELODY, Social Engine, vBulletin, Wordpress, phpFoX, myBB, PunBB, Joomla, Drupal, SimpleMachines Forum (SMF). Open Inviter is written in PHP 5 (no database required but cURL or wget required) and running on any webserver (tested on Apache) offering advanced tell a friend features. OpenInviter is a free self hosted solution that does not use a third party gateway (or API) to import contacts.
Sounds cool! How much?

OpenInviter is totally free and open-source solution. You can download it, change it, write plugins for it. Everything for free. What are you waiting for? Grab your OpenInviter today! Go to the Download section now!
Features at a glance
  • Easy access to your visitors address book in all major email providers and social networks around the world.

  • Completely painless and easy way of integrating in your website. It takes virtually not more than 5 minutes to have your own OpenInviter up and running on your site.

  • Constant updates so that you can sit back and relax and always have access to the latest ways to get your visitor's address book.

  • WGET-ready! Yes, you read right! OpenInviter is the only contacts importer supporting both WGET and cURL as methods of handling

Sunday, October 12, 2008

Google Translation API: Translate on server side using PHP

Hi Guys,

As you know, there is google translate ajax api which can be used on client side translation using it's javascript interface. But how do we do translation on server side languages such as PHP, Java, ASP.NET or Rails. There is a task for us to translate multiple records on the database into 6 different languages as cron job. Similar problems may face you. So here is the solutions that you can use for your servers-side google translations.


function translateTexts($src_texts = array(), $src_lang, $dest_lang){
//setting language pair
$lang_pair = $src_lang.'|'.$dest_lang;

$src_texts_query = "";
foreach ($src_texts as $src_text){
$src_texts_query .= "&q=".urlencode($src_text);
}

$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0".$src_texts_query."&langpair=".urlencode($lang_pair);

// sendRequest
// note how referer is set manually

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "http://www.YOURWEBSITE.com");
$body = curl_exec($ch);
curl_close($ch);

// now, process the JSON string
$json = json_decode($body, true);

if ($json['responseStatus'] != 200){
return false;
}


$results = $json['responseData'];

$return_array = array();

foreach ($results as $result){
if ($result['responseStatus'] == 200){
$return_array[] = $result['responseData']['translatedText'];
} else {
$return_array[] = false;
}
}

//return translated text
return $return_array;
}


// translate multiple texts
print_r(translateText(array('hello world', 'italian'), 'en', 'it'));

?>

Monday, October 6, 2008

I am now Zend Certified Engineer :)

Hi all,

It is been long since i wrote blog last. I was busy dealing with company projects, and also do some preparation for zend PHP5 exam. I looked for testing center in our city, Ulaanbaatar/Mongolia, and luckily found active 1 pearson vue center in Science and Technology school. First try and pass :) The guys in the testing center were very happy that i was the first engineer passed Zend PHP5 Exam from Mongolia. Here i now going to share my experience with you, on how i prepared, what i read, where i went. etc...
  1. I worked for 7 years on web based project using different languages such as PHP/Java/.NET
  2. and them i managed web based project for last 2 years
  3. and then i visited Zend website to buy practice test package
  4. and i went to amazon to buy few books including PHP Objects, Patterns and Practice, High Performance MySQL (actually i didn't order them for Zend exam, but for daily use ;)
  5. and find nearest testing center and register for exam using Pearson vue website
  6. and finally take a good sleep before exam night, no practice test, not reading
  7. passed it. My certificate verification is here.
Actually i am not fan of certification, but the zend certification was the something that we really need, espacially for offshore web project outsourcing In the near futures, we plan our employees to be certified by Zend.

Thanks,
Bayar

Sunday, August 31, 2008

How to sort randomly with pagination on MySQL


Useful information that saved my whole day. The credit goes to Nyroblog

The problem is simple: we have to list randomly data from a MySQL table, by creating a paging.

Let's start with the basis: A normal paging. To do so, you use the LIMIT parameter in the MySQL query:

SELECT * FROM user LIMIT 20,10

Where we show the second page for the users with 10 elements by page.

You will probably order the result to be easier to use. For example:

SELECT * FROM user LIMIT 20,10 ORDER BY name ASC

At this point, everything was pretty easy and you probably already knew that.

Now we want to randomly order the result. Intuitively, you will do something like:

SELECT * FROM user LIMIT 20,10 ORDER BY RAND()

Which is not totally wrong. The problem with this solution will occur when changing the page, the order will be different -for sure, it's random. By changing the page you will probably see some recurrent data, and the visitor will never see all the result by reading all the pages. That's not expected.

The solution consists to generate a random number in PHP, stores it in a session variable, and finally use it in the MySQL query inside the RAND parenthesis. And it's finish. Therefore the random number used is every time the same for the visitor session, and the global order will stay the same in the differents pages.

The PHP code to generate and stored the random number:

$rand = $_SESSION['rand'];
if (empty($rand)) {
srand((float)microtime()*1000000);
$rand = "0.".rand();
$_SESSION['rand'] = $rand;
}

Of course, you have to open the session with session_start() at the top of your PHP script before every out or header send -or you can use ob_start().

Finally the MySQL query becomes:

SELECT * FROM user LIMIT 20,10 ORDER BY RAND($rand)

VoilĂ , you can make pagination with random order.

Sunday, July 13, 2008

Regular Expressions for username, date, ip address, color, postal code, and phone

Pasting here just to reuse them in the near future.

Here are eight examples of practical PHP regular expressions and techniques that I've used over the past few years using Perl Compatible Regular Expressions. This guide goes over the eight different validation techniques and describes briefly how they work. Usernames, telephone numbers, email addresses, and more. Here are eight examples of practical PHP regular expressions and techniques that I've used over the past few years using Perl Compatible Regular Expressions. This guide goes over the eight different validation techniques and describes briefly how they work. Usernames, telephone numbers, email addresses, and more.

Validating Usernames

Something often overlooked, but simple to do with a regular expression would be username validation. For example, we may want our usernames to be between 4 and 28 characters in length, alpha-numeric, and allow underscores.
$string = "userNaME4234432_";
if (preg_match('/^[a-z\d_]{4,28}$/i', $string)) {
echo "example 1 successful.";
}

Validating Telephone Numbers

A much more interesting example would be matching telephone numbers (US/Canada.) We'll be expecting the number to be in the following form: (###)###-####
$string = "(032)555-5555";
if (preg_match('/^(\(?[2-9]{1}[0-9]{2}\)?|[0-9]{3,3}[-. ]?)[ ][0-9]{3,3}[-. ]?[0-9]{4,4}$/', $string)) {
echo "example 2 successful.";
}

Thanks to Chris for pointing out that there are no US area codes below 200.

Again, whether the phone number is typed like (###) ###-####, or ###-###-#### it will validate successfully. There is also a little more leeway than specifically checking for enough numbers, because the groups of numbers can have or not have parenthesis, and be separated by a dash, period, or space.

Email Addresses

Another practical example would be an email address. This is fairly straightforward to do. There are three basic portions of an email address, the username, the @ symbol, and the domain name. The following example will check that the email address is in the valid form. We'll assume a more complicated form of email address, to make sure that it works well with even longer email addresses.
$string = "first.last@domain.co.uk";
if (preg_match(
'/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',
$string)) {
echo "example 3 successful.";
}

Postal Codes

Validating Postal codes (Zip codes?,) is another practical example, but is a good example to show how ? works in regular expressions.

$string = "55324-4324";
if (preg_match('/^[0-9]{5,5}([- ]?[0-9]{4,4})?$/', $string)) {
echo "example 4 successful.";
}

What the ? does in this example is saying that the extra 4 digits at the end can either not exist, or exist- but only once. That way, whether or not they type them in, it will still validate correctly.

IP Addresses

Without pinging or making sure it's actually real, we can make sure that it's in the right form. We'll be expecting a normally formed IP address, such as 255.255.255.0.
$string = "255.255.255.0";
if (preg_match(
'^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$',
$string)) {
echo "example 5 successful.";
}

Hexadecimal Colors

Moving right along with numbers, we could check for Hexadecimal color codes, in short hand or long hand format (#333, 333, #333333 or 333333) with an optional # symbol. This could be useful in a lot of different ways... maybe previewing CSS files? Grabbing colors off pages? The options are endless.
$string = "#666666";
if (preg_match('/^#(?:(?:[a-f\d]{3}){1,2})$/i', $string)) {
echo "example 6 successful.";
}

Multi-line Comments

- A simple way to find or remove PHP/CSS/Other languages multi-line comments could be useful as well.
$string = "/* commmmment */";
if (preg_match('/^[(/*)+.+(*/)]$/', $string)) {
echo "example 7 successful.";
}

Dates

- And my last simple, yet practical example would be dates, in my favorite MM/DD/YYYY format.
$string = "10/15/2007";
if (preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', $string)) {
echo "example 8 successful.";
}



The source is here.

Monday, February 25, 2008

Zend vs Symfony framework

I wrote about my decision to go on with Zend framework. Few days ago, i already posted an article, review, resources and tutorials about ZF here. Then i went through that articles and tutorials, spent about two weeks just for reading and learning. Let me say that related resources are not enough on Zend framework. It was very difficult for me to find howtos on any topic related to ZF.

Instead i visited Symfony website, and found there everything needed to go forward. There is a great online free book of Symfony, explaining everything in detail and tutorial directory, trac, wiki, and plugins repository. I warmed up very fast and changed my mind. Now i am far from that days, and very happy with Symfony Framework. And i know that i can integrate Zend framework components into my Symfony application when it is needed.

Symfony is a real MVC framework that makes web application development easier and faster, while Zend framework is not a framework, just container for useful components or libraries. Zend framework doesn't have command line tools, crud generator, plugins etc... which means you have to stilllll repeat your codes, and spend time on useless boring tasks like CRUD.

Friday, November 30, 2007

Easy setup and configure WampServer - MySQL5, PHP5 + PECL, Apache2, PhpMyAdmin on Windows XP

WampServer is a Windows web development environment. It allows you to create web applications with Apache, PHP and the MySQL database. It also comes with PHPMyAdmin and SQLiteManager to easily manage your databases.

WampServer installs automatically (installer), and its usage is very intuitive. You will be able to tune your server without even touching the setting files.

WampServer is the only packaged solution that will allow you to reproduce your production server. Once WampServer is installed, you have the possibility to add as many Apache, MySQL and PHP releases as you want.

WampServer also has a trayicon to manage your server and its settings.

MySQL Singleton Class with PHP5

The singleton can be use in lot of differents cases. In this exemple we will make a MySQL connection Singleton class. This will help us to always use the same connection.

class MysqlDB{
static private $instance_MysqlDB = null;

private
$objMysqli;

/**
* Instantiate the object
**/

private function __construct(){
$this->objMysqli = new mysqli("localhost", "root", "", "mysql");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
/**
* Perform a query
*
* @param string $sql
*/

public function select($sql){
$this->objMysqli->query($sql);
$this->var_dumping();
}
/**
* Var dump the current object
*/

public function var_dumping(){
var_dump($this);
}

/**
* Get the current instance for the object
*
* @return object
*/
static public function getInstance(){
if(self::$instance_MysqlDB == null){
self::$instance_MysqlDB = new self;
}
return self::$instance_MysqlDB;
}
}

---------------------------------------
To use the singleton we will never use the constructor method. We will call the getInstance method.
Here is an example :
include_once("MysqlDb.php");
MysqlDB::getInstance()->select("SELECT * FROM `help_category` LIMIT 5");

Zend Framework Overview

Fav.or.it creator Nick has explained why he chooses Zend framework among the other PHP5 frameworks.

Is it a framework?

The first thing that I always have to explain when talking about the Zend Framework is that to me it is not a ‘framework’ or not in the same way others are frameworks. This causes a lot of confusion and misunderstand of what the Zend Framework has to offer. To me most frameworks require you to conform to how they ‘think’ (something Ruby/Rails suffers from) and breaking out from their thinking requires actual alteration of the framework.

To me the Zend Framework is actually a Library, something that I can pick and choose from and although a good percentage of each module does also interact with other modules this behavior can in most cases be overridden or sub-classed and behaviour changed.

The MVC

Another difference is that a lot of Frameworks revolve around their own implementation of the MVC (Model View Controller) and again if you want to break out from how they work then you may as well not use any of the framework. The Zend Framework does of course include modules that assist in setting up a MVC and it has many great tutorials on ‘the standard’ way of doings things. But once you begin to understand how everything fits together it has incredible power for those who want to stretch its legs.

Not for beginners?

I will at this point make lots of enemies by saying that the Framework is a professional product and is not really for the beginner. Although it has made strides towards simplifying some aspects of the MVC (and other modules) it is still certainly more complex than others and if you have no inclination to do anything ‘out of the ordinary’ then my advice is to use something else.

The Modules

The Zend Framework as I mentioned earlier is made up of a range of modules (full list here) most of which fav.or.it uses at one level or another. I wont go into detail for all of them as I would just be repeating what is said in the manual.

Zend_Acl - Access Control List

I have previous written at length about the ACL and done a podcast on the subject. It is a little hard to get your head around to start off with (the reason I tried to explain it in the PodCast) but it is extremely powerful and versatile.

Zend_Auth - Authentication

Authentication made simple. Although again we have sub-classed and extended the functionality it again got us up and running within hours and then let us think about the more complex tasks by filling in the basics.

Zend_Cache - Caching

The cache is fundamental for anyone who is serious about long term scalability. It allows caching of pages/parts of pages or just raw data. It has two killer features for me 1) Range of backend solutions (File,SQL, Memcache, ZendPlatform) 2) Tagging. The back end options give me great flexibility to choose the right kind of caching for the situation plus it is easy to extend to add your own. The tagging is a delightful way to group together different pieces of information so that they can be cleaned up / listed by tag or tags.

We created a whole new interface so we could view the current state of the various caches we have and allows us to clear out entries by key (every item must have a unique key) or by tag.

For anyone thinking about investing in Zend Platform it also means that when that time comes that any caching can be handed over to the platform.

Zend_Controller / Zend_View

I am a massive fan of well structured MVC’s and the Zend Framework gives me the flexibility to do everything we could possibly want. As default creating mapping between URL & method/controller gives you quick setup. You can then easily extend the routing (how a URL gets translated).

We have a whole set of custom routes, we have a fully sub-classed dispatcher and make use of the helpers when we can.

The Zend_View is quite simple as a starting point but is easily extended and can achieve a range of design patterns. We have various extensions to give us partials and layouts. The partials allow us easy blocks that have local variables assigned to render pages. The layout lets us arrange numbers of blocks/sections.

Zend_Db - Database

I cannot recommend Zend_Db enough! It is at once very simple to get going but fantastically full of depth. I had never considered myself much of a database expert and Zend_Db allowed me to think about the programming problem rather than SQL. The ability to build select statements programmatically with a consistent interface is a dream come true.

Zend_Feed

fav.or.it is all about feed aggregation and Zend_Feed gave us a fantastic head start on consuming and producing feeds. We have sub-classed this heavily as we have a lot of special requirements but it did save us lots of time covering the basics.

Zend_Filter + Zend_Filter_Input + Zend_Validate

I put these all in together as they all have similar tasks. Although at first I found constantly building up filter/validation chains long winded (but very readable) I soon starting building helper functions that let me build the chains with shorter (not sure if clearer) syntax which could then be easily repeated.

e.g.

const FILTER_EXAMPLE = 'Alnum:Alpha:StringTrim';
$string = Filter_Helper::filter(FILTER_EXAMPLE,$string);

The same can be applied for building up Validators. At some point I will release the full syntax and the code.

The Rest

  • Zend_Gdata - Easy to use and very powerful, we use it to access blogger services
  • Zend_XmlRpc - This is still in its infancy but it still does the job for most tasks
  • Zend_Http - Want to perform some custom request? this handles nearly everything, we use it all over the place for a range of tasks and has proved to be very robust
  • Zend_Date - Dates come in lots of formats and Zend_Date means you treat them all the same, a few question marks over future performance when over using this
  • Zend_Log - Does what it says on the tin, quite lightweight but easily extended to give a few extra features that makes it worthwhile
  • Zend_Session - I try and keep clear of over using session data but having the ability to namespace your sessions makes this very useful

Conclusion

The Zend Framework does a fantastic job of giving you a professional quality set of tools to get going with quickly and then when required it doesn’t stop you customizing it when you need to. As you grow more confident and start to understand the underlying reasoning behind the framework you start to work with it more and more and it encourages you to achieve the same kind of extensibility that it has achieved.

Thursday, November 29, 2007

Beginning Symfony tutorial - Moving from plain PHP to Framework based development

Lately, i have been busy with recent two projects, which are being developed using Symfony framework. Let me say that it is fantastic. I wonder why i didn't use it before. Symfony is PHP5 framework inspired by Rails framework, exactly suitable for Web 2.0 application development. I planned to write tutorial about how to start Symfony, but realized that there are plenty of good tutorials out there. One of them is on sitepoint. Here is the tutorial, you can follow the links to read the rest of the Symfony tutorial

With the release of symfony 1.0, it's time for those who haven't tried it yet to see what's inside this beautiful framework. Stable, fully documented, and released under the open-source MIT license, symfony is used by hundreds of web sites, including some very large ones (Yahoo! Bookmarks, with its 20 million-strong user base, is built with symfony). If you haven't taken the time to look at the introductory screencasts on the symfony project website, this simple tutorial will lead you through the basics.

The best way to learn and understand symfony is to use it, so this article will lead you through the creation of a photo album application with this framework. You already know the basic features such an application should offer: the ability to upload photos, to describe and tag them, and the ability for visitors to browse and comment on your photos.

Symfony is a Model-View-Controller (MVC) framework written in PHP that's aimed at building web applications. If you're already familiar with the MVC paradigm, you won't be surprised by the way symfony organizes scripts. If you aren't familiar with MVC, you just need to understand that separating the code into three parts -- the logic code (called the Model), the presentation code (the View), and the request handling code (the Controller) -- is a good way to ensure the maintainability and reusability of code.

Not only is Symfony an MVC implementation in PHP, it also integrates a lot of objects that facilitate the development of web applications -- and integrates them all with a coherent syntax. Smart URLs, code generation, easy templating, internationalization, caching, automated form validation, and Ajax, are among the most appreciated symfony features. Developing an application with symfony is slightly different than building it with any other framework, or without any framework at all. It's faster, more productive, and just plain fun. But enough talk, let's see some code.

Read more at Sitepoint>>>



Checkout;
Now php scripts are developed that are more compatible to generate highest pay per click revenues. These are a nice choice for the webmaster that is a beginner, since php based web design is not easier to develop and master. A beginner can just think of getting cheap domain names and high speed broadband services but has little access to search engine optimization tricks.

Wednesday, September 19, 2007

Zend Framework reviews, articles, tutorials, blogs and resources

Lately, you must be hearing about Zend Framework very much. Maybe you looked at quickly and gave it a try. I did and loved it. I absolutely plan to develop my next project using ZF. It is already got mature enough since now the stable version available for download is 1.0.1 which starts with the real number ONE ;) ZF has plenty of developers and contributors so it is very active projects among other php frameworks. Roadmap also looks nice. So what are you waiting for? Start digging into the following ZF reviews, tutorials, blogs, forums and sites.

Introduction & Reviews
Tutorials


Sites
Blogs
Forums
Resources
Update on 06/02/2008

Monday, September 17, 2007

Website screenshot capture with ASP.NET and PHP

Capturing the thumbnail of a website is pretty useful when you are creating a web application like web 2.0 directory, site review, website preview, etc... So how do you implement it in your language? I did it in my asp.net application which was was very easy. And i searched for the way in PHP. Although, PHP doesn't support natively, there are tricks that you can use to capture screenshots of websites. Here is the code snippets;

ASP.NET

Never forget that ASP.NET and Windows Forms applications are all about .NET Framework. So theoretically we can do all the things in an ASP.NET application like we do in Windows Forms. The idea behind our solution will be to initialize a hidden WebBrowser component and load our web site inside it to be able to get screenshot.

Original article can be found on Codeproject.


Imports System
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Windows.Forms
Imports System.Diagnostics

Namespace GetSiteThumbnail

Public Class GetImage
Private S_Height As Integer
Private S_Width As Integer
Private F_Height As Integer
Private F_Width As Integer
Private MyURL As String

Property ScreenHeight() As Integer
Get
Return S_Height
End Get
Set(ByVal value As Integer)
S_Height = value
End Set
End Property

Property ScreenWidth() As Integer
Get
Return S_Width
End Get
Set(ByVal value As Integer)
S_Width = value
End Set
End Property

Property ImageHeight() As Integer
Get
Return F_Height
End Get
Set(ByVal value As Integer)
F_Height = value
End Set
End Property

Property ImageWidth() As Integer
Get
Return F_Width
End Get
Set(ByVal value As Integer)
F_Width = value
End Set
End Property

Property WebSite() As String
Get
Return MyURL
End Get
Set(ByVal value As String)
MyURL = value
End Set
End Property

Sub New(ByVal WebSite As String, ByVal ScreenWidth As Integer, &_
ByVal ScreenHeight As Integer, ByVal ImageWidth As Integer,&_
ByVal ImageHeight As Integer)
Me.WebSite = WebSite
Me.ScreenWidth = ScreenWidth
Me.ScreenHeight = ScreenHeight
Me.ImageHeight = ImageHeight
Me.ImageWidth = ImageWidth
End Sub

Function GetBitmap() As Bitmap
Dim Shot As New WebPageBitmap(Me.WebSite, Me.ScreenWidth, &_
Me.ScreenHeight)
Shot.GetIt()
Dim Pic As Bitmap = Shot.DrawBitmap(Me.ImageHeight, &_
Me.ImageWidth)
Return Pic
End Function
End Class

Class WebPageBitmap
Dim MyBrowser As WebBrowser
Dim URL As String
Dim Height As Integer
Dim Width As Integer

Sub New(ByVal url As String, ByVal width As Integer, &_
ByVal height As Integer)
Me.Height = height
Me.Width = width
Me.URL = url
MyBrowser = New WebBrowser
MyBrowser.ScrollBarsEnabled = False
MyBrowser.Size = New Size(Me.Width, Me.Height)
End Sub

Sub GetIt()
MyBrowser.Navigate(Me.URL)
While MyBrowser.ReadyState <> WebBrowserReadyState.Complete
Application.DoEvents()
End While
End Sub

Function DrawBitmap(ByVal theight As Integer, &_
ByVal twidth As Integer) As Bitmap
Dim myBitmap As New Bitmap(Width, Height)
Dim DrawRect As New Rectangle(0, 0, Width, Height)
MyBrowser.DrawToBitmap(myBitmap, DrawRect)
Dim imgOutput As System.Drawing.Image = myBitmap
Dim oThumbNail As System.Drawing.Image = New Bitmap(twidth, &_
theight, imgOutput.PixelFormat)
Dim g As Graphics = Graphics.FromImage(oThumbNail)
g.CompositingQuality = Drawing2D.CompositingQuality.HighSpeed
g.SmoothingMode = Drawing2D.SmoothingMode.HighSpeed
g.InterpolationMode = Drawing2D.InterpolationMode. &_
HighQualityBilinear
Dim oRectangle As Rectangle
oRectangle = New Rectangle(0, 0, twidth, theight)
g.DrawImage(imgOutput, oRectangle)
Try
Return oThumbNail
Catch ex As Exception
Finally
imgOutput.Dispose()
imgOutput = Nothing
MyBrowser.Dispose()
MyBrowser = Nothing
End Try
End Function
End Class

End Namespace

PHP

Original article can be found here on The Pimp. Alternatively you can use third party thumbnail generators API, but your app will be dependent which you will not want.


$im = imagegrabscreen();
imagepng($im, "myscreenshot.png");

$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$im = imagegrabwindow($handle);
$browser->Quit();
imagepng($im, "iesnap.png");
$im = imagegrabscreen();

$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$browser->Navigate("http://blog.thepimp.net");

/* Still working? */
while ($browser->Busy) {
com_message_pump(4000);
}
$im = imagegrabwindow($handle, 0);
$browser->Quit();
imagepng($im, "iesnap.png");

$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;

$browser->Visible = true;
$browser->FullScreen = true;
$browser->Navigate("http://blog.thepimp.net");

/* Is it completely loaded? (be aware of frames!)*/
while ($browser->Busy) {
com_message_pump(4000);
}
$im = imagegrabwindow($handle, 0);
$browser->Quit();
imagepng($im, "iesnap.png");
?>

It should work with any kind of window as long as you give the correct handle (usually $obj->HWND).

Tuesday, August 28, 2007

60+ template engines for JAVA, PHP and .NET

Template engines are designed to allow the separation of business logic from the presentation layer, which means allowing MVC architecture to the developers. With the aid of template engines, we are able to develop websites with different looks but the same logic or the core code. Template engines are lately known as not good ideas because recent platforms already have embedded template engines to separate views from logic, generate code etc... As you see there are very few template engines in .NET and Java comparing to the PHP. But they are still pretty useful tools for developers.

Java
  • The Apache Velocity Engine - a free open-source templating engine. Velocity permits you to use a simple yet powerful template language to reference objects defined in Java code. It is written in 100% pure Java and can be easily embedded into your own applications
  • StringTemplate - a java template engine (with ports for C# and Python) for generating source code, web pages, emails, or any other formatted text output. StringTemplate is particularly good at multi-targeted code generators, multiple site skins, and internationalization/localization.
  • FreeMarker is a "template engine"; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates. It's a Java package, a class library for Java programmers. It's not an application for end-users in itself, but something that programmers can embed into their products. Integrates with servlets, XML, Python and more
  • JBYTE - JavaBY Template Engine is a general template engine used for generating any type of text document from a template. JavaBY Template Engine is used mostly for generating HTML from servlets but it can also be used for generating XML, RTF, WML, e-mail text, source code and configuration files.
  • Jamon - a text template engine for Java, useful for generating dynamic HTML, XML, or any text-based content. Jamon clearly is aimed at the View (or presentation) layer. It has a rich feature set to support encapsulation, parameterization, functional decomposition, and reuse of presentation logic.
  • Tea is a simple yet powerful template language. Tea is most commonly used for creating dynamic web pages in the TeaServlet. Tea is a strongly typed, compiled programming language, designed to work within a Java-based hosting environment. Tea is designed to enforce a separation between data acquistion and presentation, without sacrificing basic programming constructs.
  • JDynamiTe is a simple yet powerful tool used to create dynamic documents from "template" documents. It is based on the same concept as those of "FastTemplate", which is a very popular PHP extension used in many Web sites to create dynamic HTML pages. Note: JDynamiTe is not a Java port of FastTemplate.
  • BTE (Better Templates for Everyone) - A template system designed to make the creation of web sites easier.
  • Jxp (Java scripted page) is a script-processor that process JSP-like files. It contains a parser to parse the script file into an abstract syntax tree and a tree processor (JxpProcessor) that will process the syntax tree to execute the code using reflection API to produce output.
  • SiteMesh - a web-page layout and decoration framework and web- application integration framework to aid in creating large sites consisting of many pages for which a consistent look/feel, navigation and layout scheme is required.
  • LSP is an advanced web template language based on XML technology. LSP provides powerful and easy to use presentation logic, but keeps business logic and technical details out of templates. LSP is compiled into Java bytecode for efficient execution.
  • Dynamator - a simple but powerful tool that transforms standard HTML and XML files into server pages or programs. Dynamator works with any page generation technology, including JSP, XSL, PHP, ASP, Velocity, Cold Fusion, and Java. Dynamator is compatible with any application architecture, and has no performance impact.
  • Jtpl - a template engine for Java Servlet which allows you to store your HTML code apart from your Java code.
  • Bluprints - a JSP templating framework that provides a simple and powerful alternative to Tiles and other frameworks. JDK 1.5 is required to run Bluprints.
  • WebMacro - more effective for rendering web pages than JavaServerPages, PHP, and ASP. We say this because, since 1999, programmers around the world have used both and universally endorsed WebMacro.
  • Canvas - a template generator based on the Groovy language. It uses the familiar Velocity Java API to bind variables and allows you to use the full expressivity of Groovy inside your templates.
  • IKAT - the purpose of IKAT is to establish a complete separation between presentation and business logic.
.NET
  • Asp.NET HTML Template Engine - create HTML templates for your ASP.NET application. Multiple template regions can be defined; you are no longer restricted by the usual header / footer templates.
  • NVelocity - a .Net-based template engine. It permits anyone to use the simple yet powerful template language to reference objects defined in .Net code.
  • Netro - a .Net-based template engine. It allows the use of simple yet powerful template language to reference objects defined in .Net code.
  • Evolve MasterPages - a powerful template engine which allows you to merge the contents of your ASP.NET web forms with a Master Page (template). It's very easy to use and provides full designer support. It's extremely easy to use and provides full designer support. The engine provides a new approach regarding the separation of ASP.net templates and webforms and makes it extremely easy to get your templates working. It prevents you from scattering additional HTML all over your web application and enforces a clean separation of design and development.
  • StringTemplate.NET - an idiomatic C# implementation of the Java StringTemplate Library. It runs on C#/CLI platforms such as Microsoft .NET, Novell Mono and dotGNU. StringTemplate.NET is a template engine for generating formatted text output. Examples of such output includes source code, web pages and emails. It differs from most other template engines by [more] strictly enforcing Model-View separation.
PHP
  • Smarty - a template engine that compiles the templates into PHP scripts, then executes those scripts. Very fast, very flexible.
  • web.template - new template system, works only with PHP5, uses XML-like look language, and you can call for templates method in your classes.
  • XTemplate - a cool templating engine for PHP, allows you to store your HTML code separately from your PHP code (as opposed to compiling your template into PHP as per Smarty etc.). It has many useful features such as nested blocks and various kinds of variable interpolation, and yet the code is very short and very optimized.
  • Open Power Template - a template engine written in PHP, and probably the one, which natively supports PHP 5. While developing it we chose two main goals for it: to be fast, and to be flexible. OPT uses a very effective template parsing algorithm, which compiles the templates into the PHP code.
  • FryPHP - very young, fast and easy to learn templating engine/system for PHP5, written in object oriented manner using test driven development (TDD), allows local variables for each template, you also can set global variables.
  • Template Class - very easy to use yet powerful and quick template engine. It can handle simple variable replacement and table building using two dimensional arrays and/or MySQL result sets. Performance is excellent. Has support for multiple template files. Documentation is included in the zip file.
  • Template Lite - written under PHP 5 and is currently being written under PHP 5.2.1 with E_STRICT enabled. Template Lite works without error under all versions of PHP 5 from 5.1.3 and higher. Before PHP 5.1.3 VAR would give a warning notice under E_STRICT. Template Lite works under PHP 5 without any errors but does not use any PHP 5 specific attributes.
  • PHPTAL - a XML/XHTML template library for PHP. Some PHPTAL advantages and features; enforce the separation between logic and presentation, no more htmlentities, quite clean and readable templates, ability to insert sample text inside template to preview template result without PHP backend, integrates quite well with WYSIWYG HTML editors, data abstraction using xpath like system, cool html macro system, integrated internationalization system, ability to replace xpath system with php expressions, nearly no speed loss, and template source filter interface
  • Savant - a powerful but lightweight object-oriented template system for PHP. Unlike other template systems, Savant by default does not compile your templates into PHP; instead, it uses PHP itself as its template language so you don't need to learn a new markup system.
  • YATS - seeks to preserve FastTemplate features while improving on usability and speed. It is not a direct port of FastTemplate, as it adds/removes some features, changes the syntax, and simplifies a few things, such as template definition.
  • Simple Turtle PHP Template - a simple, small, fast and quick to use function that helps separate between the logic and presentation layers in PHP programs. It is simple because all it does is string replacements, for both single words and in blocks.
  • Templeet is an open-source project initiated by Pascal Courtois and Fabien Penso. It allows you to create photo galeries, news systems, personal sites, blogs, etc. Using Templeet, you can generate HTML, CSS, SVG pictures, SMIL, and any kind of text files.
  • Enzyme - simply put, is an engine for storing structured data for structured searching.
  • Bleetz - a revolutionary templates parser based on XML generating PHP. It translates Bleetz control tags into universal php code. It is designed to be fully integrated with Macromedia Dreamweaver.
  • SSTP (Server-Side Template Parser) - powerful tool for formatting pages based on templates. It will work with virtually any HTML/XHTML page, and has support for advanced features such as syndication of content and intelligent link correction.
  • VOOT (Vanilla Object Oriented Templates) - a simple ('vanilla') PHP class for creating web pages with templates. It supports user-defined HTTP headers, and it is capable of processing PHP contained in rendered templates.
  • ecTemplate - quit making dirty HTML pages. Separate your PHP code from your HTML. Finally that graphic designer will talk to you again ;)
  • phemplate - simple and fast templating engine for php. it provides a way of substituting variables into text templates and do some dynamic block functionality including loops.
  • Yapter is a PHP template engine. Other template engines all lacked some kind of functionality for me to just like them 100%.
  • ETS - easy template system - a template system written with PHP that enables you to transform a set of data to any type of document.
  • PatTemplate is a template system that gives us the power and flexibility to add templates to our PHP driven sites.
  • Qtpl - intended for use in CGI scripts. The library will be released in 6 versions: Plain Perl, Plain PHP, C version, PHP/C module, Perl/XS version, C++ version. All of them will support uniform syntax.
  • SledgeHammer - a template engine for PHP. It provides separation of business-logic and presentation in web-based applications.
  • PHPService is a powerful template engine based on an easy-extensible XML-Metalanguage.
  • Virtual Template - class for PHP4 & PHP5 (french)
  • SimpleT - An HTML Compiler
  • AvanTemplate - is a template engine for PHP. It is multi-byte safe and consumes little computing resource. It supports variable replacement, block that can be set to hidden or shown, loop, multple-depth loop, and include statement in template file.
  • TemplatePower - offers you the ability to separate your PHP code and your (HTML) layoutfile. It's simular to the popular template class FastTemplate, but than a lot faster (about 6x faster).
  • htmltmpl: templating engine - A templating engine for Python and PHP. Provides web application developers, who need to separate the program code and the design (HTML code) of their web application projects, with a templating tool that can easily be used by cooperating webdesigners with no programming skills.
  • MiniTemplator - compact template engine for HTML files. It features a simple syntax for template variables and blocks. Blocks can be nested.
  • Layout Solution - simplifies website development and maintenance. It holds commonly used variables and page elements, allowing you to focus on designing your pages rather than worrying about correctly duplicating common layouts over and over.
  • TinyButStrong - a library that enables you to create HTML pages dynamically. It enables you to easily display information from your database, but also to seriously harmonize and simplify your PHP programming. TinyButStrong is oriented to HTML but not specialized to Html. This means it can work as well with Text files, XML, RSS, RTF, WML, Excel (xml), ...
  • WACT - a template engine that separates code from design.
  • bTemplate - small and fast template class that allows you to separate your PHP logic from your HTML presentation code.offers you the ability to separate your PHP code and your (HTML) layoutfile. It's simular to the popular template class FastTemplate, but than a lot faster (about 6x faster).
  • QuickTemplate - a PHP extension for mananging templates and performing multi level variable and block interpolation.
  • VarPage - very simple PHP class for building websites based on Template files
  • FastTemplate - PHP extension for mamanging templates and performing variable interpolation, robust and flexible, and allows you to build very complex HTML documents/interfaces. It is also completely written in PHP and (should) work on Unix or NT.
  • Vemplator is PHP template engine that strives to be light-weight yet featured, and does quite well in only 200 lines of code. The template syntax is concise, and the code is written to be extensible. Though it may be somewhat strict (doesn't allow function calls from the template, among other things) it's very usable. The strictness is intended to constrain the template logic to that which relates to presentation.
See Also;

Sunday, July 22, 2007

J2EE vs ASP.NET vs PHP

In this article, I wanted to compare the web application development platforms which I have been using for recent years. My comparison has no aim to make one platform better than others, or vice versa. These are all my own thoughts and what I have experienced during the development of web applications using the three platforms. It is open to you to express your opinions and stands as a comment.
Scores mean
10 – Best.
9 – Very Good.
8 – Good.


Syntax

I love Java syntax, a real object oriented syntax. PHP have some odd characters like “->, ::” and function calls are made directly like “substr, strreplace” which makes me feel like using procedural language. For ASP.NET, I have been using VB.NET.

J2EE: 10, ASP.NET: 9, PHP: 8

Easy to Learn
Believe or not, I learned PHP in two weeks. One day I decided to learn PHP and visited PHP official website. The website had one question explaining what is PHP and how and where to start. Manuals, documentation and samples were all there and ready to download. To prepare development environment was straight easy. ASP.NET was also easy to learn but bit difficult than PHP. J2EE was the most difficult and long process for me.

J2EE: 8, ASP.NET: 9, PHP: 10

Development Speed
For simple, small-size and CRUD applications, ASP.NET is the fastest one because of the pre-implemented controls, components and APIs. In PHP, if you use the right framework, it is also fast process.

J2EE: 8, ASP.NET: 10, PHP: 9

Platform
Although PHP works best on LAMP (Linux, Apache, MySQL and PHP) environment, you can deploy PHP web applications on other platforms such as Windows, Solaris etc…
ASP.NET have only one choice; Windows. There is a Mono tool for development and deployment of ASP.NET on Linux, but not ready for enterprise use. J2EE runs best everywhere.

J2EE: 10, ASP.NET: 8, PHP: 9

Database
Simplest theory is MySQL for PHP, Oracle for J2EE and MSSQL for ASP.NET. There are many other good databases out there. You can use most of them with all three languages by adding or installing appropriate drivers.

J2EE: 10 , ASP.NET: 10, PHP: 10

IDE – Integrated Development Environments
ASP.NET has only one choice, Visual Studio which is very cool IDE but costs puff ;) PHP have commercial and open source IDE-s. Most known PHP IDEs are Zend Studio and PHP Coder as far as I know. J2EE has nice open source choices as well as commercial. Eclipse is the most used and best IDE I have ever used. With its plug-in structure, you can use Eclipse almost for all purposes, even for PHP development. Beside Eclipse, there are some more good IDE-s like IntelliJ, Netbeans, Sun Studio etc…

J2EE: 10 , ASP.NET: 10, PHP: 9

OOP – Object Oriented Support
J2EE and ASP.NET win here. PHP have OOP support in its latest versions.

J2EE: 10, ASP.NET: 10, PHP: 9

AOP – Aspect Oriented Support
J2EE have some AOP frameworks one of which I have used. I don’t know whether ASP.NET and PHP supports AOP or not.

J2EE: 10 , ASP.NET: 9, PHP: 9

Security
J2EE is the most secure one I guess. Once, I had my PHP web application hacked by someone. So PHP is secure only when you code secure ;) For ASP.NET, people have some doubts because of previous versions of windows security holes and hells. I didn’t experience any security problem of ASP.NET till now.

J2EE: 10, ASP.NET: 9, PHP: 9

Performance
I liked PHP Performance. For web applications I have ever developed, the most satisfied application was written in PHP. J2EE was little bit heavier to start, and consumes huge system resources. I have not tested my ASP.NET applications against huge loads in real life. Till now, I didn’t have any complaint about performance of my ASP.NET applications.
J2EE: 9 , ASP.NET: 9, PHP: 10

Web Server
ASP.NET has only one choice; IIS. For PHP and J2EE, you have plenty of choices; commercial and open source. Apache is the most popular one for PHP. Sun AS, JBoss AS, Oracle AS, Weblogic, Tomcat, and some more are for J2EE. Most of the J2EE servers cost high.

J2EE: 10, ASP.NET: 9, PHP: 10

Libraries and Frameworks
All of three languages have third party libraries and frameworks. In PHP and J2EE, most of the frameworks and libraries are open source or free. In ASP.NET, most of the libraries and components out there are commercial.

J2EE: 10, ASP.NET: 9, PHP: 10

Support and Community
There are plenty of forums, mailing lists, user groups, communities, developers, blogs and websites for all of three platforms. Most of the ASP.NET support, documentation and forums are managed by Microsoft, while PHP support is given by developers itself. J2EE have both commercial and open source support groups.

J2EE: 10, ASP.NET: 10, PHP: 10

Cost
PHP have big advantage on cost, both TCO and Maintenance. You can have IDE, Web Server, Operating System and Database all for FREE ;)
For ASP.NET development, first you have to pay for Visual Studio, then for Windows Server and for MSSQL. I don’t how much it costs total because my company already paid for them. For J2EE, you have choices. As I mentioned before, there are commercial and open source tools and software available. It depends on you and your company whether to use commercial, supported alliances or not. For example, if you plan not to pay, you can use Eclipse as an IDE, Tomcat or JBoss as a server, MySQL as a database.

J2EE: 9, ASP.NET: 8, PHP: 10

Conclusion
These three platforms are the most popular platforms for web development (of course, here we should mention Ruby On Rails, Django and few more ;) and they all have some advantages and disadvantages against each others. You have to choose the right platform according to the project behavior, size and scope, but also the criteria I listed above. I will not sum the total scores which will be unfair since I didn’t list all the available features of the platforms.

Related Comparisons and Discussions

See Also;
  1. Most Useful 20+ Visual Studio Add-ins
  2. ASP.NET AJAX Resources, Samples, Articles, Tutorials
  3. What is Microsoft Silverlight? Silverlight Resources, Articles and Tutorials
  4. AJAX Frameworks and Resources
  5. SQL Injection Resources
  6. Prevent robots from submitting data
  7. Frameworks are more important than Programming Languages
  8. Programming Handbooks and Cheatsheets

Sunday, July 8, 2007

Prevent robots from submitting data

Spam is/was/has been the biggest problem in the internet. Even in your application. You are developing and testing your web application, it works perfect. but when you deploy it on the internet, huge amount of data is submitted by someone, which is very big problem for you. So you have to prevent from spam like data submission. People have tried many methods to protect from spams, by the time the only method is proven and accepted as standard. Challenge/response CAPTCHA method. According to Wikipedia, CAPTCHA ("Completely Automated Public Turing test to tell Computers and Humans Apart") is a challenge response test which is used to check if the user is human or not. CAPTCHA is used exclusively in applications where user input is required. These applications include blogs, forums, and portals. From the following resources, you can find CAPTCHA implementations and tutorials in your preferred platform.

ASP.NET

Java

PHP

Rails

Programming Handbooks and Cheatsheets

Cheat sheets are useful one page document which you should print out and post it on the wall from of your eyes. It helps you to learn the subject more quickly, and saves your time.


PHP

AJAX

CSS

Perl

.NET
Python

Javascript

Ruby on Rails

Java

JSP

Javascript

HTML

Unix

Linux

C

C++
C#

Django

SQL

Web Development
Others
See Also;