Create a simple TagCloud in PHP

Create a simple TagCloud in PHP

Ok, as for my first post after my away time I’ll be showing you how to make a… Yes you figured it out, a TagCloud.

A TagCloud is as you know a Cloud… with Tags… hum, for some reason I think you already knew that. Anyway, jokes aside, a TagCloud is one of the most powerful visual information display nowadays. It’s not a complex module, by the opposite, it’s very simple.

A normal TagCloud displays all tags, in alphabetic order and the font size varies in according to the amount of times that tag has been found in use. Imagine that you have “hello”, “this”, “is”, “jose”,”blog” as your tags. You would get something like:

hello this is jose blog

You would know that “jose” is the tag with most views (when we say views we can say records in a database).

The installation of the module is very easy and all the required information can be found on the files that i provide.

Extra info:

// This will create a TagCloud with default max font size and minimum font size. The default values can be set on file tagcloud.php in function create_tag_cloud($array,$limit_top_size = 38,$limit_low_size = 18)
$tag_size = create_tag_cloud($tags_array);

Or with specific values

$tag_size = create_tag_cloud($tags_array,40,10);

Max font size will be 40 and minimum font size 10. (these are the max and min values allowed for TagCloud font fluctuation.

And there you go. Just style the code as you like.

PS: Yes, i know what you’re thinking, you can change the code as you please :)

Let me know if you have any issues.

09
Jul 2009
AUTHOR joseairosa
CATEGORY

Uncategorized

COMMENTS No Comments

Data lost! (Panic)

Well… as some that might visited my blog noticed I had a small problem… yes yes… NO, it was not the Aliens… well ok, some might’ve helped, but… I lost most of my posts!

Yes, it’s true, but now it’s not time to get upset. New posts are on the making :)

Until then.

09
Jul 2009
AUTHOR joseairosa
CATEGORY

Uncategorized

COMMENTS No Comments

Creating a pulldown website (like this one)

Creating a pulldown website (like this one)

I had the idea of creating this style effect after seeing a similar one in other website, only it was pullup and not pulldown.

We’ll be using JQuery Framework to produce the desired effect. JQuery by itself only enables the dropdown of one element, to make the desired output we need to do some modifications, and that’s what we’re gonna go over on this post.

First of all we need to import the required JavaScript:




Place these lines after <title> tag on the HTML code.

A few styles need to be added for this to work properly:

.drag_top {
	width:100%;
	height:400px;
	background-color:#333;
	margin-top:-380px;
	z-index:1000;
}
.conteudo_drag {
	height:380px;
	margin-left:auto;
	margin-right:auto;
	width:1200px;
	background-color:#333;
}
.hand_drag {
	width:100%;
	height:20px;
	background-color:#333;
	cursor:s-resize;
}

Now we need to initialize JQuery Framework and tell it which element will be affected by the dropdown effect.

After the code you just entered add:

$(document).ready(function(){
	$("#drag_top").draggable(
	{
		handle: '#hand_drag',
		axis: 'y',
		containment: [0,0,'100%',380],
		drag: function(even,ui){
			document.getElementById("page").style.marginTop = (ui.position.top)+'px';
			}
		});
	});

The element we’ve chosen to be affected is “#drag_top”.

  • “handle: ‘#hand_drag’” tells JQuery that only this element will activate the dropdown effect
  • we are going to lock it to the Y axis using “axis: ‘y’”
  • “containment: [0,0,'100%',380]” is where we specify the limits of movement of our dropdown, in this case we confine it to top 0, left 0, width 100% and height 380 from the top of the page
  • Finally we go over to the drag function, this is where we specify what will happen during the drag effect. The default drag function has 2 parameters; event and ui. Event has all event related information during the drag and ui has all changes that happen to the dragged element, so, in this case, we’re going to use that to update the rest of he page as the dragged element comes down.

For this to happen we first need to put all <body> content inside a <div> element with the id “page”


	

We still haven’t add the content of our dropdown element. Before <div id=”page”> and after <body> type

Drag Me!

And that’s it. Everything should be working. If not, go over the steps once again and check that everything has been added properly.
If you still can’t get it to work send me an email or comment this post in order, for me, to help.

See you on the next post :)

13
Feb 2009
AUTHOR joseairosa
CATEGORY

Uncategorized

COMMENTS No Comments

A good way to create Logs in PHP

A good way to create Logs in PHP

Hello everyone :)

Today we’re gonna go over Logging in PHP as nested Class.

With the introduction of PHP5 we now get the opportunity to use PHP as an Object Oriented Programming Language. What this means is, and in a very short way, that we can now have a more reliable, faster and safer way to program in PHP.

OO programming brings abstraction, encapsulation, inheritance, and polymorphism so, therefore, PHP also does.

  • Abstraction – Allows the programmer to declare abstract methods that can be instantiated in a class and declared by an object.
  • Encapsulation – Gives us the ability to protect which ever data, inside a class, by using protected methods like private classes ou functions.
  • Inheritance – We can now create tree like class structure where the lower levels on the tree are childes of the level above. (in this Logging example we’re going to be using this methodology)
  • Polymorphism – Using this feature we’re able to declare a given class and use his children methods even tho we have declared parent class without the need to redeclare them.

First of all we’re going to go over the basic structure of our Log class.

interface iLogs
{
 public function insereLog($entrada,$tipo); 
}

We declared an interface. This way the application that will be calling this class is able to read its available content without the need to directly access the class internally.

Note: Methods that are declared on the interface need to be equal to the ones declared inside the class itself (either method name or number of arguments required). Otherwise you’ll get a fatal error from PHP.

Next step takes us to declaration of the class itself.

class Logs implements iLogs
{
 const VERBOSE = false;
 // Max size for log compression -> 1MB
 private static $max_size = 1024000;
 // Folder in your root where the logs will be stored
 private static $cwd = 'logs/';

As you can see, we’re telling class Logs that it should implement interface iLogs that we previously declared.

Every class needs a constructor and a destructor. Basically what should and should not be done when we initialize the class.

 public function __construct() {
  if (!defined('LOG_FILE_ADMIN')){
   define('LOG_FILE_ADMIN','logAdmin.log');
  }
  if (!defined('LOG_FILE_CLIENTES')){
   define('LOG_FILE_CLIENTES','logClientes.log');
  }
  if (!defined('LOG_FILE_WEBSERVICES')){
   define('LOG_FILE_WEBSERVICES','logWebServices.log');
  }
  self::preparaDirectorias();
  self::preparaLogs();
 }
 public function __destruct() {
  
 }

__construct and __destruct use “__” since they are native to PHP5 and are automatically called when a class is instantiated.

When the class is built we want to create some constants used throughout the class and we want to check if everything is according to the file structure required.
We also use self to address the actual instantiated class and :: in place of -> because we’ll be calling them in static mode (no data can be changed).

Our destruct class is empty since there is nothing to be done when the class is destroyed.

Note: Normally you can use this function for a DB connection and destruct can close the connection.

 private function preparaDirectorias() {
  chdir('./');
  if(!is_dir("logs")) {
   if(!mkdir('logs'))
    throw new Exception ("It was no possible to create 'logs' dir"); 
  }
  if(!is_dir(self::$cwd."logs_arquivo")) {
   if(!mkdir(self::$cwd.'logs_arquivo'))
    throw new Exception ("It was no possible to create 'logs_arquivo' dir");
  }
 }

We attempt to check if folder structure is properly created, if not we create it.

 private function preparaLogs() {
  if (!file_exists(self::$cwd.LOG_FILE_ADMIN)) { 
   if(!fopen(self::$cwd.LOG_FILE_ADMIN , 'w'))
    throw new Exception("It was not possible to create '".LOG_FILE_ADMIN );
  } 
  if(filesize(self::$cwd.LOG_FILE_ADMIN) > self::$max_size) {
   self::compressbz2(LOG_FILE_ADMIN);
   unlink(self::$cwd.LOG_FILE_ADMIN);
   if(!fopen(self::$cwd.LOG_FILE_ADMIN , 'w'))
    throw new Exception("It was not possible to create '".LOG_FILE_ADMIN );
  }
  if (!file_exists(self::$cwd.LOG_FILE_CLIENTES )) { 
   if(!fopen(self::$cwd.LOG_FILE_CLIENTES , 'w'))
    throw new Exception("It was not possible to create '".LOG_FILE_CLIENTES );
  }
  if(filesize(self::$cwd.LOG_FILE_CLIENTES) > self::$max_size) {
   self::compressbz2(LOG_FILE_CLIENTES);
   unlink(self::$cwd.LOG_FILE_CLIENTES);
   if(!fopen(self::$cwd.LOG_FILE_CLIENTES , 'w'))
    throw new Exception("It was not possible to create '".LOG_FILE_CLIENTES );
  }
  if (!file_exists(self::$cwd.LOG_FILE_WEBSERVICES)) { 
   if(!fopen(self::$cwd.LOG_FILE_WEBSERVICES, 'w'))
    throw new Exception("It was not possible to create '".LOG_FILE_WEBSERVICES);
  }
  if(filesize(self::$cwd.LOG_FILE_WEBSERVICES) > self::$max_size) {
   self::compressbz2(LOG_FILE_WEBSERVICES);
   unlink(self::$cwd.LOG_FILE_WEBSERVICES);
   if(!fopen(self::$cwd.LOG_FILE_WEBSERVICES, 'w'))
    throw new Exception("It was not possible to create '".LOG_FILE_WEBSERVICES);
  }
 }

We’re going to check the size of our logs. If they exceed $max_size then we compress them and create a new and fresh log file.

 private function compressbz2($file_name) {
  $file_pointer = fopen(self::$cwd.$file_name, "r");
  //Opens the file in readonly,
  //Check for permissions
  $file_read = fread($file_pointer, filesize(self::$cwd.$file_name));
  //Reads the content
  fclose($file_pointer);
  //Closes the file
  $actual = date("-Ymd-His");
  $filename = $file_name.$actual.".bz2";
  //Opens compression file for writing purpose
  $bz = bzopen(self::$cwd.'logs_arquivo/'.$filename, "w");
  //Writes the file
  bzwrite($bz, $file_read);
  //Closes the file
  bzclose($bz);
 }

A simple function for compressing files. I will not go into a lot of detail on this section. If you find it to be useful please contact me and I’ll make a post about file compression.

And finally we’re going to create the method that we call when using this class to add a log.

Note: As you probably noticed (or not :P ) all other methods (except construct and destruct) are private and therefore can only be called from within the class itself.

 public function insereLog($entrada,$tipo) {
  if($tipo == 1) {
   $fp = fopen(self::$cwd.LOG_FILE_ADMIN , 'a+');
   if(!$fp)
    throw new Exception("It was not possible to create '".LOG_FILE_ADMIN );
   else {
    fwrite($fp,'['.date("Y/m/d - H:i:s").'] '.$entrada."n");
    if(self::DEBUG)
     echo $entrada."n";
   }
  }
  elseif($tipo == 2) {
   $fp = fopen(self::$cwd.LOG_FILE_CLIENTES , 'a+');
   if(!$fp)
    throw new Exception("It was not possible to create '".LOG_FILE_CLIENTES );
   else {
    fwrite($fp,'['.date("Y/m/d - H:i:s").'] '.$entrada."n");
    if(self::DEBUG)
     echo $entrada."n";
   }
  }
  elseif($tipo == 3) {
   $fp = fopen(self::$cwd.LOG_FILE_WEBSERVICES , 'a+');
   if(!$fp)
    throw new Exception("It was not possible to create '".LOG_FILE_WEBSERVICES );
   else {
    fwrite($fp,'['.date("Y/m/d - H:i:s").'] '.$entrada."n");
    if(self::DEBUG)
     echo $entrada."n";
   }
  }
  fclose($fp);
 }

This logging class supports logs for 3 different types of systems; frontoffice (clients), backoffice (administrations) and webservices.

The way you call this function can be done in different ways, in this case, I’ll go over the Inheritance feature we talked before.

Imagine you have a class, lets say, foo

class foo {
 public function hello() {
  // I bet you never seen this before!!! hehe ^_^
  echo 'Hello World';
 }
}

What we can do is…

//Logs.class.php is your Log class we just did
require_once 'Logs.class.php';

class foo extends Logs {
 public function hello() {
  // I bet you never seen this before!!! hehe ^_^
  echo 'Hello World';
  Logs::insereLog("Mom, I think i just said Hello World. Log it please, thank you!",1);
 }
}

And voila, there you go :) your very own log system out of the box.

Feel free to report me any mistakes, suggestions or doubts you might have.

Have fun and be != be# {‘run remotly’ && Get['4_free'];}

10
Feb 2009
AUTHOR joseairosa
CATEGORY

Myself

COMMENTS 401 Comments

5 killer apps for developing websites

5 Killer apps for developing websites

What better way to start out?
With the complete basics :)

We cannot develop good applications without the appropriate tools. A bit like a carpenter doing some wood job without the perfect hammer or pincer.

I’m gonna show you 5 awesome applications that will change the way you program and develop.

( Ok, since I’m a Mac user I’ll share apps that work on both platforms, Mac OSX and Windows )
1. FireFox Web Developer Toolbar

This is without a doubt one of the tools that has helped me the most all these years.
Easy to use, lightweight and groups all the features you need while debugging or analyzing a website.

Web Developer Toolkit

From all the features I find the following the most important:

  • Convert POSTs to GETs
  • Cookie Information
  • Current Window Size
  • Disable Styles
  • Display Form Details
  • Enable Autocompletion
  • Hide Images
  • Outline Block Level Elements
  • Outline Images Without Alt Tags
  • Outline Table Cells
  • Resize to 640×480
  • Resize to 800×600
  • Resize to 1024×768
  • Validate CSS
  • Validate HTML
  • Validate Section 508 Accessibility
  • Validate WAI Accessibility
  • View Source
  • View Generated Source

I personally use the View Generated Source a lot when I’m developing AJAX supported applications.

2. MAMP and WAMP

Originally created for Mac OSX (MAMP – Mac Apache MySQL and PHP) this was, for me, the best application I’ve tried.
It does 3 in 1 one-click-support for a complete web server directly on your Mac. No need to do hard configurations. Just set the port to be used by Apache and MySQL and you’re set. (I used 8888 for apache and 8889 for MySQL)

MAMP

Above all other functionalities it really shines when you need to continue working and you are not able to get an Internet connection (Yes it did happen to me a couple of times), just use MAMP widget, start your servers and access your own server by going to “http://localhost:8888“.
As simple as that!

WAMP as you probably figured out by now is the same application but this time for Windows.
WAMP is not as simples to set up as MAMP, but nether less, it keeps the do-it-simple.

WAMP
3. Coda

Coda

I know this one is for Mac OSX only but I cannot go by a not mentioning it.
An awesome tool for developing and completely managing you websites projects.

WebDevelopment + FTP Support + Coolness = Coda (simple formula that says it all)
Coda

Coda has all the fancy tools that any web developer uses on they’re daily basis.

4. Sequel Pro / MySQL Administrator

Sequel Pro is the perfect tool for quick and easy management of a database (MySQL one).

Very simple and easy to use.
It allows all normal views, Table, Content and SQL, it has SQL code verification and support for various databases.

Sequel Pro

As for windows, from what I’ve seen, there aren’t many applications that can surpass MySQL Administrator.
Created by MySQL development team this is The tool for MySQL management, and the good thing about it, it’s free :)

Sequel Pro
5. Power*Architect

A few months ago I didn’t know about this application, but as soon as I got in contact with it I just started to love it.

It’s data modeling made easy and fast. The great thing about this piece of software is the ability to export to SQL, most of the types as supported.

Power Architect

There are a lot more good apps and I only chose these ones for they’re utility and easy to use features.

Feel free to comment and suggest a few more.

10
Feb 2009
AUTHOR joseairosa
CATEGORY

Applications

COMMENTS No Comments

Welcome!

Hello fellow community!

This is my first attempt at creating my own Blog. (yes i know, please bare with me)

So that you know a little about myself, I’m a 22 year old lad from Portugal, Vila Nova de Gaia.
I’m a student at ISEP (Instituto Superior de Engenharia do Porto) and at the moment finishing my Computer Engineering degree. I also created a WebDesign and Development company with three other partners called CoreCreations® (feel free to give us some feedback).
I can be found on LinkedIn at my profile

I’m a nice person (hope so), a workaholic (when it’s needed) and tech geek that’s always searching for more and more information.

As posts are made I’ll keep talking a bit more about myself, and hopefully you’ll learn bit by bit about myself.

The main purpose of this Blog is to give you tips&tricks regarding web programming. From PHP, MySQL to CSS and HTML, going trough JavaScript and AJAXand ending (maybe not) in WebDesign.
I know there are a lot of other Blogs (Chris Shiflett, Chris Coyier, etc) and those are way better than mine, but the main reason I’m doing this is also to learn by helping.
Everyone knows the basic of programming learning, good old try&error. He’s our best friend for good and for worst (yep… he does sometimes drive you nuts). I’m basically seeing this Blogs like that. By helping you I’m also learning, and hey, guess what, that’s the fun of it!

I’m still trying stuff out with this new Blog layout. For now I’ll be using a free template I’ve grown fond of and soon, if everything goes good, a new one will be created from scratch.

See you all very soon!

10
Feb 2009
AUTHOR joseairosa
CATEGORY

Uncategorized

COMMENTS No Comments