Archive for August, 2008

SEOmoz Guy, PHP doesn’t suck really

I agree, PHP, is easy to learn, use and abuse and makes many people who don’t know anything about server and web development feel like experts, but that doesn’t mean PHP sucks, those developers suck.

Recently I read on SEOmoz:

There is no mileage in buying vBulletin for $160. It can’t be any good at that price - and is probably written in PHP. You are looking for a cool project to write in Ruby and here’s your chance.

Just in case the author doesn’t know, here is a list of sites that are powered by PHP:
1 - Facebook (http://www.facebook.com/index.php)
2 - Wikipedia (http://en.wikipedia.org/wiki/Index.php)
3 - Yahoo! bookmarks (You have to login)
4 - Stumbleupon (http://www.stumbleupon.com/index.php but redirects to http://www.stumbleupon.com/)
5 - SEOmoz itself! (http://www.seomoz.org/index.php)
6 - Flickr (http://www.niallkennedy.com/blog/uploads/flickr_php.pdf Flickr even uses Smarty template engine!)
There are more but I think this is enough.

Now vBulletin which is also written in PHP, is a state of the art forum software that is running some of the biggest communities on the web such as:
1 - Digital Point
2 - Site Point
3 - RC Groups
etc. ect.

That’s all.

Archived under Annoying Stuff, PHP, Web Development Comments

Windows Vista pisses me off

Last night I was doing some stuff and had all kinds of open apps.
I went away for like 15 minutes and apparently Windows Vista updated itself and restarted my computer!!!
It probably told me that it’s going to do it but the fact that it just goes ahead and does it is really stupid.

I don’t know who in Microsoft makes these design decisions but it makes me angry that they don’t respect the user.

The reason behind it might be that the updates are important for security or all the other problems Vista has but it’s stupid and it shouldn’t restart my computer without my permission.

It also tries to remember what you where doing but in a retarded way and I lost stuff.

I’m really considering moving to Linux and trowing this piece of crap operating system into trash.

Archived under Annoying Stuff, General Comments

Don’t upgrade to Internet Explorer 8 beta, yet

Yes, many people did and they are complaining.
It’s a beta product and it’s not meant to be for users. You can safely (well…) upgrade to Internet Explorer 8 when it’s not beta anymore.

It has so many issues, Internet Explorer 7 has so many problems already and I can’t imagine what sort of issues Internet Explorer 8 “Beta” has…

Here are some stories:
http://news.cnet.com/8301-10805_3-10028458-75.html

The definition of beta software:
http://en.wikipedia.org/wiki/Software_release_life_cycle#Beta

Beta software is for users who want to participate in testing an unfinished product.

Archived under Annoying Stuff, General, Web Browsers Comments

Adding Auto Login (Remember Me) Capability to Your Applications

Here are the steps:

1 - You need to add a field to your login form, preferably a checkbox and name it “remember” (or whatever).

2 - We need a way of recognizing users computer, to do this you will need to add an extra field to your user table and name it something like “token”:

ALTER TABLE YOUR_USER_TABLE ADD token VARCHAR(40);
ALTER TABLE YOUR_USER_TABLE ADD INDEX(token);

(We need the index for fast lookup)

You will also need another column to save the user agent:

ALTER TABLE YOUR_USER_TABLE ADD user_sig VARCHAR(40);

This is for security. (I will explain this in a little bit)

3 - We will also have to save a cookie on users computer; after you logged the user in successfully you will need something like this in your login script:

if (LOGIN_VALID()) {
   /* Log user in here first */
   if (isset($_POST['remember'])) {
       $token = md5(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
       $user_sig = md5('SOME SECRET SEED' .$_SERVER['HTTP_USER_AGENT']);
       mysql_query("UPDATE YOUR_USER_TABLE SET token = '$token', user_sig = '$user_sig' WHERE USER_ID_FIELD = USERS_ID");
       $cookie_name = 'A SHORT NAME FOR THE COOKIE';
       $cookie_value = $token;
       $cookie_expire = time() + 60 * 60 * 24 * 30 * 12 * 10; /* Approx 10 years */
       $cookie_path	= '/';
       $cookie_domain = $_SERVER['SERVER_NAME']; /* If this didn't work, put your domain name here */
       setcookie($cookie_name, $cookie_value, $cookie_expire, $cookie_path, $cookie_domain);
   }
}

What this does is that it generates a token to be saved on user’s computer as a cookie, and also for security reasons, it generates a request signature out of user’s browser user agent and saves them both in your database.
It also sets a cookie on user’s computer with the token only.

4 - Now you will need to place something like this in your main include file:

if (!isset($_SESSION['valid_user']) && isset($_COOKIE['A SHORT NAME FOR THE COOKIE']) && trim($_COOKIE['A SHORT NAME FOR THE COOKIE']) != '') {
    $token = mysql_real_escape_string($_COOKIE['A SHORT NAME FOR THE COOKIE']);
    $user_result   = mysql_query("SELECT * FROM YOUR_USER_TABLE WHERE token <> '' AND token = '$token'");
 
    if ($user_result && mysql_num_rows(user_result) > 0) {
        $user = mysql_fetch_assoc($user_result);
        if ($user['user_sig'] == md5('SOME SECRET SEED' .$_SERVER['HTTP_USER_AGENT'])) {
             /* Go ahead and log the user in again */
             $_SESSION['valid_user'] = $user;
             session_regenerate_id(); /* Always good idea */
        }
    }
}

This script will check and see if the user is already logged in and if he/she is already logged in then it won’t go through all the trouble to log the user in again.
It also checks for existence of the cookie you saved on users computer before.

If all the conditions are true then the script will checks the token and user’s signature and if everything matches, it will log the user in.

5 - There is also one last step: Clean up. In your *logout* script, place:

       $cookie_name = 'A SHORT NAME FOR THE COOKIE';
       $cookie_value = '';
       $cookie_expire = time() - 60 * 60 * 24 * 30 * 12 * 10; /* Approx 10 years ago */
       $cookie_path	= '/';
       $cookie_domain = $_SERVER['SERVER_NAME']; /* If this didn't work, put your domain name here */
       setcookie($cookie_name, $cookie_value, $cookie_expire, $cookie_path, $cookie_domain);

This will delete the cookie from user’s computer when the user logs out.
If you don’t do this, your application will keep logging the user in even after he/she logs out.

The same concept will work in other languages.
Also this script only relies on the user agent to double check everything, you might want to take extra security measures…

I hope this helps someone :)

Archived under PHP, Web Development Comments

Password Support for Jeditable, a Cool jQuery Plugin

Here is the original plugin:
http://www.appelsiini.net/projects/jeditable

It let’s you implement inline editing capabilities and it’s supported by major browser.
Here are some examples:
http://www.appelsiini.net/projects/jeditable/default.html

An example usage is like this:

$(".edit_area").editable("http://www.example.com/save.php", { 
         type      : 'textarea',
         cancel    : 'Cancel',
         submit    : 'OK',
         indicator : "<img src='img/indicator.gif'>",
         tooltip   : 'Click to edit...'
     });

The problem is, it doesn’t support password input types, but here is how to add this support.

1 - Open the plugin file.
2 - Find this code:

text: { 
	element:function(settings,original) {
		var input=$('<input>');
		if(settings.width!='none') {
			input.width(settings.width);
		}
		if(settings.height!='none') {
			input.height(settings.height);
		}
		input.attr('autocomplete','off');
		$(this).append(input);
		return(input);
	}
},

3 - Add this after that:

password: { element:function(settings,original) {
		var input=$('<input type="password">');
		if(settings.width!='none') {
			input.width(settings.width);
		}
		if(settings.height!='none') {
			input.height(settings.height);
		}
		input.attr('autocomplete','off');
		$(this).append(input);
		return(input);
	}
},

Now you can do:

$(".edit_area").editable("http://www.example.com/save.php", { 
         type      : 'password',
         cancel    : 'Cancel',
         submit    : 'OK',
         indicator : "<img src='img/indicator.gif'>",
         tooltip   : 'Click to edit...'
     });

It’s odd that the developers didn’t add this capability…

Archived under AJAX, JavaScript, Web Development Comments (3)

Fading images with Fireworks

Here is how to do it:

1 - Open your image
2 - On the top menu, go to Commands > Creative -> Fade Image
3 - A dialog box will open, choose the kind of fading effect that you want
4 - Click OK
5 - If you select your image, you will see a line with a dot and a rectangle on each side, hold the dot and move it around and experiment. Use the rectangle to move the whole effect around and the dot to resize it and change it’s direction.

Enjoy :)

Archived under Web Design, Web Graphics Comments

Fixed font sizes on Firefox 3

In Firefox 2, you couldn’t have a fixed font size, as soon as a user zoomed on your page, where ever you had a fixed font, it would get bigger and ugly.
So I used to use images for menus in form of CSS sprites.

But in Firefox 3, they fixed this issue.

Now, I find those arguments about how it was OK to blow the web pages and how it made sense, blah blah, pathetic!

Archived under CSS, HTML, Web Design Comments

Programming Paradigms 5; Linear Search and Stack

This one is about linear search and stack within the C programming language.

It’s great :)

Archived under Assembly Programming, C Programming Comments

Secret Places on Google Earth

If you haven’t seen Google Earth yet, go ahead and download and install it here:
http://earth.google.com/

After you are done, put these coordinates in the search box (on top left):

1-
50° 0′38.20″N 110° 6′48.32″W

This one is really cool but it looks like it’s random.

2-
19°56′58.08″S 69°38′2.25″W
(Zoom in a little bit)

Now, this one is not random, it was made by someone, some say Mayans but remember, they couldn’t fly so I think making something like this that only someone in the air can see would be their last thought… Correct me if I’m wrong, I can’t find anything about this on the internet.
Honestly, it looks like an alien to me :)

3-
45° 7′25.87″N 123° 6′48.97″W
(Zoom in a little bit)

:) The Firefox logo!

4-
38°31′43.91″N 76°34′0.80″W
(Zoom back and forth a little)

5-
31°39′40.82″N 106°35′26.02″W

6-
37°33′49.94″N 116°51′3.91″W

7-
45°42′12.73″N 21°18′7.53″E

Archived under Fun, General Comments

Programming Paradigms 4; More Pointers, Arrays and Structures

By Professor Jerry Cain.

Archived under Assembly Programming, C Programming Comments

The perfect meta description for your site

You may have noticed that in search result pages (SERPs) of Google, there is a two line description:

Google uses (most of the time) your meta description (if it thinks it’s more relevant) and if your description is too long, it will cut it and show 3 dots at the end:

If you don’t want this ti happen, write a good description that is only 155 characters long, for example, in this case the description fits perfectly:

So when writing a meta description remember: (in no particular order)

1 - Write a meta description that is 155 characters long. (or less, obviously)
2 - Write a meta description that is descriptive.
3 - Write a meta description that is provocative.
4 - Use your primary keyword(s) in it, don’t write a stream of keywords, write something meaningful.

Archived under SEO, Search Engines Comments

How to fix: Warning: Invalid argument supplied for foreach()

This warning happens only if you try to use foreach on a non array like:

$myvar = 10;
foreach ($myvar as $value) {}

If you run this, you will get:

Warning: Invalid argument supplied for foreach() in YOUR_FILE on line FOREACH_LINE

To fix this just cast $myvar to array like this:

$myvar = 10;
foreach ((array) $myvar as $value) {}

Archived under PHP, Web Development Comments

You can in fact use foreach to change array elements in PHP

Recently I read somewhere that you can’t do this and you have to use this awful syntax:

foreach ($array as &$value) {}

This is only valid in PHP5 and can have very bad consequences for example run this piece of code:

<pre><?php
$array = array(1, 2, 3, 4, 5);
foreach ($array as &$value) {
	echo "$value \n";
}
echo "\n\n";
foreach ($array as $value) {
	echo "$value \n";
}
?>

Here first foreach loop is foreach by reference but the second one is a normal foreach loop.
Run it and see what happens.

The way to change the elements using foreach is very simple actually, the only thing you need is a $key along with the $value!

/* Filter the input */
foreach ($_POST as $key => $value) {
   $_POST[ $key ] = trim(strip_tags($value));
}

Archived under PHP, Web Development Comments

A PHP form obfuscator; secure and spam free PHP forms

[ D O W N L O A D ]

Example usage:

<?php
 
	require_once 'class_obfuscator.php';
 
	$form_fields = array('username', 'password', 'email');
	$obfuscator  = new Form_Obfuscator($form_fields);
	$obfuscator -> set_secret_key('My Secret Key - ET8439FSKJ - EDIT THIS');
 
	if( empty($_POST) ) {
		$fields   = $obfuscator	-> obfuscate();
		$enc_form = $obfuscator	-> encode_form();
		?>
<form action="" method="post">
	Name:<br /><input type="text" name="<?php echo $fields['username']; ?>" /><br /><br />
   Password:<br /><input type="password" name="<?php echo $fields['password']; ?>" /><br /><br />
   Email:<br /><input type="email" name="<?php echo $fields['email']; ?>" /><br /><br />
   <input type="submit" />
   <input type="hidden" name="__A" value="<?php echo $enc_form; ?>" />
</form>
      <?php
	} else {
		foreach($_POST as $key => $value) $_POST[ $key ] = trim(strip_tags($value)); /* Filter input */
		$form = $obfuscator -> decode_form($_POST['__A'], $_POST);
 
		foreach($form as $key => $value) $form[ $key ] = htmlentities($value, ENT_QUOTES, 'utf-8'); /* Escape output */
		echo "Username: {$form['username']}<br />
				Password: {$form['password']}<br />
				Email: {$form['email']}";
	}
 
?>

This is a class I developed a while back while working on a project of mine and we already know that it’s very effective.

In order to understand what it does you need to first understand how a browser sends a POST request.
When a user submits a form, browser sends something like this to the server:

POST /somepage.php HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: THE LENGTH

username=blah&password=blah&email=some_email

There are 2 problems with this:

1 - Someone along the way can view the password and email address by looking at the packets that are going to the server. (take a look at Wireshark software)

2 - You can send automatic queries to servers, for example automated spam through contact forms works like this. (some spam software can also read Captcha images so you need more protection)

The class I developed will change this POST request to something like this:

POST /somepage.php HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: THE LENGTH

JDF8W9JHF=blah&OEROWF83=blah&VLKDSFOE=some_email

Note that the field names are changed to random strings, and they also change every time the form is shown, so:

1 - Even if a user in the middle can see the packets, he/she won’t know that OEROWF83 stands for “password”.

2 - A spam software won’t have a way of guessing the field names because they are random every time. There is also a secret encryption key which you only know what it is.

Questions and comments are welcome :)

Archived under PHP, Security, Web Development Comments (5)

Programming Paradigms 3; Arrays and Structures

In this lecture, Professor Jerry Cain explains arrays and structures and their internal representations.

Archived under Assembly Programming, C Programming Comments

Better PHP Applications

Developing better applications requires practice and study but there are little things you can do while you develop your applications that will help.

One of the things I think is very important and all great PHP developers do this is developing your application with error_reporting(E_ALL);

You have to simply place these lines on top of your PHP source files: (or put it on top of your common include file, hopefully you have one)

ini_set('display_errors', 1); /* Output all errors as oppose to logging them */
error_reporting(E_ALL);     /* Show all errors */

What this does is that it will ask PHP to show you all the errors (almost, later on this) such as warnings and notices. (It is most likely that PHP is already set to show you parser and fatal errors.)

Warnings are very important to address, they are run time errors but the compiler doesn’t halt the execution of the script.
Notices are most likely logical errors (in my experience). If you develop with error_reporting set to E_ALL you will see that PHP was telling you where the problems that took you 5 hours to find were all along.

Here is how to produce a notice and how it can help you with some problems.

Suppose you have this self submitting form:

<?php
error_reporting(0);
 
if (isset ($_POST['name'])) :
 
?>
 <form action="" method="post">
 Enter your name: 
 <input type="text" name="name" /><br />
 <input type="submit" />
 </form>
<?php
 
else: /* This is the alternate PHP syntax */
 
    echo 'Hello and welcome ' .htmlentities($_POST['name1'], ENT_QUOTES);
 
endif; /* This syntax will make your templates more readable */
?>

This won’t work, you might have spotted the issue but if you didn’t, you will see that this doesn’t work.
What it does is it turns error reporting off completely on line 2 and this is where the problem is (well, not the problem itself) because if you change line 2 to:

echo 'Hello and welcome ' .htmlentities(@$_POST['name'], ENT_QUOTES);

@ will tell the compiler that you know already what’s going on and the compiler won’t show the notice.

After you are done developing your application and ready to launch it, you will replace error_reporting(E_ALL); with error_reporting(0); to turn this off so the PHP compiler won’t show anything at all.

Better yet I suggest to do something like this:

ini_set("display_errors", 0); 
ini_set("log_errors",     1); 
ini_set("error_log",      "path/to/php.log"); 
error_reporting(E_ALL);

This will set the PHP to log errors rather than displaying them to the user and I suggest that you visit that error log every once in a while.

This way if your application crash or your users report strange things you will be able to check your log and possibly find some notices ;)

Also one of the reason you don’t want users to see PHP errors is that PHP will show the error and a path to the file that the error was occurred and some information about the error.
This could help malicious users identify your application’s file and folder structure and give them some clues on how they can exploit your application.

Happy Coding :)

Archived under PHP, Web Development Comments

Programming Paradigms 2; Data Types

This is the second video of “Programming Paradigms” course, Stanford by Professor Jerry Cain.
This one is about C data types and how your computer stores and converts different data types internally:

Enjoy :)

Archived under Assembly Programming, C Programming Comments

Programming Paradigms 1; Introduction

I found these great videos on Youtube that are lectures of a programming course in Stanford by Professor Jerry Cain.
This first one is the introduction of the course

I will post them as I watch them.

Enjoy :)

Archived under Assembly Programming, C Programming Comments

Steve Jobs’ 2005 Stanford Commencement Address

Thank you, thank you!

Archived under General Comments

A robot that is controlled by real living brain cells!

Archived under Artificial Intelligence Comments

« Previous entries