debuggable

 
Contact Us
 
41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49

Besiege Empty(), Isset() & Co. With This Great Syntax Cheatsheet

Posted on 22/6/07 by Tim Koschützki

Today I stumbled upon this great php syntax sheet cheat that displays to you all possible outputs of gettype(), empty(), is_null(), isSet() and (bool) for a whole range of different syntaxes for value assignments etc. This is definitely a must-read when you are like me and simply cannot grasp how these functions operate on different datatypes for different values!

The cheatsheet also contains valuable information about the different types of comparisons between strings, strings and integers, strings and floats, etc. using the equality operator (==) and the identity operator (===). You get the idea.

Awesome work there!

 

Win All The Chicks By Sticking To Coding Standards

Posted on 19/6/07 by Tim Koschützki

Coding Standards are extremely important in programming environments. They not only allow you to build a consistent code base, but also make your overall life a lot easier. Join me and find out how you can lay out the foundation for your new car/house/chick.

Five Reasons Why You Should Stick To Coding Standards

1. You Will Have A Consistent Codebase

Coding Standards help you have a consistent code base. If everything looks similar, you will easily feel home looking at your code. Try it out today and you will see for yourself that you feel much more motivated if everything looks clean and in shape. Programming is such a sophisticated task. Don't work hard - work smart! Use every tool available to make your life easier. Enforcing code conventions is one such tool.

2. You May Not Get The Help You Deserve

If you are in irc channels or on forums, you will be represented by your code. If you are in desperate need of help, people will want to see some of your code. If your code looks cumbersome and inconsistent, people will ask you "gwaa..refactor that code first young grashopper!", which takes time to repost on the forum (for example). Do it right the first time, save some time, present yourself in a better way and finally get the help you deserve.

3. Clean Code Prevents Hair Loss

hairloss2.jpg I cannot count the number of times when I looked for a small typo in a PHP script back when I was very young and coding conventions meant as little as possible to me (half of that). Coding Conventions help your debugging. They allow you to scan your code and find parse errors and notices (possibly from uninitialized variables) a lot faster. In short, coding standards prevent hair loss later in your life. Studies tell that a programmer is using up at least one third of his time with debugging. Why should you make it unnecessarily uneasy?

4. Others Will Recognize Your Will To Write Good Code

This trully goes alongside 2. However, I want to emphasize it a bit more: If the person above you is a bit angry, because you forgot (again) to triple-test your code before you checked it in (or at least forgot to make all automatic tests pass), coding standards can help you rebuild your reputation. I notice it often in my workplace. When somebody checked some untested code in, he will try to really enforce coding conventions in his code so the person above us recognizes it. Of course, your chief programmer may be different, but generally, this should help a bit.

5. Coding Standards Will Help You With Your Next [Car|House|Chick]

If you can debug code faster, feel home editing your code, get all the help you deserve and people recognize your good intentions you will feel a lot more relaxed. You will have fun with your work, with your colleagues and all other things in your life. This is the ultimate foundation for more money, general success, your new car or a new woman in your life. Okay, the latter may apply only to those who are feeling unlucky with their partner. :)

Use Coding Conventions and be happier in your life. :)

Which Coding Conventions Do You Recommend?

For this article I have looked at some sources for coding standards - especially to find out new ways of improving my own code. However, the ones that I use most often, at least in private projects (at my workplace I have to use others), are the ones from The CakePHP Foundation. Quelle surprise!

This document is simple and down to the point. For most coding situations there is a good way explained which formatting and intendation you should use. Please look at it and tell me what you think. I am eager to learn about new ways to organize my code. So should you.

Happy (clean) coding all!

 

Screencast #1: Using vendor branching and CakePHP

Posted on 17/6/07 by Felix Geisendörfer

Hi folks,

a long time ago I promised to do a screencast on unit testing. So as I sat down and tried to record it I noticed that it was quite an ambitious project. If you've never tried it then let me tell you: Doing a good screen cast is difficult. I've got deep respect for the people capable of doing so and I am in no way feeling qualified to join their league as of right now ; ). So I ended up giving up on the unit testing screencast for now and decided to start with something easier to get some experience first before trying to do difficult programming and entertaining talk at the same time as my early results where disastrous ... ^^.

So here I go with my very first screencast to be published. The topic is how to use vendor branching with CakePHP which is one of many ways to keep your CakePHP version up to date.

To follow this screencast and try things at home you'll need:

  • Windows OS (Sorry my dear Linux + Mac users, crank up your emulators)
  • TortoiseSVN: The best subversion client there is, download here.
  • Basic SVN knowledge, tolerance for my German accent and localized version of Windows
  • Most likely have to leave your RSS reader and visit this post directly

Feedback is welcome and I recommend you to watch in fullscreen mode as the screencast was recorded in 800x600 and I only had room for 720x540 here on my blog.

So here comes the screencast (16:45 minutes, 120 MB):

The player will show in this paragraph

If you want to download the FLV file, please use this link: Download screencast

-- Felix Geisendörfer aka the_undefined

 

Composing Methods: Replace Temp With Query

Posted on 14/6/07 by Tim Koschützki

When you are using a temporary variable to hold the result of an expression, extract the expression into a method. Then replace all references to the temp with the new method. The new method can then be used in other methods.

Motivation

The problem with temps is that they are temporary and local. Since they can be seen only in the context of the method they are in, temps tend to encourage longer methods, which is something we want to avoid. By replacing the temp with a query method you can easily ensure that all other methods of your PHP class can get the information that was previously held by the temporary variable.

Of course there are different forms of this. In one case the expression that generates the contents for the temp is free of side effects. You can simply copy that expression to the query method. Other cases are trickier.. for example if the temp is to collect a result, for example by summing over a loop, you need to copy some logic (the entire loop) into the query method. Sometimes a loop is to calculate multiple values. Here you need to duplicate the loop for each temp and then use "Replace Temp With Query" on each of them. As you can guess, there is a thin border to repetitive source code.

Mechanics

Here is a simple case:

  1. Look for a temporary variable that is assigned to once.
  2. Extract the right-hand side of the assignment into a method. Initially mark the method as private - you can easily relax the protection later.
  3. Ensure the extracted method is free of side-effects, meaning it does not modify any object.
  4. Run your tests.
  5. Use Inline Temp on the temporary variable.

Code Examples

Before

function calcTax() {
   $basePrice = $this->amount * $this->quantity;
   if ($basePrice > 3000)
       return $basePrice * 0.93;
   else
       return $basePrice * 0.95;
}

After

function calcTax() {
   if ($this->basePrice() > 3000)
       return $this->basePrice() * 0.93;
   else
       return $this->basePrice() * 0.95;
}

function basePrice() {
      return $this->amount * $this->quantity;
}

As you see we perform the calculation of the base price several times here. You may be concerned with performance issues. However, be aware that nine times out of ten it will not matter. When it does matter, you will fix the problem during your optimisation stage. With your code being refactored you will often find even better optimisation strategies which you would have missed without refactoring, so the refactoring pays for itself already. If you are at the worst case, you can easily put the temp back, anyway.

Have a good one, folks! :)

 

Introduction To PHP Security Vulnerabilities

Posted on 12/6/07 by Tim Koschützki

PHP has allowed people with all sorts of backgrounds to put their ideas on the web. With several hundred million webpages programmed in PHP, security plays a big deal for us webprogrammers. In this introduction I will outline the most common security vulnerabilities in PHP scripts. Tutorials on how one can prevent them will be dealt with in articles dedicated to each vulnerability.

All Input is Tainted

As a programming language, PHP generates output (HTML, Headers, Files and the like) based on User Input supplied by the url, cookies, the session data, forms, file uploads.
It is an absolute must that you regard every input supplied by a user as potentially unrelieable. When you operate on user-provided input, you have to validate it before you use it in your system.

By the time input reaches PHP, it's passed through the user's browser, any number of proxy servers and firewalls, filtering tools on your server and possibly other processing modules.
Any of those have an opportunity to corrupt your input - be it intentional or not. As the input ultimately comes from your user, it could have been corrupted in pure malice to push the limits of your application or undeliberately.
There is no universal solution that validates all input. We will learn about the most common ones in a later article where we examine all security vulnerabilities explained here in detail.

Cross-Site Scripting

Cross-Site Scripting (XSS) is one of the most common vulnerabilities of web applications. In such an attack the hacker stores unwanted code, be it Javascript, CSS or HTML, in the victim's database.
Later, when the content is fetched from the database and displayed to the visitor, it alters the page or runs some code that either distorts the overall layout, exploits and steals user's cookies or redirects confidential information like the session id to third-party sites and software.

XSS is very popular and easy-to-do. It only requires basic knowledge of javascript and / or HTML and CSS. There are two forms of XSS exploits: direct action and stored action. The former gains insight about the application whereas the latter, the more dangerous one, tries to steal identities for subsequent exploits towards site users or the site itself.

The simplest XSS attack would be inserting a <blink> tag into a form which has no html tag validation. It could make the entire website to blink awkwardly. :)

SQL Injection

SQL Injection is also a very popular vulnerability that is caused by inconsequent input validation. Unlike XSS Sql Injection is directed at the site itself and can be extremely dangerous, resulting in your entire database being deleted.

The goal of SQL Injection is the insertion of arbitrary data into a string of which the hacker knows that is going to be used in an SQL statement - for example the username of a login form. The malicious query may retrieve
data that otherwise requires authentication, modify or even remove data from the database.

Example

Suppose you have such a login form with a name and a password input field. Now when the form is sent via POST, think about what the following code does:

mysql_query("SELECT * FROM users WHERE name='{$_POST['name']}'");

At first glance it looks okay. However, when the hacker puts "john'; DELETE FROM users;'true" into the name field, the following Query will be executed:

[sql]
SELECT * FROM users WHERE name='john'; DELETE FROM users;'true'
[/sql]

The execution of this query causes all users to be deleted. Now using MySQL's query stacking option will prevent the system from executing multiple sql queries at one mysql_query() call. However, other database systems like PostgreSQL might not.

Code Injection

Code Injection can be the most dangerous attack that can affect a PHP script. This attack is also caused by a lack of input validation.

The core of this attack method is most often PHP's register_globals ini setting, which allows to register variables supplied by $_POST, $_GET and the like as direct PHP variables. Most servers turn register_globals off
by default, which is good. However, some still keep it on.

If a script loads an external script based on user input (that is not validated), an attacker can hijack the site's infrastructure by supplying an arbitrary local or remote filename.
If register_globals is on, this may cause code to be injected into the site, which modifies the database, explores data, scripts and files or compromises the entire system.

Take every possible opportunity to eliminate this vulnerability. In a subsequent article I will show you how it is done.

Command Injection

Command Injection exploits PHP's dependency on external resources. For example for some task the myriad of php functions and extensions is not enough and you depend on a local windows or linux command.

The external command-line utility doc2pdf is commonly used to convert uploaded Word-documents into pdf files. The name of the uploaded file in the following script is not validated and thus may contain all sorts of funny characters:

$dest = basename($_FILES['uploaded']['name'],'.doc');
shell_exec("doc2pdf {$_FILES['upload']['tmp_name']} {$dest].pdf");

One of such funny characters are semicolons which separate commands on the command line. If the filename was "somefile; locate * |rm -rf" the shell converts somefile and then removes all files writeable by the web server.
We will see in a later article how you can avoid such an attack.

Session And Cookie Security

Sessions are very helpful to track a user. Sessions maintain an online identity. Therefore, it's disastrous if people steal that identity, performing all sorts of actions that only the original identity had priviledges to perform.

As PHP heads more and more into Enterprise Applications where sensitive data is present, session security is absolutely essential. By exploring how sessions work you can forsee possible attacks. We will see in a dedicated article how this is done and how securing Cookies is done.

Securing File Access

All PHP scripts depend on other files in one form or the other. No matter the size of your application it is vital to maintain the proper access restrictions. Failing to protect files can make it very easy for hackers to compromise the entire system.

In most cases the PHP interpreter has the same user ID as the webserver. Files uploaded by scripts are owned by the developer's user account. Due to differing users, it's not possible to set secure file permissions (0600 for files and 0700 for directories), since the permissions
would prevent the server from being bale to access those files. Do we have to make these files world-readable? We will see in a later article.

Conclusion

These are the most common PHP vulnerabilities., shortly outlined in a compact article. I will write dedicated articles about each of those later where you learn how to prevent them. Those articles will be packed
with many code examples, I am sure many of you have not seen yet. Stay tuned!

 
41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49