Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Sunday, February 25, 2007

Ease your recursion

Ever wanted to have an easy way of building a recursive tree ?
Or something like that ?
Or even without understanding much of recursion or always thinking how was this done and so one ?

Well I eased your life a bit ;P



<?php
/**
* Function that builds a category tree with recursion
* (it selects only id, [your specified field] and parent_id
* from the selected table)
*
* @param string $spacer
* @param string $table_name
* @param string $field_name
* @param integer $start_id
* @param string $link
* @param string $request_param
* @param string $link_style
*/
function buildRecursionTree($spacer = '>>' , $table_name ,
$field_name , $start_id = '0' ,
$link , $request_param ,
$link_style) {
global $db;

$sql = "SELECT `id`,`$field_name`,`parent_id`
FROM `$table_name`
WHERE `parent_id`='$start_id'";
$result = $db->query($sql);
while (list($id,$name,$parent_id) = $db->fetch_array($result)) {
$spacer_next = " ".$spacer;
?>
<?=$spacer?>
<a href="'<?="$link?">?<?=$request_param?>=<?=$id?>'
style='<?=$link_style?>' >
<?=$name?>
</a>
<br/>
<?
buildRecursionTree($spacer_next , $table_name ,
$field_name , $id ,
$link , $request_param ,
$link_style);
}
}
?>


And now some sample usage ;)


<?
$spacer = "<img src='images/arrow.png' border='0' />";
$table_name = "categories";
$field_name = "name";
$start_id = "0";
$link = "index.php";
$request_param = "category";
$link_style = "color: #000000; font-family: arial;
font-size: 11px;
text-decoration: none;";
buildRecursionTree($spacer , $table_name , $field_name ,
$start_id ,
$link , $request_param , $link_style);
?>


Well easy enough huh !
See the sample result yourself ;)

Прочети цялата статия...

Wednesday, February 14, 2007

Ruby - the power of simplicity

I expect that most of you have already heard of RUBY.
If not! Well RUBY is the new hot programming language... as always new doesn't really mean it has been released yesterday but it is a newcomer to the world of programming language popularity.

Why is ruby hot?
Well RUBY is all about simplicity.
You know when you switched from C or Java to PHP when developing web based applications and saw how PHP deals fast and easy with web oriented stuff... so does RUBY.
Actually RUBY has been planed all around web application development. It focus on simplicity and elegance. It is a mix between PHP,PYTHON and maybe JAVA. You know! Everything in RUBY is an object! Yes! That is true :) everything is an object so for the object oriented developers it is really a good one ;)
But what is a programming language without the TOOLS.

RUBY ON RAILS
Ruby on Rails is a framework that will help you deploy everything almost out of the box. It is really made simple, elegant and very very powerful!
The actual idea of Ruby and Ruby on Rails is to enable the developer to focus on the actual problems ... what the user see and get... not the background stuff and all the silly little problems but the actual problems and solving them.

If you think I am over happy with ruby and I talk this because I am a ruby developer you can see the statistics at TIOBE
Yes that is right :) RUBY has gained an enormous popularity recently and stepped 10 positions above. Eventually I should tell you that the trends for 2007 are like this:
1. Microsoft Vista entering slowly on Desktop PC
2. Ruby gaining vast popularity among web developers
3. ...

Hmmm sounds good right ? :)
So to make you over happy I will tell you more on Ruby on Rails.

Ruby on Rails is the software you need for ruby development.
You remember when I said about making something almost out of the box ?
Well ruby on rails enables you to have UNIT testing on the fly... database stuff that generates by default and you know it is really a good software. The people from 37signals have really done again a great job with this peace of software.
What really makes people like RUBY and RUBY ON RAILS is that 37signals designed Rails with simplicity, elegance and POWER in mind. All you need to setup for the proper development of an application is made simple and powerful and you can come up with UNIT TESTS (for example) in the blink of an eye... it is made automatically for you.

But enough talking you can see more about RUBY on http://www.ruby-lang.org/

Прочети цялата статия...

Saturday, February 03, 2007

Basic SEO - steps to improve your SERP

Well I've been asked to write about SEO.

For those that don't know what SEO is it is the short of Search Engine Optimization. But what does this really mean ? It means that if a good SEO is in place your web page will display on top of the results in some search engine for a certain keyword.
For those that don't know what SERP is ;) it stands for: search engine results page

Sounds like interesting stuff?




Well here are a few steps to actually achieve this:

BASIC

1. Use H1 html tag to display your title

2. Use H2 for the subtitle

3. Keywords meta, title, description, url, h1 and h2 tags should have something in common if they are the same the satisfaction will be 100% ... so the use of a term like "findacar" for example if used right in all the stuff of the web page shall bring you very good results in search engines with the search term "FIND A CAR"

4. Do bold or strong whenever possible ... Google thinks it is important and raises results for your page for the tagged word

5. Do not use a lot of keywords in the meta

6. New content is very positive... a forum on your site shall bring enough new data for the day

7. Making your sign in the forums at the bottom of your post to be a link at your site will both increase traffic(which is the most powerful SEO) and will give a link to your page(SITES THAT LINK TO YOURS IS CONSIDERED KEY FUNDAMENTAL IN MOST OF THE SEARCH ENGINES FOR DISPLAYING... ESPECIALLY GOOGLE)

8. Don't waist your energy on giving links off your site... it will decrease your overall SEO... especially the Google results for your site

interesting

The GOOGLE Page Rank algorithm is LINK based!
It will place you more on top if major PG(Page Rank) sites give a link to yours. So a fundamental concept is to have more inbound links (to your site) ... at the opposite side external links (on your site pointing to an other site) will decrease your PG.


ADVANCED

1. The Google algorithm is strongly working depending on links... a good practice is the management of your own links(your inside site navigation and so on links) too!
The very first thing is: NOT HAVING BROKEN LINKS

2. NOT HAVING A TREE STRUCTURE OF LINKS THAT THE CRAWLER WILL CRAW AND END ON A PAGE WHERE IT CAN'T MOVE FROM IT... EXAMPLE NOT HAVING LINKS THAT ARE POINTING BACK TO YOUR HOMEPAGE

3. Having as much links that the crawler needs to crawl ... so not only to have on all the pages the home link but also many others so that the bot stays on your site much longer and finds more info... it is questionable the methods of how the crawler really works but this is tested stuff believe me!

EXPERT

If not used right this might be considered gray or even BLACK hatting so please be ethical,moral and so on on this one! I DO NOT ENCOURAGE THE USE OF ANY BLACK HAT STRATEGIES!!! I am writing strongly white hat strategies which are 100% acceptable from the SEARCH ENGINES policy and terms of service and so on...
This tips are not straight forward so it might be a good idea to check wikipedia or search Google for ideas about this.

1. Making use of the SLASHDOT effect

2. Making use of the DIGG effect

3. Making use of GOOD INFORMATION

This is the most important one!
IF YOUR SITE HAS VALUABLE CONTENT THERE IS A 99% PROBABILITY OF PEOPLE LINKING TO IT AND MAKING ENORMOUS AMOUNT OF TRAFFIC WHICH IS OUR MING GOAL!!! WHY DID I PUT THIS HERE? WELL PUBLISHING AND INTRODUCING INFORMATION IS NOT SO EASY AND IS ACTUALLY THE MOST TIME CONSUMING AND HARD CONCEPT OFF ALL. MAKE SURE YOU WILL INTRODUCE THE INFORMATION IN AS MORE HTML-ALIZED VERSION TO THE AUDIENCE AND MAKE IT SHORT AND PAGINATED. ALSO IF YOU SKIPP MOST OF THE JAVASCRIPT AND FLASH EXTRAS IT WILL BE POSITIVE FOR YOUR SEO. MAKING W3C VALIDATIONS WILL ALSO BE VERY USEFUL AND WILL MAKE POSITIVE SEO RESULTS!




Making more simple and html-lized as well as friendly and more standard compliant sites will be the most powerful SEO from the view of the development process. The next thing is introducing valuable information!

Hope this one article was useful!




Want to try your SEO skills ?
Wonder how ?
Here is a link to a contest where you can try and will a small price ;)
http://bgwebmast.org/


Прочети цялата статия...

Sunday, January 21, 2007

Looking for a Delphi like thing on LINUX ?

Well there isn't much time needed to think and we will come up with KYLIX. But isn't there something that is both not BORLAND and does give us quite a lot of useful things to do only with the mice ... do the things on linux we want to do ... without doing a nasty coding but more of designing our application with just the mouse ?

Well there is something ;)

KOMMANDER

It is a KDE thing but is just what we need... it does feels like BASH scripting but
offers us a way to escape from the konsole. I aways wanted to BASH script a Desktop application with all the GUI and so on :) now I got a chance.
This TOOL isn't actually very new... it exist from quite a lot of time but according to my recent research which was inspired from just asking about a tool which will offer me the ease of use to do a simple NOTE TACKER application... I was given quite a lot answers and finally KOMMANDER was introduced to me in it's full glory :)
So you might want to take a look at the link I provided and also you might find these links also useful:


So why I did wrote this again.
I did wrote this article to remind the world about this TOOL.
When I did asked for the tool to do my NOTE TACKER application I was flooded with C and C++ things... QT ... python and so on!

THERE IS AN EASY WAY! IT IS THE KOMMANDER WAY!

Прочети цялата статия...

Monday, January 15, 2007

3 basic files to work with

I haven't posted anything "code like" for some time huh ;)
Well now is the time to actually dig up some code!



I thought a lot about the topic to write on and it will be really a one for starters.
These 3 files I will show you are the solid foundation of all my projects. A project should have these files always. If a project does not contain those files or files like the one I will give you then it has a major drawback or is just too small so it doesn't actually needs it ;) but you need almost 99% of the time files that serve this purpose. So enough with the initial bla bla bla :) nets code ;)


I will follow this schema:

1. Describing why it is good to have it
2. Actual CODE
3. Tips and other options to this





NAME: config.php
1. Description

This is a configuration file which will give you the control over the server. As a server I mean that you will be able to tweak the php.ini file as you like. This file represents a large number of ini_set() function which will temporary change the scripts behavior. Changing the php.ini config or the scripts behavior is a big plus when developing a project which will be hosted on a server which is out of your touch and for example you can't touch the php.ini file to say hide the error reporting or so on. So having this allow us to change the preferences of PHP as expected by us, the developers! Take a note that some of the directives might not be changed so don't expect always to have a full control over the php.ini!

Besides PHP configuration this file represents a central unit for defining the PATH of our application or the USERNAMES, PASSWORDS and so on of say, the DATABASE server. So have a look a it!

2. The CODE


##################################################################
#
#===== CONFIGURAION FILE =====
#
#=================================================================
#
# php.ini directives
# database constants
# path constants
#
#=================================================================
#
# PHP 5.2 version
#
#=================================================================
#======= created by Yavor Ivanov | email: =======#
#=================================================================
##################################################################
//////////////////////////////////////////////////////////////////


#===== PHP.INI DIRECTIVES
ini_set("output_buffering" , 0); // OUTPUT BUFFER
ini_set("safe_mode" , 0); // SAFE MODE
ini_set("expose_php" , 0);
ini_set("max_execution_time" , "120");
ini_set("max_input_time" , "60");
ini_set("memory_limit" , "16M");
error_reporting(E_ALL | E_STRICT); // ERROR REPORTING
ini_set("display_errors" , 1); // DISPLAY ERRORS
ini_set("display_startup_errors" , 1);
ini_set("log_errors" , 1);
ini_set("report_memleaks" , 1);
ini_set("html_errors" , 1);
ini_set("error_log" , "syslog"); // ERROR LOG
ini_set("register_globals" , 0);
ini_set("magic_quotes_gpc" , 0);
ini_set("magic_quotes_runtime" , 0);
ini_set("file_uploads" , 1); // FILE UPLOADS
ini_set("upload_max_filesize" , "10M");
ini_set("session.use_cookies" , 0); // USE COOCKIES
ini_set("session.auto_start" , 1); // SESSION AUTO START
ini_set("session.cookie_lifetime" , 0);
ini_set("session.gc_probability" , "1");
ini_set("session.gc_divisor" , "100");
ini_set("session.gc_maxlifetime" , "1440");
ini_set("session.cache_expire" , "180");
ini_set("url_rewriter.tags" , ""); // URL REWRITER
#=================================================================


#===== DATABASE CONSTANTS
define("DBHOST" , "127.0.0.1");
define("DBUSER" , "username");
define("DBPASS" , "password");
define("DBNAME" , "database");
#=================================================================


#===== PATH CONSTANTS
define("BASE_PATH", str_replace('\\', '/', dirname(__FILE__)));

define("CLASSES" , BASE_PATH."classes/");
define("WEB_ROOT" , BASE_PATH."/web_root/");
#=================================================================
?>



3. Tips and other options to this

There aren't much words to be put in here for this piece of code but we can say that you are free to add some more directives or define more constants at your desire and need. The tricky thing you can do here is to put as much configuration options as possible so your team mates knows that they only need to go in here and change the desired thing.





NAME: session.inc.php
1. Description

Basically this is a file to be included always at the start of every file. Why? Because it starts the session every time and keeps it running trough the whole application and also protects from hijacing. But let us see the code!

2. The CODE


session_start();
session_regenerate_id(true);

// if the user is just accessing the server his session
// is empty so BUILD a unique hash and put it in
if (empty($_SESSION)) {
// md5 or sha1 might be used for increased security
// but it might become slower
$_SESSION['hash'] = $_SERVER['REMOTE_ADDR'] .
$_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_PORT'];
} else{
// md5 or sha1 might be used for increased security
// but it might become slower
$hash = $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] .
$_SERVER['REMOTE_PORT'];

// if the hash is different from the original one build
// when first accessing the SERVER
// there might be a second user who might be a hidjacker
// so we destroy the SESSION !!!
if ($_SESSION['hash'] != $hash) {
session_unset($_SESSION);
session_destroy();
session_start();
session_regenerate_id(true);
$err = "Sorry there was a problem accessing the page!";
exit($err);
}
}
?>



3. Tips and other options to this

So what you see here is changing the session on every click of the user ;) why? Why not :) Every switching of session id can make our un-welcomed harmful user have a hard time. Beside in php5 regenerate_id() has a param of true which will destroy our previous session. Also making a unique hash of some info about the user protects us from hijacing. You can do the hash more complex and unique :) just play with code a bit it is well documented and easy to read :) at least my team mates and I think so.




NAME: database.class.php
1. Description

What you will see in the source is a PHP 5 class which will connect automatically to the database, when you create the object and the cool thing about this class is that it will execute every single query as a custom method... what is so cool about it :)
Well if you decide that you will use postgres sql you will not change all the mysql_query with pg_query for example but instead you will change just the class methods ;) cool huh! And I made a special param called DEBUG when you give it TRUE it will print your query ;) so you can latter paste it in for example in phpMyAdmin or something of the sort and look at what is actually causing trouble and so on ;) yes you can do it some more advanced like putting error logging and so on so this is the reason you can use the class and upgrade it ;)

2. The CODE


##################################################################
#
#===== Database Interaction Class =====
#
#=================================================================
#
# Written for MySQL database server
# Easily modified to work for a different SQL server
#
#
#=================================================================
#
# PHP 5.2 version
#
#=================================================================
#======= created by Yavor Ivanov | yavor.xenium@gmail.com =======#
#=================================================================
##################################################################
//////////////////////////////////////////////////////////////////


class DBI {
private $init_db;


public function __construct() {
if ( !isset($this->init_db) ) {
$this->init_db = mysqli_connect( DBHOST , DBUSER , DBPASS , DBNAME );
}
}


public function __destruct() {
mysqli_close();
}


//============================================================


function query($sql , $DEBUG = false) {
if ( $DEBUG == true ) {
print "";
print "SQL: ";
print "
";
print $sql;
print "
";
print "
";
}
return mysqli_query($sql);
}


function fetch_array($sql) {
return mysqli_fetch_array($sql);
}


function query_and_fetch($sql , $DEBUG = FALSE) {
$result = $this->fetch_array($this->query($sql));

if ( $DEBUG == true ) {
print "";
print "SQL: ";
print "
";
print $sql;
print "
";
print "
";
}

return $result;
}


function num_rows($result) {
return mysqli_num_rows($result);
}


function get_last_id() {
list($value) = $this->query_and_fetch("SELECT LAST_INSERT_ID()");
return $value;
}


}
?>



3. Tips and other options to this

So as I said the cool thing is that you can actually change databases very easily with few mods of the class. Also adding error logging might be a good idea or for example you can make automated escapes of variables or just another method like EscapeParam for example ;)
Use you imagination here and automate as much as you can to ease your work! Notice I use mysqli so don't expect this to work on php4.

There are a lot of object persistent classes and abstract ones but this is something that is easily understood and is something that you can tweak around :) most of the persistent/abstract classes aren't very short and need time to go into the code while this is short and useful the other alternative (I mean the persistent/abstract classes) are much more powerful and offer much more things ;)




Well with this article I demonstrated the basic files each application should have. I hope those of you who didn't knew where to start now know the entry point and will start smooth ;)
The demonstrated here CODE isn't the best! Come on! Spare me all the critics you might have for it... it is far than a complete solution. The targeted audience isn't experienced programmers which know everything while sharing some ideas might enlightened them, it is new ones that could not find the path and I try to give them what is considered good.


So I hope you will find the CODE interesting and you got idea what to do with it so start the codding, have fun with it and.... CODE it secure ;)

Прочети цялата статия...

Tuesday, January 09, 2007

Why programmers don't want to comment code

Why don't developer comment their code?
This is a question I will try to answer by summarizing my life experience.
I've been coding most in PHP but I coded also in a few other languages but the majority of code I have written is PHP so I am a PHP programmer and that has shown me a lot of ugly thoughts why people just wont comment their code.
So here are some of the reasons why most of my colleagues and team mates didn't wont to comment their code and often find more appropriate to delete mines too so they see more REAL CODE than bullshits like comments and lines that separate CODE from DESIGN and so on.

"I'm lazy!"
Well I am lazy too. Laziness is the reason why people are so advanced these days ;). That is why I personally comment my code. I don't want to figure it all out again later cause I forgot what it was and how it works. Think about it. If it is commented you will never have to figure it out again because you have written down an explanation of all the weird parts. It ease everyones work if you haven't got to figure out the problem again every time it comes up.

"Good code is self-documenting!"
The programmer that thinks that way thinks his code is so good that any moron could understand it without comments. After all good code is self-documenting is it? Totally wrong! There are many pieces of code which just could be understand by looking at it. For example because they are one line of code. But in the big picture most of the hard to code algorithms aren't obvious at first look to all the programmers even to you if you look at it after a while. So hard, complex algorithms and code blocks should be documented.

"Upper management doesn't care about comments!"
The BOSS looks at the metrics supplied to him. These usually are like lines of code, hours spent at work, tasks completed or simply does this work. But just cause time spent commenting is not reported or your boss isn't interested in it doesn't mean it isn't important at least to you. The better your comment skill is, the more productive you will code when you rewrite or upgrade your code later. This will decrease some of your hours in the long term so putting some extra time in the beginning might be a good idea.

"I'll never work on this after I'm done!"
This is the normal newbie mistake. So when you have finished your first project and all went well with it you are ready to move on the next one and you do. You might get a couple of more projects done but then they start coming back to you. It is not because they were bad written but because the users wants new features. The idea is that if you have written something once you will most of the time (99% of the time) need at least a piece of it again.

Well I think I gave you enough reasons to think about this for a moment and at least give it a try. After all how bad could it be to put an extra sentence at the end or at the top of your code block ?

Well have fun with your comments...
and your well written never reused code too ;)



I will really appreciate comments on this topic.
And if you have in mind another reason why programmers just wont comment their code feel free to share it with us ;)

Прочети цялата статия...

Monday, January 08, 2007

PHP Security Tips

A lot of programmers out there use PHP to do their every day tasks but a lot of them are not very aware of SECURITY issues at all. So this article is intended to those users who actually are not very aware of the security in PHP development. I will provide some basic overview and run through the most common problems and their solution and actually I will tell you some pretty cool tricks so you don't worry about your applications security. So shall we start ?

Short list of security issues:
1. Not escaping user input fields
2. Not escaping SQL queries
3. URL parameters hack
4. Giving direct access to files
5. Configuration of the web server



First of all I shall say that this article will not make you aware of all the problems you might get when fighting with crackers and there are plenty of other hacks that will not be covered here... but this list of SECURITY issues shall be more than enough for your web site to be stable and secure. And second - a completely secure system is virtually impossible.

This is what I call a list of basic security issues which most of the unexperienced web developers are unaware of.

1. Not escaping user input fields
and 2. Not escaping SQL queries

Escaping of a string means the obscuring of the special symbols like HTML or SCRIPT tags which provide native code execution or something of the kind. So escaping means if we put our PHP code in a post on a site which has escaped our post the code wont execute.

Well as you might already think not using this method for protecting your site is a very serious issue. Imagine this web page where you can post a comment. Imagine you can make in your post a whole new page. Well lets just limit our imagination to a JavaScript for redirection. So if a user posts this JS like a comment and all the symbols aren't escaped we will end up with a page which will redirect to somewhere else... so a big minus for our users and probably they will not come back to our site because the HARMFUL user already did his job well to bring our site down. And just in case this seems not so bad for you imagine putting a piece of code which will execute and delete our database or just bring our web server down (without redirecting).

A simple code use that will eventually prevent the closing of an html tag:


//user submited text is: I will brake you code with this " symbol
$str = $_POST['user_submited_text'];

echo addslashes($str);
// Outputs: I will brake you code with this \" symbol


Addslashes function will escape the ' , " , \ and NULL symbols by putting a dash in front of them. Actually addslashes will be more effective for our second issue - SQL queries.
SQL queries are vulnerable to the so called sql injection. It means that you want ot submit a qeury with a value that is submitted by the user but instead of standard WORD he puts a whole string that makes your query end, begins a new query build by himself then ends his query.
And guess what might his query be? Maybe "DROP dbname;" will be appropriate which ofcourse isn't a good query and will drop our database.

So a really useful thing in all the cases is to just use not addslashes but some other function which will escape most of the harmful symbols like < > ? ; " ' and so on.
So a good function to use is htmlspecialchars, mysql_real_escape_string or build a custom one.


3. URL parameters hack
This issue is connected with what the most of the normal web surfers don't really see.
The GET parameters in the URL. Normally these GET params are of great help for the web developers so they can process information across multiple scripts but if those scripts are badly written a potential security hole is open and a cracker might use this against us.
See this example of telling the script to create a page.
http://example.com/pages.php?action=create
Let us say this script gives you control over your pages and you can create, edit and delete your pages. Well normally the delete process would be something like this:
http://example.com/pages.php?action=delete&id=2
Well this will tell the script to delete page with ID = 2. But what if the user doesn't pick one of the links with his assigned pages IDs but puts like ID = 2105. Well he might just got one of our users hate us for deleting his page. So you should be very careful about the usage of URL GET PARAMS in your application. A method to protect is to double check everything especially user rights. I can't give you a code example to protect against this cause it will depend on what you have programmed but you can use isset(), empty() and the $_SESSION super global array to prevent some of the bugs you might INCIDENTALLY leave. Cause you know no body is perfect.


4. Giving direct access to files
Another issue is the use of require_once("script_name.php");.
What is wrong with this? Actually nothing :)
You include a file which will provide certain functionality in another file which you have checked that the user has been logged in and so on... security security security.... but what if the user access this file directly and skip all the checking that were made in the other file?
So providing access to all your script files is a bad idea.
you can always put tons of code in them to make them not execute but!
I said something about tricks right ?
Well most of the web developers use htaccess files to protect files from direct execution or as I said tons of code includes which serves the same purpose. Well here is the tricky part.
While developing your web application make a directory like WEB_ROOT where you will put all the visible parts of the site like all your HTML files, images and so on. The scripts you include one level up in the tree. So you have all the scripts in the ROOT folder and all the things that the users will see in its subfolder named WEB_ROOT. In the WEB_ROOT include just one script file (mostly this is the index.php file) which will control the scripts that aren't directly accessible. And when you deploy your web site just make sure your domain name will load the WEB_ROOT folder.
Why this is tricky?
- you don't need many files for access control
- you don't include unnecessary protection code in your files
- PHP works with the file system (so it can access the files with ../ but HTTP doesn't work the same way and ../ wont bring you the content of the ROOT folder).


5. Configuration of the web server
Many problems come from miss configuration of the web server especially the php.ini file which is responsible for the PHP module of your web server.
While in general this is a custom process you can do the following to protect.
1. Make a config file to include in your project if you don't have/use one
2. with ini_set set some of the php.ini directives so they work as you expect
3. turn error_reporting off when you site is in production state not development
4. and at the end always recommend to turn php into safe mode




I say again that this is far alway from full list of SECURITY issues. But this shall be more than enough if you comply with it to provide your application a stable and secure environment to run.

There is a lot about this topic I will be glad to explain if you leave a comment and ask politely! But I will have to ASK those of you who will find my article unsatisfied to not submit their hate here!

As I used to say: "Love your code, have fun with it and don't hate it" ;)

Cheers!

Прочети цялата статия...

Sunday, January 07, 2007

IE7 Web Developers Nightmare

Internet Explorer 7 has kicked in at last on all MS Windows OS running PCs because of the fact M$ decided to force it's users to migrate through update. Well actually there isn't much wrong with this but IE7 was supposed to comply more with the standards what in fact isn't true.
IE7 is a night mare for most of the developers that try to comply with standards for crossbrowsing.
I recently needed to rewrite a web site so it works on firefox too... and the surprising element was that when testing the new and the old site on IE7 I found out that many things does not function as expected and "not function as expected" isn't the right word for it, it was more a question of working at all.

I found that submiting through JavaScript has some pretty uncool things which I don't actually blame IE but some functions did not work when not passing all the parameters and so on.
And the MOST killer thing was the DISability of IE to submit data through "input type img" which actually was the whole sites data... I don't actually blame the programmers that they did it so but IE for not keeping with standards again.

So actually with IE7 we come to a new era of "web developers nightmare" as it will require BAD and maybe not so BAD web sites to be rewritten and this with crush some of the small companies business.

And a final TIP from me! Try avoiding writing JavaScript without testing it 100% on all of the major used web browsers like FireFox, IE7, Opera and Safari.

Just to have a clue:
According to W3C the web browser market share of IE7 for the previous month is: 7.1%
and for IE6 is: 49.9%

So with a bit of analyzing the situation and the facts as well as doing some math we can say that IE7 will show a market share of about 60% according to W3C... which isn't the best picture for us the devs.



Have fun with you code and don't hate it :) hate the things that don't comply to the standards...

Прочети цялата статия...

Saturday, January 06, 2007

Use of Model View Controller

Model View Controller also known as MVC is a great way to do development. But what actually is MVC? It is not a tool or software that you can actually buy... well yes you can buy it and you can name it a tool but I will not speak of those made by others but for those hand made by you. OK so what was MVC? MVC is a self made FRAMEWORK. It's idea is to have TREE TIER SOFTWARE DEVELOPMENT.
Those tree layers are Model, View and Controller. In this article I will write mostly about the CONTROLLER and leave you space to think about the other elements while I will try to give you some basic idea about them too.


step 0. We start building some project and we don't know where to start from. Obviously we should start with some configuration file right? That is good... but don't forget the initial planning it is way more important but we skip this now :) After building some config file we need an index.php file which we will enchant with the power of MVC methodology.

So a basic step 0 is to make a config file and index.php with some basic design and idea.

step 1. The next thing we will do is to build our CONTROLLER. It is responsible for controlling the overall process of our application. So it needs to comply with the following things:
- handle URL requests
- process requested information to and from the layers
- handle loading of classes

This is our very basic form.
/we skip some other code that should be there keep that in mind/


Here it is in PHP code:




##### ..:CONFIG FILE:.. #####
require_once("../config.php");
##### ***CONFIG FILE*** #####

##### ..:AUTOLOAD:.. #####
function __autoload($class_name) {
$dirs = array('/experts/','/experts/db/','/experts/user/', '/experts/question/');
array_push($dirs,'/experts/exceptions/');

foreach ($dirs as $dir) {
$classfile = CLASSES . $dir . $class_name . '.php';
if ( file_exists($classfile ) ) {
require_once ($classfile);
}
}
}
##### ***AUTOLOAD*** #####

##### ..:CONTROLLER:.. #####
if (isset ($_REQUEST['module'])) {
require_once(MODULES . basename($_REQUEST['module']) . ".php");
} else {
require_once(MODULES . 'default.php');
}
##### ***CONTROLLER*** #####




So what you see in this code is that we include in the first place the CONFIG file and this shall be clear why. The second thing is making use of AUTOLOAD function in PHP5 which finds for us the needed class and we don't care about including classes we made into the files (modules) we write.

And then the actual CONTROLLER which just looks a GET parameter and sees if its name build with .php exists in the MODULES folder and if yes it loads it... if not it loads a default one.

This is the INDEX.PHP file code... it needs to have some design or some VIEW implementation which you can see how to achive in the bottom (well actually you will have to read a bit more off this site but don't bother I might write about this another time)

step 2. Is the Model... we will call these MODELS - MODULES.
These MODULES work in the following way:

They are loaded by the CONTROLLER and they serve a specific functionality like login/logout. In this Module we work with the functionality (the classes) we wrote. And this is it.
We might do this to work directly with the VIEW as the following code:




// Proccess with user input if given
if (isset($_GET['action'])) {
switch ($_GET['action']) {
case 'login':
require_once(STATIC_MODULES."login/handle_login.php");
break;
case 'logout':
require_once(STATIC_MODULES."login/handle_logout.php");
break;
}
}

// Display the needed Smarty tpl
if (isset($_SESSION['auth'])) {
$user = unserialize($_SESSION['user']);
$user->loadStats();

$smarty->assign("button" , '<a href="index.php?action=logout">
<img src="button logout.png" style="border: 0px;" />
');
$smarty->assign("username" , $user->getUsername());
$smarty->assign("title" , $user->getStats()->getTitle());
$smarty->assign("points" , $user->getStats()->getCredits());
$smarty->display("STATIC/login/login.tpl");
} else {
$smarty->display("STATIC/login/login_form.tpl");
}




The Module just looks after a PARAM to be sure if it is set then process to other modules if necessary ... then it unserializes an OBJECT of the user from the SESSION loads the user info and process the needed info for the VIEW (which is SMARTY template engine).

step 3. The VIEW is already mentioned it is just a TPL file of SMARTY ... for more info about this Templating Engine look at smarty.php.net or just google it for more information. In few words the VIEW is a TPL file which has in it those {$variableName} tags which by parsing this file they are replaced with values that we assign through the MODULES (MODEL).



So for all of you PHP geeks which were not known to MVC I think this is enough to see the power you get from this framework... if you don't see it I will mention some things:

- You get a FRAMEWORK for every project you build to use
- It is easily to upgrade and use
- You don't need to touch the files of your framework most of the times only the CONFIG file and then just start building the MODULES
- You easily will redesign the site because of the templates you use
- You write without caring about includes paths or other stuff
- and if you write this good (not that this isn't good but this piece of code is not what it is now at the project we have used it... yes this was working code :) now it is more advanced with more lines of code and complexity but this is its main idea) you will develop you projects twice as fast as you usually do and believe me when I say YOU GOT THE POWER OF Objects AND Templates AND Re-Usability OF CODE and this is what most programmers have difficulties to achieve.

But YES this isn't a topic that I can cover in a hour or too just like this and yes I am not good at large scale Articles which cover future and history and so on so just look at what wikipedia has to offer about this topic... I'll ease you with this direct link to MVC at wikipedia.

I hope I have given you the first steps and thoughts about building your own MVC whether in PHP or some other programming language.
Have fun!
And remember not to hate your code but to have fun with it ;)

Прочети цялата статия...

Friday, January 05, 2007

Basic Recursion

I found out that many programmers that are not academic educated but self learners don't know recursion. And this is something that might safe your life pretty fast sometimes ... so I will drop a few lines about it and why use it.


Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition. The term is also used more generally to describe a process of repeating objects in a self-similar way. For instance, when the surfaces of two mirrors are almost parallel with each other the nested images that occur are a form of recursion.
/description from Wikipedia/

I actually find pretty confusing the example with the mirrors for someone who is hearing for the first time about recursion. So I will give one from me:
"Drawing a tree structure from the folders and sub folders of your computer hard drive is made with recursion."

So as I expect my audience to be people from the IT sector or at least people generally known to software or programming at least at a basic level I will give an example of this with web based category navigation.

So we have something like 1 is the root of 2 and 3.
And 2 is the root of 4.
It looks like this:
1
|-2
_|-4
|-3


php code example:




// Making the function to draw the tree ***RECURSION IN MIND***
function tree($id='0',$spacer="          "){
$query = "SELECT * FROM categories WHERE parent_id='$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo $spacer.'img src="images/folder.png" border="0" /> '.
$row['title'].'   '.
'a href="index.php?module=ADMIN">'.'add'.'/a> | '.
'a href="index.php?module=ADMIN" style="font-size:9px;">'.'edit'.'/a>
';
// The RECURSION
tree($row['id'],$spacer."          ");
}
}

// Calling the function
tree();





This is old code that I posted accidentally without looking at it that it is not recursion sorry about this... I will leave it in case someone find it useful ;)



public function navigation($id) {
$navigation = '';

$this->initdb();
$sql = "SELECT `id`,`name`,`description`,`parent_id`
FROM `category`
WHERE `id` = '$id'
LIMIT 1";

$res = $this->db->query($sql);
$row = $res->fetchRow(MDB2_FETCHMODE_ASSOC);
$navigation .= $row['name'];
$parent_id = $row['parent_id'];

while($parent_id != 0) {
$sql = "SELECT `id`,`name`,`description`,`parent_id`
FROM `category`
WHERE `id` = '$parent_id'
LIMIT 1";

$result = $this->db->query($sql);
$row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);

// REVERSE THE BUILD
$navigation = $row['name'].' > '.$navigation;

$parent_id = $row['parent_id'];
}

//$this->checkPearError($result);
return $navigation;
}






I hope that the example is clear to understand... for those with PHP and MySQL knowledge it shouldn't be a problem even if they never used the MDB2 pear package.
Recursion is very useful in those situations where you need repetitive work.

This is working code from a project I participate in and this chunk is written by me :-p
So yes it actually works ;-)

So I hope I gave light on this topic!
Good night folks.

Прочети цялата статия...